-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCreateInputPlan4res.py
More file actions
1745 lines (1541 loc) · 80.7 KB
/
CreateInputPlan4res.py
File metadata and controls
1745 lines (1541 loc) · 80.7 KB
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 pyam
import pandas as pd ## necessary data analysis package
import numpy as np
import os
import yaml
import calendar
import math
from math import ceil
from datetime import timedelta
from calendar import monthrange
from itertools import product
import sys
from p4r_python_utils import *
p4rpath = os.environ.get("PLAN4RESROOT")
print("p4rpath=",p4rpath)
path=get_path()
print("plan4res path=",path)
nbargs=len(sys.argv)
if nbargs>1:
settings_create=sys.argv[1]
else:
settings_create="settingsCreateInputPlan4res.yml"
print("os.path.abspath(settings_create)=",os.path.abspath(settings_create))
#if os.path.abspath(settings_create):
#settings_create = os.path.relpath(settings_create, path)
print("settings_create=",settings_create)
cfg={}
# open the configuration file using the pathway defined below
#with open(os.path.join(path, settings_create),"r") as mysettings:
with open(settings_create,"r") as mysettings:
cfg=yaml.load(mysettings,Loader=yaml.FullLoader)
# replace name of current dataset by name given as input
if nbargs>2:
namedataset=sys.argv[2]
cfg['path']=os.path.join(path, 'data/local', namedataset)
# if cfg['USEPLAN4RESROOT']:
# cfg['path']=os.path.join(path, 'data/local', namedataset)
# else:
# cfg['path']=cfg['path'].replace(cfg['path'].split('/')[len(cfg['path'].split('/'))-2],namedataset)
if 'outputpath' not in cfg:
if cfg['ParametersCreate']['invest']:
cfg['outputpath']=os.path.join(cfg['path'], 'csv_invest')
else:
cfg['outputpath']=os.path.join(cfg['path'], 'csv_simul')
if 'dirTimeSeries' not in cfg: cfg['dirTimeSeries'] = os.path.join(cfg['path'], 'TimeSeries')
if 'genesys_inputpath' not in cfg: cfg['genesys_inputpath'] = os.path.join(cfg['path'], 'genesys_inputs')
if 'timeseriespath' not in cfg: cfg['timeseriespath'] = os.path.join(cfg['path'], 'TimeSeries')
if 'configDir' not in cfg: cfg['configDir']=os.path.join(cfg['path'], 'settings')
if 'pythonDir' not in cfg: cfg['pythonDir']=os.path.join(p4rpath,'scripts/python/plan4res-scripts/settings/')
if 'nomenclatureDir' not in cfg: cfg['nomenclatureDir']=os.path.join(p4rpath,'scripts/python/openentrance/definitions/')
# if 'pythonDir' not in cfg:
# if cfg['USEPLAN4RESROOT']:
# cfg['pythonDir']='scripts/python/plan4res-scripts/settings/'
# else:
# logger.error('\npythonDir missing in settingsCreateInputPlan4res')
# log_and_exit(1, cfg['path'])
# if 'nomenclatureDir' not in cfg:
# if cfg['USEPLAN4RESROOT']:
# cfg['nomenclatureDir']='scripts/python/openentrance/definitions/'
# else:
# logger.error('\nnomenclatureDir missing in settingsCreateInputPlan4res')
# log_and_exit(1, cfg['path'])
for datagroup in cfg['datagroups']:
if 'inputdatapath' not in cfg['datagroups'][datagroup]:
cfg['datagroups'][datagroup]['inputdatapath']='IAMC'
#cfg['datagroups'][datagroup]['inputdatapath'] = os.path.join(cfg['genesys_inputpath'], cfg['datagroups'][datagroup]['inputdatapath'])
cfg['datagroups'][datagroup]['inputdatapath'] = os.path.join(cfg['path'], cfg['datagroups'][datagroup]['inputdatapath'])
if 'inputdata' not in cfg['datagroups'][datagroup]:
cfg['datagroups'][datagroup]['inputdata']=namedataset+'.xlsx'
if cfg['USEPLAN4RESROOT']:
cfg['outputpath']=os.path.join(path, cfg['outputpath'])
cfg['dirTimeSeries']=os.path.join(path, cfg['timeseriespath'])
cfg['nomenclatureDir']=os.path.join(path, cfg['nomenclatureDir'])
cfg['pythonDir']=os.path.join(path, cfg['pythonDir'])
for datagroup in cfg['datagroups']:
cfg['datagroups'][datagroup]['inputdatapath']=os.path.join(path, cfg['datagroups'][datagroup]['inputdatapath'])
else:
cfg['dirTimeSeries']=cfg['timeseriespath']
if not os.path.isdir(cfg['outputpath']):
os.mkdir(cfg['outputpath'])
logger.info('results of this script will be available in: '+cfg['outputpath'])
isInertia= ( 'InertiaDemand' in cfg['CouplingConstraints'] )
isPrimary= ( 'PrimaryDemand' in cfg['CouplingConstraints'] )
isSecondary= ( 'SecondaryDemand' in cfg['CouplingConstraints'] )
isCO2=False
if 'PollutantBudget' in cfg['CouplingConstraints']:
if 'CO2' in cfg['CouplingConstraints']['PollutantBudget']:
isCO2=True
partitionDemand = cfg['CouplingConstraints']['ActivePowerDemand']['Partition']
if isInertia: partitionInertia=cfg['CouplingConstraints']['InertiaDemand']['Partition']
if isPrimary: partitionPrimary=cfg['CouplingConstraints']['PrimaryDemand']['Partition']
if isSecondary: partitionSecondary=cfg['CouplingConstraints']['SecondaryDemand']['Partition']
isInvest= cfg['ParametersCreate']['invest']
# connect to the openentrance scenario explorer (set credentials)
if cfg['mode_annual']=='platform' or cfg['mode_subannual']=='platform':
pyam.iiasa.set_config(cfg['user'],cfg['password'])
pyam.iiasa.Connection('openentrance')
# 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)
# create the dictionnary of time series, containing the names of the timeseries to be included in
# the dataset
timeseriesdict={}
timeseries_setting_file = os.path.join(path, cfg['configDir'], "DictTimeSeries.yml")
with open(timeseries_setting_file,"r") as mytimeseries:
timeseriesdict=yaml.safe_load(mytimeseries)
# if only one scenario/year is defined in config file set the list of scenarios / years to 1 element
if 'scenarios' not in cfg: cfg['scenarios']= [ cfg['scenario'] ]
if 'years' not in cfg: cfg['years']= [ cfg['year'] ]
# create the list of options
if 'options' in cfg:
option_types=cfg['options']
cfg['options']=[]
for option_type in option_types:
cfg['options'].append('WITH_'+option_type)
cfg['options'].append('WITHOUT_'+option_type)
else: cfg['options']=['None']
cfg['treat']=cfg['csvfiles']
cfg['StochasticScenarios']=[str(x) for x in cfg['StochasticScenarios']]
# loop on scenarios, years, options => create one dataset per (scenario,year,option) triplet
for current_scenario, current_year, current_option in product(cfg['scenarios'],cfg['years'],cfg['options']):
cfg['scenario']=current_scenario
cfg['year']=current_year
if current_option != "None":
logger.info('create dataset for scenario '+current_scenario+', year '+str(current_year)+' and option '+current_option)
else:
logger.info('create dataset for scenario '+current_scenario+', year '+str(current_year))
if len(cfg['scenarios'])==1 and len(cfg['years'])==1 and len(cfg['options'])<2:
outputdir=cfg['outputpath']
if not os.path.isdir(outputdir):
os.mkdir(outputdir)
elif not current_option=='None':
outputdir=os.path.join(cfg['outputpath'], 'plan4res-'+cfg['scenario']+'-'+str(cfg['year'])+'-'+current_option)
if not os.path.isdir(outputdir):
os.mkdir(outputdir)
else:
outputdir=os.path.join(cfg['outputpath'], 'plan4res-'+cfg['scenario']+'-'+str(cfg['year']))
if not os.path.isdir(outputdir):
os.mkdir(outputdir)
# upload of relevant Scenario data from platform
# creation of a csv file and a pandas dataframe containing all necessary data
####################################################################################################
i=0
ExistsAnnualData=False # AnnualDataFrame is still empty
ExistsSubAnnualData=False # SubAnnualDataFrame is still empty
SubAnnualDataFrame=pyam.IamDataFrame
AnnualDataFrame=pyam.IamDataFrame
listLocalReg=[]
listGlobalReg=[]
# define list of aggregated regions
if cfg['ParametersCreate']['ExistsNuts']:
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)
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/ehighway.yaml"),"r",encoding='UTF-8') as nutsreg:
subcountries=yaml.safe_load(nutsreg)
with open(os.path.join(cfg['nomenclatureDir'], "region/european-regions.yaml"),"r",encoding='UTF-8') as nutsreg:
aggregateregions=yaml.safe_load(nutsreg)
# create table of correspondence for iso3 and iso2 names
iso3=pd.Series(str)
iso2=pd.Series(str)
listcountries=[]
for k in range(len(countries[0]['Countries'])):
countryname=next(iter(countries[0]['Countries'][k]))
iso=countries[0]['Countries'][k][countryname]['iso3']
iso3[iso]=countryname
iso=countries[0]['Countries'][k][countryname]['iso2']
iso2[iso]=countryname
listcountries.append(countryname)
dict_iso3=iso3.to_dict()
dict_iso2=iso2.to_dict()
rev_dict_iso3={v:k for k,v in dict_iso3.items()}
rev_dict_iso2={v:k for k,v in dict_iso2.items()}
# create the list of regions to work on
for datagroup in cfg['listdatagroups']:
if type(cfg['datagroups'][datagroup]['regions']['local'])==list: listLocalReg=listLocalReg+cfg['datagroups'][datagroup]['regions']['local']
elif cfg['datagroups'][datagroup]['regions']['local']=='countries':listLocalReg=listLocalReg+countries.keys()
elif cfg['datagroups'][datagroup]['regions']['local']=='countries_ISO3':listLocalReg=listLocalReg+iso3.index.tolist()
elif cfg['datagroups'][datagroup]['regions']['local']=='countries_ISO2':listLocalReg=listLocalReg+iso2.index.tolist()
if(cfg['datagroups'][datagroup]['regions']['global']): listGlobalReg.append(cfg['datagroups'][datagroup]['regions']['global'])
# create list of lines
lines=[]
for region1 in cfg['listregionsGET']:
for region2 in cfg['listregionsGET']:
if (region1!=region2):
lines.append(region1+'>'+region2)
lines.append(region2+'>'+region1)
# define list of regions including lines
listLocalReg=listLocalReg+lines
for region in cfg['listregionsGET']:
if region not in listGlobalReg: listLocalReg.append(region)
listRegGet=listLocalReg+listGlobalReg
# treat cases where disaggregation level is nuts1/2/3
if cfg['ParametersCreate']['ExistsNuts']:
minaggr=''
nuts3list= {}
nuts2list= {}
nuts1list= {}
for k in nuts1[0]['NUTS1']: nuts1list.update(k)
for k in nuts2[0]['NUTS2']: nuts2list.update(k)
for k in nuts3[0]['NUTS3']: nuts3list.update(k)
# create lists of nuts per countries
countryNuts3={v:[] for v in listcountries}
{countryNuts3[v['country']].append(k) for k,v in nuts3list.items()}
countryNuts2={v:[] for v in listcountries}
{countryNuts2[v['country']].append(k) for k,v in nuts2list.items()}
countryNuts1={v:[] for v in listcountries}
{countryNuts1[v['country']].append(k) for k,v in nuts1list.items()}
# extend list of regions to get with regions from datagroups
if 'nuts3' in listRegGet:
while 'nuts3' in listRegGet: listRegGet.remove('nuts3')
listRegGet=listRegGet+list(nuts3.keys())
minaggr='nuts3'
if 'nuts2' in listRegGet:
while 'nuts2' in listRegGet: listRegGet.remove('nuts2')
listRegGet=listRegGet+list(nuts2.keys())
minaggr='nuts2'
if 'nuts1' in listRegGet:
while 'nuts1' in listRegGet: listRegGet.remove('nuts1')
listRegGet=listRegGet+list(nuts1.keys())
minaggr='nuts1'
if 'countries' in listRegGet:
while 'countries' in listRegGet: listRegGet.remove('countries')
listRegGet=listRegGet+list(countries.keys())
# create list of variables
for datagroup in cfg['listdatagroups']:
# loop on all different data sources
if 'scenario' in cfg['datagroups'][datagroup]: scenget=cfg['datagroups'][datagroup]['scenario']
else: scenget=cfg['scenario']
if cfg['ParametersCreate']['debug']: logger.info('reading '+datagroup)
listvardatagroup=[]
listlocalvar=[] # list of variables which are not 'global'
listglobalvar=[]
globalreg= cfg['datagroups'][datagroup]['regions']['global']
# loop on category of variables : coupling or techno
for varcat1 in cfg['datagroups'][datagroup]['listvariables']:
# treat coupling variables (ie variables not depending on techno)
if varcat1=='coupling':
# loop on category of coupling variables: mean, add, flow or global
for varcat2 in cfg['datagroups'][datagroup]['listvariables'][varcat1].keys():
# loop on variables
for var in cfg['datagroups'][datagroup]['listvariables'][varcat1][varcat2]:
listvardatagroup.append(var)
# specific treatment for global variables (meaning they do not depend on regions)
if varcat2=='global':listglobalvar.append(var)
else: listlocalvar.append(var)
# treat variables depending on technos
elif varcat1=='techno':
# loop on category of techno variables: thermal, reservoir, .....
for varcat2 in cfg['datagroups'][datagroup]['listvariables'][varcat1].keys():
# loop on category of variables: add, mean, global
for varcat3 in cfg['datagroups'][datagroup]['listvariables'][varcat1][varcat2].keys():
# is there only a list of variables or subgroups of variables per fuels
if(type(cfg['datagroups'][datagroup]['listvariables'][varcat1][varcat2][varcat3])==list):
# loop on variables and fuels
for var in cfg['datagroups'][datagroup]['listvariables'][varcat1][varcat2][varcat3]:
for fuel in cfg['technos'][varcat2]:
newvar=var+fuel
listvardatagroup.append(newvar)
if varcat3=='global': listglobalvar.append(newvar)
else: listlocalvar.append(newvar)
else: # there are subgroups of variables per fuels
for subgroup in cfg['datagroups'][datagroup]['listvariables'][varcat1][varcat2][varcat3].keys():
for var in cfg['datagroups'][datagroup]['listvariables'][varcat1][varcat2][varcat3][subgroup]['variables']:
for fuel in cfg['datagroups'][datagroup]['listvariables'][varcat1][varcat2][varcat3][subgroup]['fuels']:
newvar=var+fuel
listvardatagroup.append(newvar)
if varcat3=='global': listglobalvar.append(newvar)
else: listlocalvar.append(newvar)
if ( cfg['datagroups'][datagroup]['subannual'] and cfg['mode_subannual']=='platform') or ( not cfg['datagroups'][datagroup]['subannual'] and cfg['mode_annual']=='platform'):
if cfg['ParametersCreate']['debug']: logger.info('download data from platform')
groupdf=pyam.read_iiasa('openentrance',model=cfg['datagroups'][datagroup]['model'],
variable=listvardatagroup,
region=listRegGet,year=cfg['year'],
scenario=scenget)
# remove rows for global variables / local regions or local variables / global regions
groupdf=groupdf.filter(region=globalreg, variable=listlocalvar, keep=False)
groupdf=groupdf.filter(region=listLocalReg, variable=listglobalvar, keep=False)
# rename regions if necessary
if cfg['datagroups'][datagroup]['regions']['local']=='countries_ISO3':groupdf.rename(dict_iso3,inplace=True)
if cfg['datagroups'][datagroup]['regions']['local']=='countries_ISO2':groupdf.rename(dict_iso2,inplace=True)
if cfg['datagroups'][datagroup]['subannual']:
if not ExistsSubAnnualData:
ExistsSubAnnualData=True
SubAnnualDataFrame=groupdf
else:
SubAnnualDataFrame=SubAnnualDataFrame.append(groupdf)
else:
if not ExistsAnnualData:
ExistsAnnualData=True
AnnualDataFrame=groupdf
else:
AnnualDataFrame=AnnualDataFrame.append(groupdf)
if not (cfg['mode_annual']=='platform' and cfg['mode_subannual']=='platform'):
# load data from files per data source (previously uploaded from platform)
if cfg['ParametersCreate']['debug']: logger.info('open data files')
if ( cfg['datagroups'][datagroup]['subannual'] and cfg['mode_subannual']=='files') or ( not cfg['datagroups'][datagroup]['subannual'] and cfg['mode_annual']=='files'):
logger.info('reading datagroup '+datagroup+' from '+os.path.join(cfg['genesys_inputpath'], cfg['datagroups'][datagroup]['inputdatapath'], cfg['datagroups'][datagroup]['inputdata']))
if 'Start' in cfg['datagroups'][datagroup]['inputdata']:
file=os.path.join(cfg['genesys_inputpath'], cfg['datagroups'][datagroup]['inputdatapath'], cfg['datagroups'][datagroup]['inputdata']['Start'], str(cfg['variant']), cfg['datagroups'][datagroup]['inputdata']['End'])
else:
file=os.path.join(cfg['genesys_inputpath'], cfg['datagroups'][datagroup]['inputdatapath'], cfg['datagroups'][datagroup]['inputdata'])
# creation of empty df for storing annual and subannual data for the current group
dfdatagroup=pyam.IamDataFrame(pd.DataFrame(columns=['model','scenario','region','variable','unit','subannual',str(cfg['year'])]))
# filter on the listgetfegion regions
SubAdfdatagroup=pyam.IamDataFrame(pd.DataFrame(columns=['model','scenario','region','variable','unit','subannual',str(cfg['year'])]))
# read data as a IAMDataFrame
if cfg['ParametersCreate']['debug']: logger.info('read file '+file)
if not os.path.isfile(file):
logger.error('\nError: '+file+' does not exist.')
logger.error('Check file '+settings_create+'. You can specify the input data repository using key inputdatapath (default=IAMC) and file name using key inputdata (default=name of the study+.xlsx).')
log_and_exit(2, cfg['path'])
if 'xlsx' in file:
df=pd.read_excel(file,sheet_name='data')
else:
df=pd.read_csv(file)
if 'Subannual' in df.columns:
if len(df['Subannual'].unique()==1): df=df.drop(['Subannual'],axis=1)
dfdatagroup=pyam.IamDataFrame(data=df)
if 'countries_ISO3' in cfg['datagroups'][datagroup]['regions']['local']:
if cfg['ParametersCreate']['debug']: logger.info('renaming ISO3')
dfdatagroup=dfdatagroup.rename(region=dict_iso3)
if 'countries_ISO2' in cfg['datagroups'][datagroup]['regions']['local']:
if cfg['ParametersCreate']['debug']: logger.info('renaming ISO2')
dfdatagroup=dfdatagroup.rename(region=dict_iso2)
if cfg['ParametersCreate']['debug']: logger.info('change country names')
dfdatagroup=dfdatagroup.filter(region=listRegGet)
if cfg['ParametersCreate']['debug']: logger.info('filter countries')
# if there are data at lower granularity than country or cluster (only country until now), aggregate
firstcountry=1
if cfg['ParametersCreate']['ExistsNuts']:
for country in listcountries:
# create list of nuts of the country
listNuts1=countryNuts1[country]
listNuts2=countryNuts2[country]
listNuts3=countryNuts3[country]
listNuts=listNuts1+listNuts2+listNuts3
NumberOfNutsLists=int(len(listNuts1)>0)+int(len(listNuts2)>0)+int(len(listNuts3)>0)
# To be implemented: include weights to aggregation, weight=1/NumberOfNutsLists
if (len(listNuts)>0 and ('NoNutsAggregation' not in cfg)):
if cfg['ParametersCreate']['debug']: logger.info('aggregating nuts')
dfdatagroup.aggregate_region(dfdatagroup.variable,region=country, subregions=listNuts, append=True)
dfdatagroup=dfdatagroup.filter(model=cfg['datagroups'][datagroup]['model'])
dfdatagroup=dfdatagroup.filter(scenario=scenget)
dfdatagroup=dfdatagroup.filter(year=cfg['year'])
dfdatagroup=dfdatagroup.filter(variable=listvardatagroup)
# remove local variables on global region and global variables on local regions
dfdatagroup=dfdatagroup.filter(region=globalreg, variable=listlocalvar, keep=False)
dfdatagroup=dfdatagroup.filter(region=listLocalReg, variable=listglobalvar, keep=False)
if cfg['datagroups'][datagroup]['subannual']: SubAdfdatagroup=dfdatagroup
if cfg['datagroups'][datagroup]['subannual']:
if not ExistsSubAnnualData:
ExistsSubAnnualData=True
SubAnnualDataFrame=SubAdfdatagroup
else:
SubAnnualDataFrame=SubAnnualDataFrame.append(SubAdfdatagroup)
else:
if not ExistsAnnualData:
ExistsAnnualData=True
AnnualDataFrame=dfdatagroup
else:
AnnualDataFrame=AnnualDataFrame.append(dfdatagroup)
#conversion of units to plan4res usual units (MWh, MW, €/MWh, €/MW/yr, €/MW)
if(ExistsAnnualData): #check if there exist annual data
logger.info('converting units')
for var_unit in cfg['ParametersCreate']['conversions']:
if 'factor' in cfg['ParametersCreate']['conversions'][var_unit]:
AnnualDataFrame=AnnualDataFrame.convert_unit(var_unit, to=cfg['ParametersCreate']['conversions'][var_unit]['to'], factor=float(cfg['ParametersCreate']['conversions'][var_unit]['factor']))
else:
AnnualDataFrame=AnnualDataFrame.convert_unit(var_unit, to=cfg['ParametersCreate']['conversions'][var_unit]['to'])
# validate the format of the data (prevents errors)
AnnualDataFrame.validate(exclude_on_fail=True)
if(ExistsSubAnnualData): # check if there exist subannual data
for var_unit in cfg['ParametersCreate']['conversions']:
if 'factor' in cfg['ParametersCreate']['conversions'][var_unit]:
SubAnnualDataFrame=SubAnnualDataFrame.convert_unit(var_unit, to=cfg['ParametersCreate']['conversions'][var_unit]['to'], factor=cfg['ParametersCreate']['conversions'][var_unit]['factor'])
else:
SubAnnualDataFrame=SubAnnualDataFrame.convert_unit(var_unit, to=cfg['ParametersCreate']['conversions'][var_unit]['to'])
SubAnnualDataFrame.validate(exclude_on_fail=True)
#regional aggregations
logger.info('computing regional aggregations')
# some variables are added (all energy, capacity), others are averageded, and finally for flow variable specific aggregations are done
listvaradd=[]
listvarmean=[]
for datagroup in cfg['listdatagroups']:
if 'coupling' in cfg['datagroups'][datagroup]['listvariables'].keys():
for typeagr in cfg['datagroups'][datagroup]['listvariables']['coupling'].keys():
for var in cfg['datagroups'][datagroup]['listvariables']['coupling'][typeagr]:
variable=var
if typeagr=='add':
if variable not in listvaradd:
listvaradd.append(variable)
elif typeagr=='mean':
if variable not in listvarmean:
listvarmean.append(variable)
if 'techno' in cfg['datagroups'][datagroup]['listvariables'].keys():
for technogroup in cfg['datagroups'][datagroup]['listvariables']['techno'].keys():
for typeagr in cfg['datagroups'][datagroup]['listvariables']['techno'][technogroup].keys():
if type(cfg['datagroups'][datagroup]['listvariables']['techno'][technogroup][typeagr])==list:
for var in cfg['datagroups'][datagroup]['listvariables']['techno'][technogroup][typeagr]:
for techno in cfg['technos'][technogroup]:
newvar=var+techno
if typeagr=='add':
if newvar not in listvaradd:
listvaradd.append(newvar)
elif typeagr=='mean':
if newvar not in listvarmean:
listvarmean.append(newvar)
else:
for groupvar in cfg['datagroups'][datagroup]['listvariables']['techno'][technogroup][typeagr].keys():
for fuel in cfg['datagroups'][datagroup]['listvariables']['techno'][technogroup][typeagr][groupvar]['fuels']:
for var in cfg['datagroups'][datagroup]['listvariables']['techno'][technogroup][typeagr][groupvar]['variables']:
newvar=var+fuel
if typeagr=='add':
if newvar not in listvaradd:
listvaradd.append(newvar)
elif typeagr=='mean':
if newvar not in listvarmean:
listvarmean.append(newvar)
if(cfg['aggregateregions']!=None):
for reg in cfg['aggregateregions'].keys():
if cfg['ParametersCreate']['debug']: logger.info('aggregating ' +reg+' for subregions:')
if cfg['ParametersCreate']['debug']: logger.info(cfg['aggregateregions'][reg])
# creation of aggregated timeseries
listTypes={'ZV': cfg['CouplingConstraints']['ActivePowerDemand']['SumOf'],'RES':cfg['technos']['res']+cfg['technos']['runofriver'],'SS':['Inflows']}
for typeData in listTypes:
for typeSerie in listTypes[typeData]:
sumValTS=0.0
firstSerie=True
isSeries=False
for region in cfg['aggregateregions'][reg]:
if region in timeseriesdict[typeData][typeSerie].keys():
isSeries=True
file = os.path.join(cfg['dirTimeSeries'], timeseriesdict[typeData][typeSerie][region])
if not os.path.isfile(file):
logger.error('\nError: '+file+' does not exist.')
logger.error('Check file '+settings_create+'. You can specify the timeseries input repository using key dirTimeSeries (default=study path/TimeSeries).')
logger.error('Also check the timeseries file name for '+typeData+', '+typeSerie+', '+region+' in file '+timeseries_setting_file)
log_and_exit(2, cfg['path'])
timeserie=pd.read_csv(file,index_col=0)
if len(timeserie.columns)>1:
for col in timeserie.columns:
if 'Unnamed' in col: timeserie.drop([col],axis=1)
timeserie=timeserie[ cfg['StochasticScenarios'] ]
else:
timeserie.columns=['DET']
if typeData=='ZV':
varTS=vardict['Input']['Var'+typeData][typeSerie]
elif typeData=='SS':
varTS=vardict['Input']['Var'+typeData][typeSerie]+'Reservoir'
else:
varTS=vardict['Input']['Var'+typeData]['MaxPower']+typeSerie
if varTS in AnnualDataFrame.variable:
valTS_IAMdf=AnnualDataFrame.filter(variable=varTS,region=region,year=current_year).as_pandas()['value'].unique()
if len(valTS_IAMdf)>0: valTS=valTS_IAMdf[0]
else: valTS=0.0
else:
# the only variables which may not be in the data are the different parts of the ActiveDemand:
if varTS in [timeseriesdict['ZV'][part] for part in cfg['CouplingConstraints']['ActivePowerDemand']['SumOf']]:
# compute valTS as Total-sum of parts which are present
valTS=AnnualDataFrame[ (AnnualDataFrame['Variable']==timeseriesdict['ZV']['Total']) & (df['Region']==region) ][str(current_year)].unique()[0]
for part in cfg['CouplingConstraints']['ActivePowerDemand']:
if vardict['Input']['Var'+typeData][part] in AnnualDataFrame['Variable'].unique():
valTS=valTS-AnnualDataFrame[ (AnnualDataFrame['Variable']==timeseriesdict['ZV'][part]) & (df['Region']==region) ][str(current_year)].unique()[0]
if valTS==0.0: valTS=cfg['ParametersCreate']['zerocapacity']
if firstSerie:
newSerie=valTS*timeserie
firstSerie=False
sumValTS=valTS
else:
newSerie=newSerie+valTS*timeserie
sumValTS=sumValTS+valTS
if isSeries:
if sumValTS>0: newSerie=(1/sumValTS)*newSerie
else: newSerie=0.0*newSerie
nameNewSerie='AggregatedTimeSerie_'+typeSerie+'_'+reg+'.csv'
nameNewSerie=nameNewSerie.replace('|', pipe_replace)
newSerie.to_csv(os.path.join(cfg['dirTimeSeries'], nameNewSerie))
timeseriesdict[typeData][typeSerie][reg]=nameNewSerie
# aggregation of variables
for variable in listvaradd:
if ExistsAnnualData:
if variable in AnnualDataFrame.variable: AnnualDataFrame.aggregate_region(variable, region=reg, subregions=cfg['aggregateregions'][reg], append=True)
if ExistsSubAnnualData:
if variable in SubAnnualDataFrame.variable: SubAnnualDataFrame.aggregate_region(variable, region=reg, subregions=cfg['aggregateregions'][reg], append=True)
for variable in listvarmean:
if ExistsAnnualData:
if variable in AnnualDataFrame.variable: AnnualDataFrame.aggregate_region(variable, region=reg, subregions=cfg['aggregateregions'][reg], method='mean',append=True)
if ExistsSubAnnualData:
if variable in SubAnnualDataFrame.variable: SubAnnualDataFrame.aggregate_region(variable, region=reg, subregions=cfg['aggregateregions'][reg], method='mean',append=True)
#remove aggregated subregions
listregion=listGlobalReg
for partition in cfg['partition']:
for region in cfg['partition'][partition]:
if region not in listregion: listregion.append(region)
if ExistsAnnualData:
AnnualDataFrame=AnnualDataFrame.filter(region=(listregion+lines))
AnnualDataFrame.to_csv(os.path.join(outputdir, 'IAMC_annual_data.csv'))
bigdata=AnnualDataFrame
if ExistsSubAnnualData:
SubAnnualDataFrame=SubAnnualDataFrame.filter(region=(listregion+lines))
SubAnnualDataFrame.to_csv(os.path.join(outputdir, 'IAMC_subannual_data.csv'))
bigdata_SubAnnual=SubAnnualDataFrame
# creation of plan4res dataset
################################"
# creating list of regions
listregions=listGlobalReg
for partition in list(cfg['partition'].keys()):
listregions=listregions+cfg['partition'][partition]
listregions = list(set(listregions))
logger.info('regions in dataset:'+str(listregions))
# create file ZP_ZonePartition
#############################################################
if cfg['csvfiles']['ZP_ZonePartition']:
logger.info('Creating ZP_ZonePartition')
nbreg=len(cfg['partition'][ partitionDemand ])
nbpartition=len(cfg['partition'])
ZP = pd.DataFrame(columns=list(cfg['partition'].keys()),index=range(nbreg))
ZP[ partitionDemand ]=pd.Series(cfg['partition'][ partitionDemand ],name=partition,index=range(nbreg))
for partition in list(cfg['partition'].keys()):
if not partition == cfg['CouplingConstraints']['ActivePowerDemand']['Partition']:
if len(cfg['partition'][partition])==nbreg: ZP[partition]=pd.Series(cfg['partition'][partition],name=partition,index=range(nbreg))
else: ZP[partition]=pd.Series(cfg['partition'][partition][0] ,name=partition,index=range(nbreg))
ZP.to_csv(os.path.join(outputdir, cfg['csvfiles']['ZP_ZonePartition']), index=False)
# create file IN_Interconnections
###############################################################
if cfg['csvfiles']['IN_Interconnections']:
IN = pd.DataFrame()
logger.info('Creating IN_Interconnections')
for variable in vardict['Input']['VarIN']:
varname=vardict['Input']['VarIN'][variable]
vardf=bigdata.filter(variable=varname).as_pandas(meta_cols=False)
vardf=vardf.set_index('region')
vardf=vardf.rename(columns={"value":variable})
dataIN=vardf[variable]
IN=pd.concat([IN, dataIN], axis=1)
IN=IN.fillna(value=0.0)
# delete lines which start/end in same aggregated
if cfg['ParametersCreate']['debug']: logger.info('deleting lines which start and end in same aggregated region')
IN['Name']=IN.index
IN['StartLine']=IN['Name'].str.split('>',expand=True)[0]
IN['EndLine']=IN['Name'].str.split('>',expand=True)[1]
IN['AgrStart']=IN['StartLine']
IN['AgrEnd']=IN['EndLine']
for line in dataIN.index:
# check if start / end is in an aggregated region
regstart=line.split('>')[0]
regend=line.split('>')[1]
if(cfg['aggregateregions']!=None):
for AggReg1 in cfg['aggregateregions'].keys():
if (regstart in cfg['aggregateregions'][AggReg1]): IN.at[line,'AgrStart']=AggReg1
if (regend in cfg['aggregateregions'][AggReg1]): IN.at[line,'AgrEnd']=AggReg1
# delete line with start and end in smae aggregated region
DeleteLines=IN[ IN.AgrStart == IN.AgrEnd ].index
IN=IN.drop(DeleteLines)
DeleteLines=[]
# sum lines with start in same aggregated region AND end in same other aggregated region
if cfg['ParametersCreate']['debug']: logger.info('aggregate lines which start or end in same aggregated region')
if cfg['ParametersCreate']['debug']: logger.info(cfg['aggregateregions'])
if(cfg['aggregateregions']!=None):
for AggReg1 in cfg['partition'][ partitionDemand ]:
if AggReg1 in cfg['aggregateregions'].keys(): # AggReg1 is an aggregated region
for AggReg2 in cfg['partition'][partitionDemand]:
if AggReg2 != AggReg1:
if AggReg2 in cfg['aggregateregions'].keys(): # AggReg2 is another aggregated region
# sum all lines fitting this selection
MaxPowerFlow=0.0
InvCost=0.0
LossFactor=0.0
N=0
for reg1 in cfg['aggregateregions'][AggReg1]:
for reg2 in cfg['aggregateregions'][AggReg2]:
if (reg1+'>'+reg2) in IN.index:
N=N+1
MaxPowerFlow=MaxPowerFlow+IN['MaxPowerFlow'][reg1+'>'+reg2]
InvCost=InvCost+IN['InvestmentCost'][reg1+'>'+reg2]
LossFactor=LossFactor+IN['LossFactor'][reg1+'>'+reg2]
DeleteLines.append(reg1+'>'+reg2) # delete individual line
if N==0: N=1
InvCost=InvCost/N
LossFactor=LossFactor/N
IN = pd.concat([IN,pd.DataFrame(data=[[MaxPowerFlow,InvCost,LossFactor,AggReg1+'>'+AggReg2,AggReg1,AggReg2,AggReg1,AggReg2]],index=[AggReg1+'>'+AggReg2],columns=IN.columns)])
else:
# AggReg2 is not an aggregated region
MaxPowerFlow=0.0
InvCost=0.0
LossFactor=0.0
N=0
for reg1 in cfg['aggregateregions'][AggReg1]:
if (reg1+'>'+AggReg2) in IN.index:
N=N+1
LossFactor=LossFactor+IN['LossFactor'][reg1+'>'+AggReg2]
MaxPowerFlow=MaxPowerFlow+IN['MaxPowerFlow'][reg1+'>'+AggReg2]
InvCost=InvCost+IN['InvestmentCost'][reg1+'>'+AggReg2]
DeleteLines.append(reg1+'>'+AggReg2) # delete individual line
if N==0: N=1
InvCost=InvCost/N
LossFactor=LossFactor/N
IN = pd.concat([IN,pd.DataFrame(data=[[MaxPowerFlow,InvCost,LossFactor,AggReg1+'>'+AggReg2,AggReg1,AggReg2,AggReg1,AggReg2]],index=[AggReg1+'>'+AggReg2],columns=IN.columns)])
else:
for AggReg2 in cfg['partition'][partitionDemand]:
if AggReg2 != AggReg1:
if AggReg2 in cfg['aggregateregions'].keys(): # AggReg2 is an aggregated region
MaxPowerFlow=0.0
InvCost=0.0
LossFactor=0.0
N=0
for reg2 in cfg['aggregateregions'][AggReg2]:
if (AggReg1+'>'+reg2) in IN.index:
N=N+1
InvCost=InvCost+IN['InvestmentCost'][AggReg1+'>'+reg2]
LossFactor=LossFactor+IN['LossFactor'][AggReg1+'>'+reg2]
MaxPowerFlow=MaxPowerFlow+IN['MaxPowerFlow'][AggReg1+'>'+reg2]
DeleteLines.append(AggReg1+'>'+reg2) # delete individual line
if N==0: N=1
InvCost=InvCost/N
LossFactor=LossFactor/N
IN = pd.concat([IN,pd.DataFrame(data=[[MaxPowerFlow,InvCost,LossFactor,AggReg1+'>'+AggReg2,AggReg1,AggReg2,AggReg1,AggReg2]],index=[AggReg1+'>'+AggReg2],columns=IN.columns)])
IN=IN.drop(DeleteLines )
RowsToDelete = IN[ IN['MaxPowerFlow'] == 0 ].index
IN=IN.drop(RowsToDelete )
# merge lines reg1>reg2 reg2>reg1
if cfg['ParametersCreate']['debug']: logger.info('merging symetric lines')
IN['MinPowerFlow']=0
NewLines=[]
LinesToDelete=[]
for line in IN.index:
regstart=line.split('>')[0]
regend=line.split('>')[1]
inverseline=regend+'>'+regstart
if (line not in LinesToDelete):
NewLines.append(line)
LinesToDelete.append(inverseline)
IN.at[line,'MinPowerFlow']=-1.0*IN.loc[inverseline]['MaxPowerFlow']
IN=IN.drop(LinesToDelete)
IN['Name']=IN.index
listcols=['Name','StartLine','EndLine','MaxPowerFlow','MinPowerFlow']
if 'Impedance' in IN.columns: listcols.append('Impedance')
if isInvest and 'interconnections' in cfg['ParametersCreate']['CapacityExpansion']:
IN['MaxAddedCapacity']=0
IN['MaxRetCapacity']=0
if 'Share' in cfg['ParametersCreate']['CapacityExpansion']['interconnections']:
# all lines can be invested
IN['MaxAddedCapacity']=IN['MaxPowerFlow']*cfg['ParametersCreate']['CapacityExpansion']['interconnections']['Share']['MaxAdd']
IN['MaxRetCapacity']=IN['MaxPowerFlow']*cfg['ParametersCreate']['CapacityExpansion']['interconnections']['Share']['MaxRet']
else:
for line in cfg['ParametersCreate']['CapacityExpansion']['interconnections']:
if line != 'Share' and line !='InvestmentCost':
IN.loc[line]['MaxAddedCapacity']=IN.loc[line]['MaxPowerFlow']*cfg['ParametersCreate']['CapacityExpansion']['interconnections'][line]['MaxAdd']
IN.loc[line]['MaxRetCapacity']=IN.loc[line]['MaxPowerFlow']*cfg['ParametersCreate']['CapacityExpansion']['interconnections'][line]['MaxRet']
if 'InvestmentCost' not in IN.columns:
if 'InvestmentCost' in cfg['ParametersCreate']['CapacityExpansion']['interconnections']:
IN['InvestmentCost']=cfg['ParametersCreate']['CapacityExpansion']['interconnections']['InvestmentCost']
else:
IN['InvestmentCost']=0
listcols.append('MaxAddedCapacity')
listcols.append('MaxRetCapacity')
listcols.append('InvestmentCost')
IN=IN[ listcols ]
# delete lines which do not start and end in a zone in partition
if cfg['ParametersCreate']['debug']: logger.info('delete lines which are not in partition')
LinesToDelete=[]
for line in IN.index:
regstart=line.split('>')[0]
regend=line.split('>')[1]
if (regstart not in listregions):
LinesToDelete.append(line)
if (regend not in listregions):
LinesToDelete.append(line)
IN=IN.drop(LinesToDelete)
IN.to_csv(os.path.join(outputdir, cfg['csvfiles']['IN_Interconnections']), index=False)
# create file ZV_ZoneValues
###############################################################
numserie=0
if cfg['csvfiles']['ZV_ZoneValues']:
logger.info('Creating ZV_ZoneValues')
ListTypesZV=[]
for coupling_constraint in cfg['CouplingConstraints']:
ListTypesZV=ListTypesZV+cfg['CouplingConstraints'][coupling_constraint]['SumOf']
listvar=[]
for var in vardict['Input']['VarZV'].keys(): listvar.append(vardict['Input']['VarZV'][var])
datapartition=bigdata.filter(variable=listvar,region=listregions).as_pandas(meta_cols=False)
datapartition=datapartition.rename(columns={"variable": "Type", "region": "Zone", "unit":"Unit"})
# rename variables using Variables dictionnary
# create reverse variables dictionnary
dictZV={}
dictZV=vardict['Input']['VarZV']
reversedictZV={}
for key, values in dictZV.items():
for value in values:
myvalue=dictZV[key]
reversedictZV[myvalue]=key
datapartition=datapartition.replace({"Type":reversedictZV})
# include slack unit costs (slack means non served)
datainertia=datapartition[ datapartition.Type == 'Inertia' ]
Inertia=datainertia['value'].mean()
MaxDemand=cfg['CouplingConstraints']['ActivePowerDemand']['MaxPower']
CostDemand=cfg['CouplingConstraints']['ActivePowerDemand']['Cost']
if 'PrimaryDemand' in cfg['CouplingConstraints']:
isPrimary=True
MaxPrimary=cfg['CouplingConstraints']['PrimaryDemand']['MaxPower']
CostPrimary=cfg['CouplingConstraints']['PrimaryDemand']['Cost']
else: isPrimary=False
if 'SecondaryDemand' in cfg['CouplingConstraints']:
isSecondary=True
MaxSecondary=cfg['CouplingConstraints']['SecondaryDemand']['MaxPower']
CostSecondary=cfg['CouplingConstraints']['SecondaryDemand']['Cost']
else: isSecondary=False
if 'InertiaDemand' in cfg['CouplingConstraints']:
isInertia=True
MaxInertia=cfg['CouplingConstraints']['InertiaDemand']['MaxPower']
CostInertia=cfg['CouplingConstraints']['InertiaDemand']['Cost']
else: isInertia=False
# compute missing global values
if cfg['ParametersCreate']['debug']: logger.info('compute missing Coupling constraints')
isTotalEnergy=False
isHeating=False
isTransport=False
isCooling=False
isShareCooling=False
isElectrolyzer=False
isCooking=False
if 'Cooking' in datapartition.Type.unique(): isCooking=True
if 'ElecVehicle' in datapartition.Type.unique(): isTransport=True
if 'ElecHeating' in datapartition.Type.unique(): isHeating=True
if 'Total' in datapartition.Type.unique() : isTotalEnergy=True
if 'AirCondition' in datapartition.Type.unique(): isCooling=True
if 'Electrolyzer' in datapartition.Type.unique(): isElectrolyzer=True
if 'Share|Final Energy|Electricity|Cooling' in bigdata.variable : isShareCooling=True
for region in cfg['partition'][partitionDemand]:
if isTotalEnergy:
TotalEnergy=datapartition[ (datapartition.Zone==region) & (datapartition.Type == 'Total') ]['value'].mean()
if math.isnan(TotalEnergy): TotalEnergy=0
else:
logger.info('missing variable for total electricity demand')
exit(0)
if isCooking:
CookingEnergy=datapartition[ (datapartition.Zone==region) & (datapartition.Type == 'Cooking') ]['value'].mean()
if math.isnan(CookingEnergy): CookingEnergy=0
else: CookingEnergy=0
if isElectrolyzer:
ElectrolyzerEnergy=datapartition[ (datapartition.Zone==region) & (datapartition.Type == 'Electrolyzer') ]['value'].mean()
if math.isnan(ElectrolyzerEnergy): ElectrolyzerEnergy=0
else: ElectrolyzerEnergy=0
if isHeating:
HeatingEnergy=datapartition[ (datapartition.Zone==region) & (datapartition.Type == 'ElecHeating') ]['value'].mean()
if math.isnan(HeatingEnergy): HeatingEnergy=0
else: HeatingEnergy=0
if isTransport:
TransportEnergy=datapartition[ (datapartition.Zone==region) & (datapartition.Type == 'ElecVehicle') ]['value'].mean()
if math.isnan(TransportEnergy): TransportEnergy=0
else: TransportEnergy=0
if isCooling:
CoolingEnergy=datapartition[ (datapartition.Zone==region) & (datapartition.Type == 'AirCondition') ]['value'].mean()
if math.isnan(CoolingEnergy): CoolingEnergy=0
elif isShareCooling:
ShareCooling=bigdata.filter(region=region,variable='Share|Final Energy|Electricity|Cooling').as_pandas(meta_cols=False)['value'].fillna(0).mean()
if isTotalEnergy :
CoolingEnergy=TotalEnergy*(ShareCooling/100)
else : CoolingEnergy=0
else : CoolingEnergy=0
OtherEnergy=TotalEnergy-CoolingEnergy-TransportEnergy-HeatingEnergy-ElectrolyzerEnergy-CookingEnergy
if (isShareCooling) and ('AirCondition' in cfg['CouplingConstraints']['ActivePowerDemand']['SumOf']):
newdata=pd.DataFrame({'Type':['AirCondition'],'Unit':['MWh/yr'],\
'Zone':[region],'model':['Recalculated'],'scenario':[cfg['listdatagroups'][0]],\
'value':[CoolingEnergy],'year':[cfg['year']]})
datapartition=pd.concat([datapartition,newdata],ignore_index=True)
if ('Other' in cfg['CouplingConstraints']['ActivePowerDemand']['SumOf']):
newdata=pd.DataFrame({'Type':['Other'],'Unit':['MWh/yr'],\
'Zone':[region],'model':['Recalculated'],'scenario':[cfg['listdatagroups'][0]],\
'value':[OtherEnergy],'year':[cfg['year']]})
datapartition=pd.concat([datapartition,newdata],ignore_index=True)
newdata=pd.DataFrame({'Type':['MaxActivePowerDemand','CostActivePowerDemand'],\
'Unit':['MW','EUR/MWh'],\
'Zone':[region, region],'model':['Recalculated','Recalculated'],\
'scenario':[cfg['scenario'],cfg['scenario']],\
'value':[MaxDemand,CostDemand],\
'year':[cfg['year'],cfg['year']]})
datapartition=pd.concat([datapartition,newdata],ignore_index=True)
if isPrimary:
Primary=datapartition[ (datapartition.Zone==region) & (datapartition.Type == 'PrimaryDemand') ]['value'].mean()
if isSecondary:
Secondary=datapartition[ (datapartition.Zone==region) & (datapartition.Type == 'SecondaryDemand') ]['value'].mean()
if isPrimary:
newdata=pd.DataFrame({'Type':['MaxPrimaryDemand','CostPrimaryDemand'],\
'Unit':['MW','EUR/MWh'],\
'Zone':[region, region],'model':['Recalculated','Recalculated'],\
'scenario':[cfg['scenario'],cfg['scenario']],\
'value':[MaxDemand,CostDemand],\
'year':[cfg['year'],cfg['year']]})
datapartition=pd.concat([datapartition,newdata],ignore_index=True)
if isSecondary:
newdata=pd.DataFrame({'Type':['MaxSecondaryDemand','CostSecondaryDemand'],\
'Unit':['MW','EUR/MWh'],\
'Zone':[region, region],'model':['Recalculated','Recalculated'],\
'scenario':[cfg['scenario'],cfg['scenario']],\
'value':[MaxDemand,CostDemand],\
'year':[cfg['year'],cfg['year']]})
datapartition=pd.concat([datapartition,newdata],ignore_index=True)
if isInertia:
newdata=pd.DataFrame({'Type':['Inertia','MaxInertia','CostInertia'],'Unit':['MWs/MWA','MWs/MWA','EUR/MWs/MWA'],\
'Zone':[cfg['partition'][partitionInertia], cfg['partition'][partitionInertia], cfg['partition'][partitionInertia]],\
'model':['Parameter','Parameter','Parameter'],\
'scenario':[cfg['listdatagroups'][0],cfg['listdatagroups'][0],cfg['listdatagroups'][0]],\
'value':[Inertia,MaxInertia,CostInertia],'year':[cfg['year'],cfg['year'],cfg['year']]})
# include timeseries names from TimeSeries dictionnary and compute scaling coefficient
if cfg['ParametersCreate']['debug']: logger.info('include time series and compute scaling coefficients')
for row in datapartition.index:
mytype=datapartition.loc[row,'Type']
if mytype in ListTypesZV:
if mytype in timeseriesdict['ZV'].keys():
filetimeserie=timeseriesdict['ZV'][datapartition.loc[row,'Type']][datapartition.loc[row,'Zone']]
datapartition.loc[row, 'Profile_Timeserie']=filetimeserie
columnsZV=['Type','Zone','value','Profile_Timeserie']
datapartition=datapartition[columnsZV]
datapartition.to_csv(os.path.join(outputdir, cfg['csvfiles']['ZV_ZoneValues']), index=False)
# treat global variables
logger.info('treat global variables ')
globalvars=pd.Series(str)
for datagroup in cfg['listdatagroups']:
if cfg['ParametersCreate']['debug']: logger.info('treat datagroup '+datagroup)
if 'techno' in cfg['datagroups'][datagroup]['listvariables'].keys():
for techno in cfg['datagroups'][datagroup]['listvariables']['techno'].keys():
if 'global' in cfg['datagroups'][datagroup]['listvariables']['techno'][techno].keys():
if cfg['ParametersCreate']['debug']: logger.info('there are global vars for:'+datagroup+',techno:'+techno)
if type(cfg['datagroups'][datagroup]['listvariables']['techno'][techno]['global'])==list:
for var in cfg['datagroups'][datagroup]['listvariables']['techno'][techno]['global']:
for fuel in cfg['technos'][techno]:
globalvars[var+fuel]=cfg['datagroups'][datagroup]['regions']['global']
else:
for key in cfg['datagroups'][datagroup]['listvariables']['techno'][techno]['global'].keys():
for var in cfg['datagroups'][datagroup]['listvariables']['techno'][techno]['global'][key]['variables']:
for fuel in cfg['datagroups'][datagroup]['listvariables']['techno'][techno]['global'][key]['fuels']:
globalvars[var+fuel]=cfg['datagroups'][datagroup]['regions']['global']
if 'coupling' in cfg['datagroups'][datagroup]['listvariables'].keys():
if 'global' in cfg['datagroups'][datagroup]['listvariables']['coupling'].keys():
for var in cfg['datagroups'][datagroup]['listvariables']['coupling']['global']:
globalvars[var]=cfg['datagroups'][datagroup]['regions']['global']
# create file TU_ThermalUnits
###############################################################
if cfg['csvfiles']['TU_ThermalUnits']:
logger.info('Creating TU_ThermalUnits')
listvar=[]
isCO2=False
isDynamic=cfg['ParametersCreate']['DynamicConstraints']
isPrice=(cfg['ParametersCreate']['thermal']['variablecost']=='Price')
isMaintenance=False
for variable in list(vardict['Input']['VarTU'].keys()):
oevar=vardict['Input']['VarTU'][variable]
if variable!='NumberUnits':
listvar.append(oevar)
v=0
# loop on technos
for oetechno in cfg['technos']['thermal']:
if cfg['ParametersCreate']['debug']: logger.info('treat '+oetechno)
TU=pd.DataFrame({'Name':oetechno,'region':listregions})
TU=TU.set_index('region')
for variable in vardict['Input']['VarTU']:
isFuel=False
TreatVar=True
isMainVar=False
if variable=='Capacity': isMainVar=True
if variable=='Price' and 'thermal' in cfg['ParametersCreate'] and cfg['ParametersCreate']['thermal']['variablecost']=='Price':
# case where VariableCost is computed as Efficency*Price of fuel
if oetechno in cfg['ParametersCreate']['thermal']['fuel']:
fuel=cfg['ParametersCreate']['thermal']['fuel'][oetechno]
varname=vardict['Input']['VarTU'][variable]+fuel
isFuel=True
else:
TreatVar=False
else:
varname=vardict['Input']['VarTU'][variable]+oetechno
if varname not in bigdata['variable'].unique():
if cfg['ParametersCreate']['debug']: logger.info('variable '+varname+' not in dataset')
if not isMainVar:
TreatVar=False
TreatVar=False
if TreatVar:
vardf=bigdata.filter(variable=varname,region=listregions).as_pandas(meta_cols=False)
vardf=vardf.set_index('region')
vardf=vardf.rename(columns={"value":variable})
dataTU=vardf[variable]