-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostTreatPlan4res.py
3005 lines (2658 loc) · 135 KB
/
PostTreatPlan4res.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
## Import packages
import pandas as pd ## necessary data analysis package
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.dates as mdates
import numpy as np
import yaml
import os
import math
import os.path
import pyam
from itertools import product
import sys
from shapely import wkt
from p4r_python_utils import *
OE_SUBANNUAL_FORMAT = lambda x: x.strftime("%m-%d %H:%M%z").replace("+0100", "+01:00")
# definition of seasons - this is used to aggregate variables per seasons
spring = range(80, 172)
summer = range(172, 264)
fall = range(264, 355)
def season(x):
if x in spring:
return 'Spring'
if x in summer:
return 'Summer'
if x in fall:
return 'Autumn'
else :
return 'Winter'
p4rpath = os.environ.get("PLAN4RESROOT")
print('p4rpath',p4rpath)
path = get_path()
logger.info('path='+path)
def abspath_to_relpath(path, basepath):
return os.path.relpath(path, basepath) if os.path.abspath(path) else path
nbargs=len(sys.argv)
if nbargs>1:
#settings_posttreat=abspath_to_relpath(sys.argv[1], path)
settings_posttreat=sys.argv[1]
if nbargs>2:
settings_format=sys.argv[2]
#settings_format=abspath_to_relpath(sys.argv[2], path)
if nbargs>3:
settings_create=sys.argv[3]
#settings_create=abspath_to_relpath(sys.argv[3], path)
else:
settings_create="settingsCreateInputPlan4res.yml"
else:
settings_format="settings_format.yml"
else:
settings_posttreat="settingsPostTreatPlan4res.yml"
print("settings_posttreat",settings_posttreat)
print("settings_posttreat",os.path.join(path,settings_posttreat))
# read config file
cfg={}
# open the configuration files
with open(os.path.join(path, settings_posttreat),"r") as myyaml:
cfg1=yaml.load(myyaml,Loader=yaml.FullLoader)
with open(os.path.join(path, settings_create),"r") as mysettings:
cfg2=yaml.load(mysettings,Loader=yaml.FullLoader)
with open(os.path.join(path, settings_format),"r") as mysettings:
cfg3=yaml.load(mysettings,Loader=yaml.FullLoader)
cfg = {**cfg1, **cfg2, **cfg3}
if 'partition' in cfg.keys():
if 'Continent' in cfg['partition'].keys():
cfg['partition']['continent'] = cfg['partition']['Continent']
# replace name of current dataset by name given as input
if nbargs>4:
namedataset=sys.argv[4]
if 'path' in cfg:
cfg['path']=cfg['path'].replace(cfg['path'].split('/')[len(cfg['path'].split('/'))-2],namedataset)
else:
#cfg['path']='/data/local/'+namedataset+'/'
cfg['path']=os.path.join(path, 'data/local', namedataset)
logger.info('posttreat '+namedataset)
TimeStepHours=cfg['Calendar']['TimeStep']['Duration']
#cfg['dir']=cfg['path']+cfg['Resultsdir']
cfg['dir']=os.path.join(cfg['path'], cfg['Resultsdir'])
#cfg['inputpath']=cfg['path']+cfg['inputDir']
cfg['inputpath']=os.path.join(cfg['path'], cfg['inputDir'])
#if 'configDir' not in cfg: cfg['configDir']=cfg['path']+'settings/'
if 'nomenclatureDir' not in cfg:
cfg['nomenclatureDir']='scripts/python/openentrance/definitions/'
# if cfg['USEPLAN4RESROOT']:
# cfg['nomenclatureDir']='/scripts/python/openentrance/definitions/'
# else:
# logger.error('\nnomenclatureDir missing in settingsCreateInputPlan4res')
# log_and_exit(1, cfg['path'])
print("cfg[nomenclatureDir]",cfg['nomenclatureDir'])
print("p4rpath=",p4rpath)
cfg['nomenclatureDir']=os.path.join(p4rpath, cfg['nomenclatureDir'])
print("cfg[nomenclatureDir]",cfg['nomenclatureDir'])
# if cfg['USEPLAN4RESROOT']:
# path = os.environ.get("PLAN4RESROOT")
# cfg['dir']=path+cfg['dir']
# cfg['inputpath']=path+cfg['inputpath']
# cfg['path']=path+cfg['path']
# cfg['nomenclatureDir']=path+cfg['nomenclatureDir']
cfg['dayfirst']=cfg['Calendar']['dayfirst']
cfg['BeginDataset']=cfg['Calendar']['BeginDataset']
#if 'pythonDir' not in cfg:
# if cfg['USEPLAN4RESROOT']:
# cfg['pythonDir']='/scripts/python/plan4res-scripts/settings/'
# else:
# logger.error('pythonDir missing in settingsCreateInputPlan4res')
# log_and_exit(1, cfg['path'])
cfg['pythonDir']=os.path.join(p4rpath,'scripts/python/plan4res-scripts/settings/')
print('pythondir=',cfg['pythonDir'])
logger.info('results in:'+cfg['dir'])
logger.info('dataset in:'+cfg['inputpath'])
# define latex functions
############################
isLatex=cfg['PostTreat']['Volume']['latex']+cfg['PostTreat']['Flows']['latex']\
+cfg['PostTreat']['Power']['latex']+cfg['PostTreat']['Demand']['latex']\
+cfg['PostTreat']['MarginalCost']['latex']+cfg['PostTreat']['MarginalCostFlows']['latex']\
+cfg['PostTreat']['InstalledCapacity']['latex']+cfg['PostTreat']['SpecificPeriods']['latex']
if isLatex:
# include list of packages
def packages(*packages):
p= ""
for i in packages:
p= p+"\\usepackage{"+i+"}\n"
return p
# include list of ticklibraries
def tikzlibraries(*tikzlibrary):
p=""
for i in tikzlibrary:
p= p+"\\usetikzlibrary{"+i+"}\n"
return p
# define list of colors
def definecolors(*color):
p=""
for i in color:
p= p+"\\definecolor"+i+"\n"
return p
# include an image
def figure(fig,caption,figlabel):
p="\\begin{figure}[H]\n\\centering\n\\includegraphics[width=\\textwidth,keepaspectratio]{"+fig+"}\n\\caption{"+caption+"}\n\\label{fig:"+figlabel+"}\n\\end{figure}\n"
return p
# include a table
def tablelatex(df,label,column_format=None,header=True,index=True):
p="\\begin{center}"
p=p+"\\small"
p=p+df.to_latex(header=header,index=index,label=label,caption=label,column_format=column_format)
p=p+"\\end{center}"
# the following is necessary if booktabs is not in the latex distribution used
p=p.replace("\\toprule","\\hline")
p=p.replace("\\midrule","\\hline")
p=p.replace("\\bottomrule","\\hline")
p=p.replace(">","$\\Rightarrow$ ")
p=p+"\n"
return p
############################################################################
# create the dictionnary of variables containing the correspondence between plan4res (SMS++) variable
# names and openentrance nomenclature variable names
vardict={}
with open(cfg['pythonDir']+"VariablesDictionnary.yml","r") as myvardict:
vardict=yaml.safe_load(myvardict)
# it may be difficult to install geopandas, this allows to skip it (not install, not use)
if cfg['geopandas']:
import geopandas as gpd
from shapely.geometry import Polygon, LineString, Point
with open(os.path.join(cfg['nomenclatureDir'], "region/countries.yaml"),"r",encoding='UTF-8') as nutsreg:
countries=yaml.safe_load(nutsreg)
with open(os.path.join(cfg['nomenclatureDir'], "region/nuts3.yaml"),"r",encoding='UTF-8') as nutsreg:
nuts3=yaml.safe_load(nutsreg)
with open(os.path.join(cfg['nomenclatureDir'], "region/nuts2.yaml"),"r",encoding='UTF-8') as nutsreg:
nuts2=yaml.safe_load(nutsreg)
with open(os.path.join(cfg['nomenclatureDir'], "region/nuts1.yaml"),"r",encoding='UTF-8') as nutsreg:
nuts1=yaml.safe_load(nutsreg)
countryFromCode={}
codeFromCountry={}
list_nuts1=[]
list_nuts2=[]
list_nuts3=[]
for elem in countries[0]['Countries']:
current_country=next(iter(elem))
current_code=elem[current_country]['iso2']
countryFromCode[current_code]=current_country
codeFromCountry[current_country]=current_code
for elem in nuts1[0]['NUTS1']:
list_nuts1.append(next(iter(elem)))
for elem in nuts2[0]['NUTS2']:
list_nuts2.append(next(iter(elem)))
for elem in nuts3[0]['NUTS3']:
list_nuts3.append(next(iter(elem)))
# loop on scenarios, years, options => post-treat and create outputs for each (scenario,year,option) triplet
if 'variants' not in cfg: cfg['variants']=['']
if 'option' not in cfg: cfg['option']=['']
for variant,option,year in product(cfg['variants'],cfg['option'],cfg['years']):
if len(variant)>0 or len(option)>0:
logger.info('treat '+variant+' '+option)
# create the paths to the different directories
# dirSto is the main directory for one (scenario,year,option)
# dirL is the same but with name of path written such that latex understands
if 'dir' not in cfg: cfg['dir']=cfg['outputpath']
cfg['dirL']=cfg['dir'].replace("/","\\")
if len(option)>0:
cfg['dirSto']=cfg['dir']+str(variant)+'-'+str(option)+'/'
elif len(variant)>0:
cfg['dirSto']=cfg['dir']+str(variant)+'/'
else:
cfg['dirSto']=cfg['dir']
# dirOUT is used to store the output files (plan4res format)
# dir IAMC is used to store the results in Open ENTRANCE format (IAMC)
# dirOUTScen is used to store outputs when post-treating individual results for one climatic scenario
# dirIMG stores the images created by this script
cfg['dirOUT']=cfg['dirSto']+'OUT/'
cfg['dirIAMC']=cfg['dirSto']+'IAMC/'
if 'SpecificPeriods' in cfg['PostTreat']:
cfg['dirOUTScenario']=[cfg['dirSto']+'Scenario'+str(i)+'/' for i in cfg['PostTreat']['SpecificPeriods']['scenarios']]
cfg['dirIMG']=cfg['dirSto']+'IMG/'
cfg['dirIMGLatex']=cfg['dirIMG'].replace("/","\\")
if not os.path.isdir(cfg['dirOUT']): os.mkdir(cfg['dirOUT'])
if not os.path.isdir(cfg['dirIAMC']): os.mkdir(cfg['dirIAMC'])
if not os.path.isdir(cfg['dirIMG']): os.mkdir(cfg['dirIMG'])
if cfg['PostTreat']['SpecificPeriods']:
for dir in cfg['dirOUTScenario']:
if not os.path.isdir(dir): os.mkdir(dir)
# these variables are used to check wether it is the first IAMC format (annual or subannual) output
# if not, the IAMC output will be merged with the already existing one
firstAnnualIAMC=True
firstSubAnnualIAMC=True
writeIAMC=cfg['PostTreat']['Volume']['iamc']+cfg['PostTreat']['Power']['iamc']+cfg['PostTreat']['MarginalCost']['iamc']+cfg['PostTreat']['MarginalCostFlows']['iamc']+cfg['PostTreat']['Demand']['iamc']+cfg['PostTreat']['InstalledCapacity']['iamc']
if 'SpecificPeriods' in cfg['PostTreat']: writeIAMC=writeIAMC+cfg['PostTreat']['SpecificPeriods']['iamc']
# list of storage assets with/without pumping
cfg['turbine']=cfg['nopumping']+cfg['pumping']
cfg['pump']=[]
for elem in cfg['pumping']: cfg['pump'].append(elem+'_PUMP')
# preamble of latex file
if isLatex:
startlatex = "\\documentclass[10pt]{report}\n"
startlatex = startlatex+packages('float','amsfonts','amssymb','amsmath','makeidx','amsgen','epsf','fancyhdr','acro','etoolbox')
startlatex=startlatex+"\\usepackage[hidelinks]{hyperref}\n"
startlatex = startlatex+packages('subfigure','lastpage','ltablex','graphicx','color','url')
startlatex=startlatex+"\\usepackage[table]{xcolor}\n"
startlatex = startlatex+packages('multirow','enumitem','cite','tikz')
startlatex=startlatex+"\\usepackage[latin1]{inputenc}\n"
startlatex=startlatex+"\\usepackage[official]{eurosym}\n"
startlatex=startlatex+"\\setlength{\\hoffset}{0pt}\n"
startlatex=startlatex+"\\setlength{\\oddsidemargin}{0pt}\n\\setlength{\\evensidemargin}{9pt}\n"
startlatex=startlatex+"\\setlength{\\marginparwidth}{54pt}\n"
startlatex=startlatex+"\\setlength{\\textwidth}{481pt}\n"
startlatex=startlatex+"\\setlength{\\voffset}{-18pt}\n"
startlatex=startlatex+"\\setlength{\\marginparsep}{7pt}\n"
startlatex=startlatex+"\\setlength{\\topmargin}{0pt}\n"
startlatex=startlatex+"\\setlength{\\headheight}{13pt}\n"
startlatex=startlatex+"\\setlength{\\headsep}{10pt}\n"
startlatex=startlatex+"\\setlength{\\footskip}{27pt}\n"
startlatex=startlatex+"\\setlength{\\textheight}{708pt}\n"
startlatex = startlatex+"\\begin{document}\n"
startlatex=startlatex+"\\title{"+cfg['titlereport']+"}\n\\maketitle\n"
startlatex=startlatex+"\\newpage\n\\listoffigures\n\\newpage\n\\listoftables\n\\newpage\n\\tableofcontents\n\\newpage\n"
endlatex = "\\end{document}"
bodylatex_IC=""
bodylatex_Sto=""
bodylatex_Det=""
writelatex=False
# create list of regions
##########################################################
inputdata_save = dict()
logger.info('read regions')
if os.path.isfile(os.path.join(cfg['inputpath'], cfg['csvfiles']['ZP_ZonePartition'])):
InputData=read_input_csv(cfg, 'ZP_ZonePartition')
colregion=cfg['CouplingConstraints']['ActivePowerDemand']['Partition']
list_regions=InputData[colregion].unique().tolist()
else:
logger.error('no file ZP_ZonePartition in dataset')
log_and_exit(1, cfg['path'])
# create list of technos, installed capacities and costs
##########################################################
logger.info('read installed capacity and costs')
InputVarCost=pd.DataFrame(index=list_regions)
InputStartUpCost=pd.DataFrame(index=list_regions)
InputFixedCost=pd.DataFrame(index=list_regions)
InstalledCapacity=pd.DataFrame(index=list_regions)
IsInvestedTechno=pd.DataFrame(index=list_regions)
isInvest=cfg['ParametersCreate']['invest']
listTechnosInDataset=[]
listLinesInDataset=[]
listInvestedAssets=[]
# seasonal storage mix
if os.path.isfile(os.path.join(cfg['inputpath'], cfg['csvfiles']['SS_SeasonalStorage'])):
InputData=read_input_csv(cfg,'SS_SeasonalStorage')
inputdata_save['SS_SeasonalStorage'] = InputData
listTechnosSS=InputData.Name.unique().tolist()
for techno in listTechnosSS:
if techno not in listTechnosInDataset:
listTechnosInDataset.append(techno)
df=InputData[ InputData.Name==techno ]
df.index=df.Zone
InstalledCapacity[techno]=df['MaxPower']*df['NumberUnits']
InputVarCost[techno]=0
InputStartUpCost[techno]=0
InputStartUpCost[techno]=0
if isInvest:
IsInvestedTechno[techno]=False
else: listTechnosSS=[]
logger.info('Seasonal storage technos: '+str(listTechnosSS))
# thermal mix
if os.path.isfile(os.path.join(cfg['inputpath'], cfg['csvfiles']['TU_ThermalUnits'])):
InputTUData=read_input_csv(cfg, 'TU_ThermalUnits')
inputdata_save['TU_ThermalUnits'] = InputTUData
listTechnosTU=InputTUData.Name.unique().tolist()
if isInvest:
for row in InputTUData.index:
if (InputTUData.loc[row,'MaxAddedCapacity']>0)+(InputTUData.loc[row,'MaxRetCapacity']>0):
listInvestedAssets.append( (InputTUData.loc[row,'Zone'],InputTUData.loc[row,'Name']) )
for techno in listTechnosTU:
if techno not in listTechnosInDataset:
listTechnosInDataset.append(techno)
df=InputTUData[ InputTUData.Name==techno ]
df.index=df.Zone
InputVarCost[techno]=df['VariableCost']
InstalledCapacity[techno]=df['MaxPower']*df['NumberUnits']
if 'VariableCost' in df.columns:
InputStartUpCost[techno]=df['VariableCost']
else:
InputStartUpCost[techno]=0
if 'FixedCost' in df.columns:
InputStartUpCost[techno]=df['VariableCost']/8760*TimeStepHours
else:
InputStartUpCost[techno]=0
if isInvest:
IsInvestedTechno[techno]=(df['MaxAddedCapacity']>0)+(df['MaxRetCapacity']>0)
else: listTechnosTU=[]
logger.info('Thermal technos: '+str(listTechnosTU))
# intermittent generation mix
if os.path.isfile(os.path.join(cfg['inputpath'], cfg['csvfiles']['RES_RenewableUnits'])):
InputData=read_input_csv(cfg, 'RES_RenewableUnits')
inputdata_save['RES_RenewableUnits'] = InputData
listTechnosRES=InputData.Name.unique().tolist()
if isInvest:
for row in InputData.index:
if (InputData.loc[row,'MaxAddedCapacity']>0)+(InputData.loc[row,'MaxRetCapacity']>0):
listInvestedAssets.append( (InputData.loc[row,'Zone'],InputData.loc[row,'Name']) )
for techno in listTechnosRES:
if techno not in listTechnosInDataset:
listTechnosInDataset.append(techno)
df=InputData[ InputData.Name==techno ]
df.index=df.Zone
InstalledCapacity[techno]=df['Capacity']
InputVarCost[techno]=0
InputStartUpCost[techno]=0
InputStartUpCost[techno]=0
if isInvest:
IsInvestedTechno[techno]=(df['MaxAddedCapacity']>0)+(df['MaxRetCapacity']>0)
else: listTechnosRES=[]
logger.info('Variable renewable technos: '+str(listTechnosRES))
# short term storage mix
if os.path.isfile(os.path.join(cfg['inputpath'], cfg['csvfiles']['STS_ShortTermStorage'])):
InputData=read_input_csv(cfg, 'STS_ShortTermStorage')
inputdata_save['STS_ShortTermStorage'] = InputData
listTechnosSTS=InputData.Name.unique().tolist()
if isInvest:
for row in InputData.index:
if (InputData.loc[row,'MaxAddedCapacity']>0)+(InputData.loc[row,'MaxRetCapacity']>0):
listInvestedAssets.append( (InputData.loc[row,'Zone'],InputData.loc[row,'Name']) )
for techno in listTechnosSTS:
if techno not in listTechnosInDataset:
listTechnosInDataset.append(techno)
listTechnosInDataset.append(techno+'_PUMP')
df=InputData[ InputData.Name==techno ]
df.index=df.Zone
InstalledCapacity[techno]=df['MaxPower']*df['NumberUnits']
InputVarCost[techno]=0
InputStartUpCost[techno]=0
InputStartUpCost[techno]=0
if isInvest:
IsInvestedTechno[techno]=(df['MaxAddedCapacity']>0)+(df['MaxRetCapacity']>0)
else: listTechnosSTS=[]
logger.info('Short term storage technos: '+str(listTechnosSTS))
listTechnosInDataset.append('SlackUnit')
# create list of aggregated technos
listaggrTechnosInDataset=[]
for aggrTech in cfg['technosAggr']:
for tech in listTechnosInDataset:
if tech in cfg['technosAggr'][aggrTech]['technos'] and aggrTech not in listaggrTechnosInDataset:
listaggrTechnosInDataset.append(aggrTech)
# interconnections
if os.path.isfile(os.path.join(cfg['inputpath'], cfg['csvfiles']['IN_Interconnections'])):
InputData=read_input_csv(cfg, 'IN_Interconnections')
inputdata_save['IN_Interconnections'] = InputData
if 'Name' in InputData.columns:
InputData=InputData.set_index('Name')
listLinesInDataset=InputData.index.tolist()
cfg['lines']=listLinesInDataset
LineCapacity=InputData[ ['MaxPowerFlow', 'MinPowerFlow'] ]
if isInvest:
IsInvestedLine=(InputData['MaxAddedCapacity']>0)+(InputData['MaxRetCapacity']>0)
else:
listLinesInDataset=[]
cfg['lines']=[]
InstalledCapacity=InstalledCapacity.fillna(0)
LineCapacity=LineCapacity.fillna(0)
invest_factor_by_asset = dict()
if isInvest:
InstalledCapacity.to_csv(cfg['dirOUT']+'InitialInstalledCapacity.csv')
LineCapacity.to_csv(cfg['dirOUT']+'InitialLineCapacity.csv')
IsInvestedTechno=IsInvestedTechno.fillna(False)
IsInvestedLine=IsInvestedLine.fillna(False)
InvestedCapacity=pd.DataFrame(index=InstalledCapacity.index,columns=InstalledCapacity.columns,data=0.0)
InvestedLine=pd.DataFrame(index=LineCapacity.index,columns=LineCapacity.columns,data=0.0)
# get solution of capacity expansion
sol=check_and_read_csv(cfg, cfg['dir']+'Solution_OUT.csv',header=None)
indexSol=0
for asset in listInvestedAssets:
techno=asset[1]
region=asset[0]
invest_factor_by_asset[(region, techno)] = sol[0].loc[indexSol]
print('region ',region,' techno ',techno,' indexsol ',indexSol,' sol ',sol[0].loc[indexSol],' added ',InstalledCapacity[techno].loc[region]*sol[0].loc[indexSol]-InstalledCapacity[techno].loc[region])
InvestedCapacity[techno].loc[region]=np.round(InstalledCapacity[techno].loc[region]*sol[0].loc[indexSol]-InstalledCapacity[techno].loc[region],decimals=cfg['arrondi'])
indexSol=indexSol+1
InvestedCapacity=InvestedCapacity.fillna(0.0)
for line in listLinesInDataset:
if IsInvestedLine.loc[line]:
invest_factor_by_asset[line] = sol[0].loc[indexSol]
InvestedLine.loc[line]=np.round(LineCapacity.loc[line]*sol[0].loc[indexSol],decimals=cfg['arrondi'])
indexSol=indexSol+1
InvestedLine=InvestedLine.fillna(0.0)
InvestedCapacity.to_csv(cfg['dirOUT']+'InvestedCapacity.csv')
InvestedLine.to_csv(cfg['dirOUT']+'InvestedLines.csv')
LineCapacity=LineCapacity+InvestedLine
InstalledCapacity=InstalledCapacity+InvestedCapacity
InputVarCost.to_csv(cfg['dirOUT']+'InputVariableCost.csv')
InputStartUpCost.to_csv(cfg['dirOUT']+'InputStartUpCost.csv')
InputFixedCost.to_csv(cfg['dirOUT']+'InputFixedCost.csv')
InstalledCapacity.to_csv(cfg['dirOUT']+'InstalledCapacity.csv')
LineCapacity.to_csv(cfg['dirOUT']+'LineCapacity.csv')
# write csv_after_invest
# if isInvest:
# dir_csv_after_invest = cfg['inputpath']
# if not os.path.isdir(dir_csv_after_invest):
# os.makedirs(dir_csv_after_invest)
# installed_capacity = InstalledCapacity.stack().swaplevel().sort_index()
# for k in inputdata_save.keys():
# path_cs_save = os.path.join(dir_csv_after_invest, cfg['csvfiles'][k])
# logger.info('Writing '+path_cs_save)
# for c in ['MaxPower', 'MinPower', 'Capacity']:
# if c in inputdata_save[k].columns:
# for i in inputdata_save[k].index:
# asset = tuple(inputdata_save[k].loc[i, ['Zone', 'Name']]) if 'Zone' in inputdata_save[k].columns else inputdata_save[k].loc[i, 'Name']
# if asset in invest_factor_by_asset.keys():
# inputdata_save[k][c].loc[i] = np.round(inputdata_save[k][c].loc[i]*invest_factor_by_asset[asset],decimals=cfg['arrondi'])
# inputdata_save[k].to_csv(path_cs_save, index=None)
# compute aggregated Installed capacity
AggrInstalledCapacity=pd.DataFrame(index=list_regions)
for aggrtechno in cfg['technosAggr']:
AggrCols=[]
for techno in cfg['technosAggr'][aggrtechno]['technos']:
if techno in InstalledCapacity.columns: AggrCols=AggrCols+[ techno ]
if len(AggrCols)>0:
AggrInstalledCapacity[aggrtechno]=InstalledCapacity[ AggrCols ].sum(axis=1)
AggrInstalledCapacity.to_csv(cfg['dirOUT']+'AggrInstalledCapacity.csv')
# treat hex color codes
for techno in cfg['Technos']:
cfg['Technos'][techno]['color']=mcolors.hex2color(cfg['Technos'][techno]['color'])
# build tables of colors
TechnoColors=pd.DataFrame(index=listTechnosInDataset,columns=['color'])
TechnoAggrColors=pd.DataFrame(index=listaggrTechnosInDataset,columns=['color'])
ChloroColors=pd.DataFrame(index=listaggrTechnosInDataset,columns=['color'])
for techno in listTechnosInDataset:
TechnoColors.loc[techno,'color']=cfg['Technos'][techno]['color']
for techno in listaggrTechnosInDataset:
TechnoAggrColors.loc[techno,'color']=cfg['technosAggr'][techno]['color']
ChloroColors.loc[techno,'colormap']=cfg['technosAggr'][techno]['colors']
# treat lists of regions
#################################################
# get list of scenarios and timeframe in dataset from file Demand0.csv
if os.path.isdir(cfg['dirSto']+cfg['PostTreat']['Demand']['Dir']):
listFiles=os.listdir(cfg['dirSto']+cfg['PostTreat']['Demand']['Dir'])
listscen=[]
if 'FileNumScenPrefix' in cfg:
lenpre=len(cfg['FileNumScenPrefix'])
else:
lenpre=0
if 'FileNumScenPostfix' in cfg:
lenpost=len(cfg['FileNumScenPostfix'])
else:
lenpost=0
for elem in listFiles:
print(elem)
print(lenpre,lenpost)
if '-' not in elem: listscen.append(int(elem.split('.')[0].replace("Demand","")[lenpre:][:-lenpost]))
listscen=list(range(len(listscen)))
else:
logger.error('missing Demand in results')
log_and_exit(2, cfg['path'])
logger.info('scenarios in dataset: '+str(cfg['ParametersFormat']['Scenarios']))
logger.info(' indexed: '+', '.join([str(s) for s in listscen]))
#create shortened names of regions, used in the latex report (for graphics to be readable)
cfg['regions_short']=[]
for region in list_regions:
cfg['regions_short'].append(region[0:4])
# list of regions to account for in visualisation
if 'regionsANA' not in cfg:
cfg['regionsANA']=list_regions
logger.info('Regions in dataset: '+', '.join(list_regions))
logger.info(' regions shortened names: '+str(cfg['regions_short']))
logger.info(' regions analysed: '+str(cfg['regionsANA']))
# update list of regions with reservoirs
toremove=[]
cfg['ReservoirRegions']=[]
ScenIndex=str(listscen[0])
if 'FileNumScenPrefix' in cfg: ScenIndex=cfg['FileNumScenPrefix']+ScenIndex
if 'FileNumScenPostfix' in cfg: ScenIndex=ScenIndex+cfg['FileNumScenPostfix']
if os.path.isfile(os.path.join(cfg['dirSto'], cfg['PostTreat']['Volume']['Dir'], 'Volume'+ScenIndex+'.csv')):
df=pd.read_csv(cfg['dirSto']+cfg['PostTreat']['Volume']['Dir']+'Volume'+ScenIndex+'.csv',index_col=0)
for elem in df.columns:
if 'Reservoir' in elem:
cfg['ReservoirRegions'].append(elem.split('_')[1])
for region in cfg['ReservoirRegions']:
if region not in cfg['regionsANA']:
toremove.append(region)
for region in toremove:
cfg['ReservoirRegions'].remove(region)
logger.info(' regions with reservoirs: '+str(cfg['ReservoirRegions']))
logger.info('Lines in dataset: '+str(cfg['lines']))
# treat dates
number_timesteps=len(df.index)
BeginDataset=pd.Timestamp(pd.to_datetime(cfg['BeginDataset'],dayfirst=cfg['dayfirst']))
if cfg['Calendar']['TimeStep']['Unit']=='days': TimeStepHours=TimeStepHours*24
elif cfg['Calendar']['TimeStep']['Unit']=='weeks': TimeStepHours=TimeStepHours*168
elif cfg['Calendar']['TimeStep']['Unit']!='hours':
logger.error('only hours, days, weeks possible as timestep unit')
log_and_exit(2, cfg['path'])
EndDataset=BeginDataset+number_timesteps*pd.Timedelta(str(TimeStepHours)+' hours')-pd.Timedelta('1 hours')
BeginTreat=pd.Timestamp(pd.to_datetime(cfg['BeginTreatData'],dayfirst=cfg['dayfirst']))
EndTreat=pd.Timestamp(pd.to_datetime(cfg['EndTreatData'],dayfirst=cfg['dayfirst']))
if BeginTreat>EndDataset:
logger.error('Treatment start date is after end of available data')
log_and_exit(2, cfg['path'])
if EndTreat<BeginDataset:
logger.error('Treatment end date is before start of available data')
log_and_exit(2, cfg['path'])
if BeginTreat<BeginDataset: BeginTreat=BeginDataset
if EndTreat>EndDataset: EndTreat=EndDataset
if EndTreat<BeginTreat:
logger.error('Treatment end date is before treatment start date')
log_and_exit(2, cfg['path'])
cfg['p4r_start']=BeginDataset
cfg['p4r_end']=EndDataset
cfg['plot_start']=BeginTreat
cfg['plot_end']=EndTreat
logger.info('data available between '+str(BeginDataset)+' and '+str(EndDataset))
logger.info('PostTreating between '+str(BeginTreat)+' and '+str(EndTreat))
# compute date ranges
cfg['Tp4r'] = pd.date_range(start=pd.to_datetime(cfg['p4r_start'],dayfirst=cfg['dayfirst']),end=pd.to_datetime(cfg['p4r_end'],dayfirst=cfg['dayfirst']), freq=str(TimeStepHours)+'h')
cfg['PlotDates'] = pd.date_range(start=pd.to_datetime(cfg['plot_start'],dayfirst=cfg['dayfirst']),end=pd.to_datetime(cfg['plot_end'],dayfirst=cfg['dayfirst']), freq=str(TimeStepHours)+'h')
NbTimeStepsToRemoveBefore=len(pd.date_range(start=pd.to_datetime(cfg['p4r_start'],dayfirst=cfg['dayfirst']),end=pd.to_datetime(cfg['plot_start'],dayfirst=cfg['dayfirst']), freq=str(TimeStepHours)+'h'))-1
NbTimeStepsToRemoveAfter=len(pd.date_range(start=pd.to_datetime(cfg['plot_end'],dayfirst=cfg['dayfirst']),end=pd.to_datetime(cfg['p4r_end'],dayfirst=cfg['dayfirst']), freq=str(TimeStepHours)+'h'))-1
# date ranges for graph outputs
datestart=cfg['plot_start']
dateend=cfg['plot_end']
start=pd.to_datetime(datestart,dayfirst=cfg['dayfirst'])
end=pd.to_datetime(dateend,dayfirst=cfg['dayfirst'])
TimeIndex=pd.date_range(start=start,end=end, freq=str(TimeStepHours)+'h')
MonthIndex=pd.to_datetime(TimeIndex,format ='%Y-%m-%d %H%M%s+01:00').strftime('%Y-%m')
NbTimeSteps=len(TimeIndex)
ScenarioIndex=[]
for i in range(listscen[0],listscen[0]+len(listscen)):
ScenarioIndex=ScenarioIndex+[i]
FailureCost=cfg['CouplingConstraints']['ActivePowerDemand']['Cost']
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
#world.to_csv('world.csv')
if cfg['map']:
####################################################################################################
# Create map of selected regions
####################################################################################################
logger.info('create map')
listcountrymap=list_regions
if 'nameregions' in cfg.keys(): listcountrymap=cfg['nameregions']
if 'private_map' in cfg:
logger.info('use private map')
file_extension = os.path.splitext(cfg['private_map'])[1]
if file_extension == '.csv':
df_continent = pd.read_csv(os.path.join(cfg['path'],cfg['private_map']),index_col=0)
df_continent['geometry'] = df_continent['geometry'].apply(wkt.loads)
continent=gpd.GeoDataFrame(df_continent, crs='epsg:4326')
elif file_extension == '.geojson':
continent = gpd.read_file(cfg['path']+cfg['private_map'])
else:
logger.info('unrecognised map file')
logger.info('maps will not be created')
cfg['map']=False
else:
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
continent = world [ world['continent'].isin(cfg['partition']['continent'])]
continent['Aggr']=continent['name']
continent['country']=continent['name']
continent['index']=continent['name']
continent=continent.set_index('index')
if cfg['aggregateregions']:
for Aggr in cfg['aggregateregions']:
for country in cfg['aggregateregions'][Aggr]:
continent.loc[country,'Aggr']=Aggr
else:
logger.info('no aggregated regions')
# create list of countries and sample of values (to delete)
mycountries=[]
myvalue=[]
i=0
for country in listcountrymap:
if cfg['aggregateregions']:
if country in cfg['aggregateregions']:
#if not (cfg['countryaggregates'] and country in cfg['countryaggregates']):
for smallcountry in cfg['aggregateregions'][country]:
mycountries.append(smallcountry)
else:
mycountries.append(country)
else: mycountries.append(country)
else:
mycountries.append(country)
# keep only country names and geometry
continent['name']=continent['Aggr']
#continent = continent[ ['continent','name','Aggr','country','geometry','pop_est'] ]
continent = continent[ ['continent','name','Aggr','country','geometry'] ]
continent['isin']=0
for i in continent.index:
if continent.loc[i,'country'] in mycountries:
continent.at[i,'isin']=1
mycontinent = continent [ continent['isin'] ==1 ]
restofcontinent = continent [ continent['isin'] == 0 ]
del mycontinent['isin']
del restofcontinent['isin']
# aggregate countries in the map
if cfg['aggregateregions']: mycontinent = mycontinent.dissolve(by='Aggr')
# plot continent avec frontieres et representative point
figmapcontinent, axmapcontinent = plt.subplots(1,1,figsize=(10,10))
mycontinent.boundary.plot(ax=axmapcontinent,figsize=(10,10))
axmapcontinent.set_xticklabels([])
axmapcontinent.set_yticklabels([])
# compute representative point of countries and get their coordinates
centers=mycontinent.representative_point()
numcenters=pd.Series(mycontinent.index,index=mycontinent['name'])
mycontinent['x']=centers.x
mycontinent['y']=centers.y
mycontinent['centers']=centers
mycontinent=mycontinent.set_index('name')
plt.savefig(cfg['dirIMG']+'mycontinent.jpeg')
plt.close()
####################################################################################################
# plot funtions
####################################################################################################
# functions for drawing continent maps with pies or bars
# df: dataframe with cfg['partition']['Level1'] as index
# NameFile: name of file => 'file.jpeg'
# create one pie per region and draw it at the right place over the continent map
# returns a jpg file cfg['dirIMG']+NameFile
####################################################################################################
def FlowsMap(df,NameFile):
# draws a map of continent with arrows representing the mean annual flows
###########################################################
namefigpng=cfg['dirIMG']+NameFile
if cfg['geopandas']:
figflows, axflows = plt.subplots(1,1,figsize=(10,10))
mycontinent.boundary.plot(ax=axflows,figsize=(10,10))
centers.plot(color='r',ax=axflows,markersize=1)
# fill data with flows and start/end
lines=df.columns
data={'start':[ x.split('>')[0] for x in lines ],'end':[ x.split('>')[1] for x in lines ],'flow':df.sum(axis=0).transpose()}
flows = pd.DataFrame(data, index = df.columns )
# compute width of arrows
if flows['flow'].abs().max()>0: flows['width']=(10.0*flows['flow']/(flows['flow'].abs().max())).abs()
else: flows['width']=flows['flow'].abs()
flows['newstart']=flows['start']
flows['newend']=flows['end']
flows['newstart']=np.where(flows['flow']<0,flows['end'],flows['start'])
flows['newend']=np.where(flows['flow']<0,flows['start'],flows['end'])
flows['newflow']=flows['flow'].abs()
flows['startpoint']=flows['newstart'].apply(lambda x: centers[numcenters[x]])
flows['endpoint']=flows['newend'].apply(lambda x: centers[numcenters[x]])
flows['line']=flows.apply(lambda x: LineString([x['startpoint'], x['endpoint']]),axis=1)
geoflows=gpd.GeoDataFrame(flows,geometry=flows['line'])
# reduce length of arrows
scaledgeometry=geoflows.scale(xfact=0.7,yfact=0.7,zfact=1.0,origin='center')
geoflows.geometry=scaledgeometry
# plot lines
geoflows.plot(ax=axflows,column='newflow',linewidth=geoflows.width,cmap='Reds',vmin=-100,vmax=500)
# plot arrows
for line in geoflows.index:
if geoflows['flow'][line]!=0:
plt.arrow(list(geoflows['geometry'][line].coords)[0][0],list(geoflows['geometry'][line].coords)[0][1],
list(geoflows['geometry'][line].coords)[1][0]-list(geoflows['geometry'][line].coords)[0][0],
list(geoflows['geometry'][line].coords)[1][1]-list(geoflows['geometry'][line].coords)[0][1],
head_width=1,head_length=0.5,color='black',linewidth=0,zorder=2)
axflows.set_title("Import/Exports (MWh)",fontsize=10)
axflows.tick_params(labelbottom=False,labelleft=False)
plt.savefig(namefigpng)
figflows.clf()
plt.close('all')
return namefigpng
def EuropePieMap(df,NameFile,Colors):
# draw a map of continent with pies in each region
namefigpng=cfg['dirIMG']+NameFile
TechnosInGraph=[]
for tech in df.columns:
if ~df[tech].isin([0,cfg['ParametersCreate']['zerocapacity']]).all() :
if tech not in TechnosInGraph:
TechnosInGraph.append(tech)
ColorsInGraph=pd.DataFrame(data=Colors.loc[ TechnosInGraph ])
if cfg['geopandas']:
figmapcontinent, axmapcontinent = plt.subplots(1,1,figsize=(10,10))
mycontinent.boundary.plot(ax=axmapcontinent,figsize=(10,10))
axmapcontinent.set_xticklabels([])
axmapcontinent.set_yticklabels([])
xbounds=axmapcontinent.get_xbound()
ybounds=axmapcontinent.get_ybound()
xmin,xmax=axmapcontinent.get_xbound()
ymin,ymax=axmapcontinent.get_ybound()
for country in cfg['regionsANA']:
todraw=df.loc[country]
ColorsKept=Colors['color'].loc[ todraw.index ]
x=mycontinent['x'][country]
y=mycontinent['y'][country]
axmapcontinent.pie(todraw,colors=ColorsKept,center=(x,y),radius=1.5)
step=1/len(df.columns)
X=np.arange(xmin,xmin+1,step)
patches=axmapcontinent.bar(X,todraw,bottom=ymax,width=0,color=ColorsInGraph['color'])
axmapcontinent.legend(patches,ColorsInGraph.index,loc="lower left",bbox_to_anchor=(0, -0.09),facecolor='white',ncol=2)
axmapcontinent.set_xbound(xbounds)
axmapcontinent.set_ybound(ybounds)
namefigpng=cfg['dirIMG']+NameFile
plt.savefig(namefigpng)
figmapcontinent.clf()
plt.close('all')
return namefigpng
def EuropeBarMap(df,NameFile,Colors):
# draw a map of continent with a bargraph in each region
namefigpng=cfg['dirIMG']+NameFile
TechnosInGraph=[]
for tech in df.columns:
if ~df[tech].isin([0,cfg['ParametersCreate']['zerocapacity']]).all() :
if tech not in TechnosInGraph:
TechnosInGraph.append(tech)
ColorsInGraph=pd.DataFrame(data=Colors.loc[ TechnosInGraph ])
if cfg['geopandas']:
figmapcontinent, axmapcontinent = plt.subplots(1,1,figsize=(10,10))
mycontinent.boundary.plot(ax=axmapcontinent,figsize=(10,10))
axmapcontinent.set_xticklabels([])
axmapcontinent.set_yticklabels([])
xbounds=axmapcontinent.get_xbound()
ybounds=axmapcontinent.get_ybound()
barsize=3
for country in cfg['regionsANA']:
todraw=df.loc[country]
x=mycontinent['x'][country]
y=mycontinent['y'][country]
step=barsize/len(df.columns)
X=np.arange(x,x+barsize,step)
maxtodraw=todraw.max(axis=0)
todraw=todraw*barsize/maxtodraw
patches=axmapcontinent.bar(X,todraw,bottom=y,width=0.9*step,color=ColorsInGraph['color'])
axmapcontinent.legend(patches,ColorsInGraph.index,loc="upper left",facecolor='white',ncol=2)
namefigpng=cfg['dirIMG']+NameFile
plt.savefig(namefigpng)
figmapcontinent.clf()
plt.close('all')
return namefigpng
def Chloromap(NbCols,NbRows,List,mytable,SizeCol,SizeRow,TitleSize,LabelSize,name,dpi=80):
# draw a serie of maps of continent with each region lighter if the value of the table is lower
namefigpng=cfg['dirIMG']+'ChloroMap-'+name+'.jpeg'
if cfg['geopandas']:
fig, axes = plt.subplots(figsize=(SizeCol*NbCols,SizeRow*NbRows),nrows=NbRows, ncols=NbCols)
x=0
y=0
for item in List:
if item in mytable.columns:
chloroeurope=mycontinent
chloroeurope[item]=mytable[item]
mintech=mytable[item].min()
maxtech=mytable[item].max()
chloroeurope=mycontinent.fillna(0)
ax=chloroeurope.plot(column=item,ax=axes[y][x],cmap=ChloroColors.loc[item,'colormap'],vmin=mintech,vmax=maxtech,legend=True,\
legend_kwds={'label':"energy (MWh)",'orientation':"vertical"})
fig=ax.figure
cb_ax=fig.axes[1]
cb_ax.tick_params(labelsize=40)
axes[y][x].set_title(item,fontsize=TitleSize)
if x<NbCols-1: x=x+1
else:
x=0
y=y+1
namefigpng=cfg['dirIMG']+'ChloroMap-'+name+'.jpeg'
plt.savefig(namefigpng,dpi=dpi)
fig.clf()
plt.close('all')
return namefigpng
def OneChloromap(mycol,TitleSize,LabelSize,name,dpi=80,mytitle=''):
# draw a unique map of continent with each region lighter if the value of the table is lower
namefigpng=cfg['dirIMG']+'ChloroMap-'+name+'.jpeg'
if cfg['geopandas']:
chloroeurope=mycontinent
chloroeurope[mytitle]=mycol
mintech=0
maxtech=1
chloroeurope=chloroeurope.fillna(0)
figchloroeurope, axchloroeurope = plt.subplots(1,1)
chloroeurope.plot(column=mytitle,ax=axchloroeurope,cmap='Greens',legend=True,vmin=0.2,vmax=1,legend_kwds={'label':"Decarbonized Energy Share (%)",'orientation':"horizontal"})
namefigpng='ChloroMap-'+mytitle+'.jpeg'
plt.savefig(cfg['dirIMG']+namefigpng)
plt.close()
return namefigpng
def StackedBar(dfin,NameFile,Colors,drawScale=True):
# draw a graphic with technos stacked (in the order of the df)
df=pd.DataFrame(data=dfin)
df = df.drop(columns=df.columns[df.le(cfg['ParametersCreate']['zerocapacity']).all()])
x=list_regions
df=df.fillna(0.0)
Bottom=pd.Series(index=x,data=0.0)
fig, axes = plt.subplots(figsize=(10,5),nrows=1, ncols=1)
for techno in df.columns:
plt.bar(x,df[techno],color=Colors.loc[techno,'color'],bottom=Bottom)
Bottom=Bottom+df[techno]
plt.legend(df.columns,bbox_to_anchor=(1.1, 1.05),loc='upper left')
plt.xticks(rotation=45,fontsize=14)
plt.tight_layout()
if not drawScale:
plt.yticks([])
plt.ylabel(None) # remove the y-axis label
plt.tick_params(left=False)
namefigpng=cfg['dirIMG']+NameFile
plt.savefig(namefigpng)
fig.clf()
plt.close('all')
return namefigpng
# function for drawing stochastic graph
def StochasticGraphs(NbCols,NbRows,List,What,Dir,SizeCol,SizeRow,TitleSize,LabelSize,DrawMean=False,max=0,drawScale=True,isTimeIndex=True):
# draw one graphic per item in the List, organised as a table with NbCols and NbRows, ...
# each graphic includes all scenarios plus the mean of scenarios
fig, axes = plt.subplots(figsize=(SizeCol*NbCols,SizeRow*NbRows),nrows=NbRows, ncols=NbCols)
indexres=0
x=0
y=0
i=0
for item in List:
Data=pd.read_csv(cfg['dirSto']+Dir+'/'+What+'-'+item+'.csv',nrows=NbTimeSteps,index_col=0).fillna(0.0)
if 'time' in Data.columns:Data=Data.drop('time',axis=1)
maxData=Data.max(axis=1).max()
minY=Data.min(axis=1).min()
if maxData<max:
maxY=maxData
else: maxY=max
if isTimeIndex: Data.index=pd.to_datetime(Data.index)
axes[y][x].plot(Data.index.to_list(),Data)
axes[y][x].set_title(item,fontsize=TitleSize)
if isTimeIndex:
axes[y][x].tick_params(axis='x', labelsize =LabelSize)
period=pd.to_datetime(Data.index[-1])-pd.to_datetime(Data.index[0])
nb_seconds=period.total_seconds()
nb_hours=nb_seconds/3600
nb_days=nb_hours/24
if period> pd.Timedelta('180 days'):
locator=mdates.MonthLocator(bymonth=range(1,13))
axes[y][x].xaxis.set_major_locator(locator)
axes[y][x].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
elif period> pd.Timedelta('90 days'):
locator=mdates.WeekdayLocator(byweekday=1,interval=2)
axes[y][x].xaxis.set_major_locator(locator)
axes[y][x].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
elif period> pd.Timedelta('30 days'):
locator=mdates.WeekdayLocator(byweekday=1)
axes[y][x].xaxis.set_major_locator(locator)
axes[y][x].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
elif period> pd.Timedelta('14 days'):
locator=mdates.DayLocator(bymonthday=range(1,32))
axes[y][x].xaxis.set_major_locator(locator)
axes[y][x].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
elif period> pd.Timedelta('2 days'):
locator=mdates.HourLocator(byhour=range(24),interval=12)
axes[y][x].xaxis.set_major_locator(locator)
axes[y][x].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d:%H'))
else:
locator=mdates.HourLocator(byhour=range(24))
axes[y][x].xaxis.set_major_locator(locator)
axes[y][x].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d:%H'))
for label in axes[y][x].get_xticklabels(which='major'):
label.set(rotation=30, horizontalalignment='right')
if drawScale:
axes[y][x].tick_params(axis='y', labelsize =LabelSize)
else:
axes[y][x].set_yticks([])
if max>0: axes[y][x].set_ylim(ymax=maxY,ymin=minY)
mean=Data.mean(axis=1)
del Data
if i==0:
meanScen=pd.DataFrame(mean,columns=[item])
i=1
else:
meanScen[item]=mean
if DrawMean: axes[y][x].plot(mean,linewidth=5,color="k")