-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformat.py
2814 lines (2551 loc) · 140 KB
/
format.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
import numpy as np
import os
import yaml
from itertools import product
from netCDF4 import Dataset
import calendar
import sys
from p4r_python_utils import *
#path = os.environ.get("PLAN4RESROOT")
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_format=sys.argv[1]
else:
settings_format="settings_format.yml"
settings_format = abspath_to_relpath(settings_format, path)
# read config file
cfg1={}
with open(os.path.join(path, settings_format),"r") as mysettings:
cfg1=yaml.load(mysettings,Loader=yaml.FullLoader)
settings_create = None
if nbargs>2:
settings_create=abspath_to_relpath(sys.argv[2], path)
cfg2={}
with open(os.path.join(path, settings_create),"r") as mysettings:
cfg2=yaml.load(mysettings,Loader=yaml.FullLoader)
cfg = {**cfg1, **cfg2}
else:
cfg=cfg1
# replace name of current dataset by name given as input
if nbargs>3:
namedataset=sys.argv[3]
if 'path' in cfg:
cfg['path']=cfg['path'].replace(cfg['path'].split('/')[len(cfg['path'].split('/'))-2],namedataset)
else:
cfg['path']=os.path.join(path, 'data/local', namedataset)
#cfg['path']='/data/local/'+namedataset+'/'
cfg['inputpath']=os.path.join(cfg['path'], cfg['inputDir'])
cfg['outputpath']=os.path.join(cfg['path'], cfg['outputDir'])
if 'timeseriespath' not in cfg: cfg['timeseriespath']=os.path.join(cfg['path'],'TimeSeries/')
# if cfg['USEPLAN4RESROOT']:
# path = os.environ.get("PLAN4RESROOT")
# cfg['path']=path+cfg['path']
# cfg['outputpath']=path+cfg['outputpath']
# cfg['inputpath']=path+cfg['inputpath']
# cfg['timeseriespath']=path+cfg['timeseriespath']
logger.info('path: '+cfg['inputpath'])
cfg['treat']=cfg['csvfiles']
cfg['treat']['ZP']=cfg['csvfiles']['ZP_ZonePartition']
cfg['treat']['IN']=cfg['csvfiles']['IN_Interconnections']
cfg['treat']['ZV']=cfg['csvfiles']['ZV_ZoneValues']
cfg['treat']['TU']=cfg['csvfiles']['TU_ThermalUnits']
cfg['treat']['SS']=cfg['csvfiles']['SS_SeasonalStorage']
cfg['treat']['STS']=cfg['csvfiles']['STS_ShortTermStorage']
cfg['treat']['RES']=cfg['csvfiles']['RES_RenewableUnits']
if 'SYN_SynchCond' in cfg['csvfiles']:
cfg['treat']['SYN']=cfg['csvfiles']['SYN_SynchCond']
if not os.path.isdir(cfg['outputpath']):os.mkdir(cfg['outputpath'])
format=cfg['inputformat']
if format=='excel':
p4r_excel=cfg['inputpath']+cfg['excelfile']
excelfile=pd.read_excel(p4r_excel,None)
sheets=list(excelfile.keys())
else:
sheets=cfg['csvfiles']
def read_input_timeseries(cfg, ts_name, which_path='timeseriespath', **kwargs):
file = os.path.join(cfg[which_path], ts_name)
if not os.path.isfile(file):
logger.error('File '+file+' does not exist. Use key '+which_path+' in configuration file '+settings_format+(' or configuration file '+settings_create if settings_create is not None else '')+' to specify input directory.')
log_and_exit(2, cfg['path'])
logger.info('Read '+file)
return pd.read_csv(file, **kwargs)
#################################################################################################################################################
# #
# Read main data file(s) #
# #
# #
#################################################################################################################################################
# some of the sheets may have an additional row on top (where usually units can be written)
if 'additionalRowInSheets' in cfg and cfg['additionalRowInSheets']:
skiprow=True
skip=1
else:
skiprow=False
skip=0
# Read Parameters
#################################################################################################################################################
# create table of coupling constraints
ListPossibleTypesCoupling=['ActivePowerDemand','PrimaryDemand','SecondaryDemand','InertiaDemand','PollutantBudget']
ListCouplingConstraints=[elem for elem in cfg['CouplingConstraints'] if 'Pollutant' not in elem]
ListPollutants=[]
if 'PollutantBudget' in cfg['CouplingConstraints']:
for pollutant in cfg['CouplingConstraints']['PollutantBudget']:
ListPollutants=ListPollutants+[pollutant]
Coupling=pd.DataFrame(index=ListCouplingConstraints+ListPollutants,dtype=object,columns=['Partition','Sum'])
NumberPollutants=0
for coupling_constraint in cfg['CouplingConstraints']:
if coupling_constraint not in ListPossibleTypesCoupling:
logger.error('Constraint '+coupling_constraint+'is not possible')
logger.error('Possible constraints are: '+', '.join(ListPossibleTypesCoupling))
log_and_exit(1, cfg['path'])
if coupling_constraint=="PollutantBudget":
NumberPollutants=len(cfg['CouplingConstraints']['PollutantBudget'])
for pollutant in ListPollutants:
Coupling.loc[pollutant]['Sum']=[cfg['CouplingConstraints']['PollutantBudget'][pollutant]['SumOf']]
Coupling.loc[pollutant]['Partition']=cfg['CouplingConstraints']['PollutantBudget'][pollutant]['Partition']
else:
Coupling.loc[coupling_constraint,'Sum']=cfg['CouplingConstraints'][coupling_constraint]['SumOf']
Coupling.loc[coupling_constraint,'Partition']=cfg['CouplingConstraints'][coupling_constraint]['Partition']
logger.info('Coupling constraints:'+', '.join(ListCouplingConstraints))
logger.info('Emissions constraints:'+', '.join(ListPollutants))
# get dates
dates=pd.Series()
beginTS=pd.to_datetime(cfg['Calendar']['BeginTimeSeries'],dayfirst=cfg['Calendar']['dayfirst'])
dates['UCBeginData']=pd.Timestamp(year=beginTS.year,month=beginTS.month,day=beginTS.day,hour=beginTS.hour,minute=beginTS.minute)
beginDS=pd.to_datetime(cfg['Calendar']['BeginDataset'],dayfirst=cfg['Calendar']['dayfirst'])
dates['UCBegin']=pd.Timestamp(year=beginDS.year,month=beginDS.month,day=beginDS.day,hour=beginDS.hour,minute=beginDS.minute)
endTS=pd.to_datetime(cfg['Calendar']['EndTimeSeries'],dayfirst=cfg['Calendar']['dayfirst'])
dates['UCEndData']=pd.Timestamp(year=endTS.year,month=endTS.month,day=endTS.day,hour=endTS.hour,minute=endTS.minute)
endDS=pd.to_datetime(cfg['Calendar']['EndDataset'],dayfirst=cfg['Calendar']['dayfirst'])
dates['UCEnd']=pd.Timestamp(year=endDS.year,month=endDS.month,day=endDS.day,hour=endDS.hour,minute=endDS.minute)
logger.info('dates: timeseries start: '+str(dates['UCBeginData'])+' end: '+str(dates['UCEndData']))
logger.info('plan4res dataset start : '+str(dates['UCBegin'])+' end: '+str(dates['UCEnd']))
dates['UCBeginDataYearP4R']=pd.Timestamp(year=dates['UCBegin'].year,month=dates['UCBeginData'].month,day=dates['UCBeginData'].day,hour=dates['UCBeginData'].hour,minute=dates['UCBeginData'].minute)
DurationTimeSeries=pd.Timedelta(dates['UCEndData']-dates['UCBeginData'])
if dates['UCBegin']<dates['UCBeginDataYearP4R']:
dates['UCBeginDataYearP4R']=pd.Timestamp(year=dates['UCBegin'].year-1,month=dates['UCBeginData'].month,day=dates['UCBeginData'].day,hour=dates['UCBeginData'].hour,minute=dates['UCBeginData'].minute)
dates['UCEndDataYearP4R']=dates['UCBeginDataYearP4R']+DurationTimeSeries
dates['UCBeginExtendedData']=dates['UCBeginDataYearP4R']
dates['UCEndExtendedData']=dates['UCEndDataYearP4R']
SSVTimeStep=cfg['Calendar']['SSVTimeStep']['Duration']
UnitSSV=cfg['Calendar']['SSVTimeStep']['Unit']
if UnitSSV=='days': SSVTimeStep=SSVTimeStep*24
if UnitSSV=='weeks': SSVTimeStep=SSVTimeStep*168
UCTimeStep=cfg['Calendar']['TimeStep']['Duration']
UnitUC=cfg['Calendar']['TimeStep']['Unit']
if UnitUC=='days': UCTimeStep=UCTimeStep*24
if UnitUC=='weeks': UCTimeStep=UCTimeStep*168
# get scenarios and convert list to string
ListScenarios=[str(elem) for elem in cfg['ParametersFormat']['Scenarios'] ]
ScenarisedData=cfg['ParametersFormat']['ScenarisedData']
# other parameters
if 'ThermalMaxPowerTimeSpan' in cfg['ParametersFormat']:
ThermalMaxPowerTimeSpan=cfg['ParametersFormat']['ThermalMaxPowerTimeSpan']['Duration']
UnitTMPTS=cfg['ParametersFormat']['ThermalMaxPowerTimeSpan']['Unit']
if UnitTMPTS=='days': ThermalMaxPowerTimeSpan=ThermalMaxPowerTimeSpan*24
if UnitTMPTS=='weeks': ThermalMaxPowerTimeSpan=ThermalMaxPowerTimeSpan*168
else:
ThermalMaxPowerTimeSpan=SSVTimeStep
CoeffSpillage=cfg['ParametersFormat']['CoeffSpillage']
# dates treatments
############################
durationData=dates.UCEndData-dates.UCBeginData+pd.Timedelta(hours=1)
durationInstance=dates.UCEnd-dates.UCBegin+pd.Timedelta(hours=1)
NumberUCTimeSteps=int((durationInstance.days*24+durationInstance.seconds/3600)/UCTimeStep)
durationUCTimeStep=pd.Timedelta(str(UCTimeStep)+' hours')
durationSSVTimeStep=pd.Timedelta(str(SSVTimeStep)+' hours')
logger.info('Duration instance:'+str(durationInstance))
if not ((durationInstance.total_seconds()/3600)/SSVTimeStep)-int((durationInstance.total_seconds()/3600)/SSVTimeStep)==0:
NewNumberUCTimeSteps=int((durationInstance.total_seconds()/3600)/SSVTimeStep)*SSVTimeStep/UCTimeStep
NumberUCTimeStepsToDelete=NumberUCTimeSteps-NewNumberUCTimeSteps
NumberUCTimeSteps=int(NewNumberUCTimeSteps)
durationToDelete=pd.Timedelta(str(NumberUCTimeStepsToDelete*UCTimeStep)+' hours')
dates['UCEnd']=dates['UCEnd']-durationToDelete
durationInstance=dates.UCEnd-dates.UCBegin+pd.Timedelta(hours=1)
logger.info('Number of time steps:'+str(NumberUCTimeSteps)+' of duration:'+str(durationUCTimeStep))
TimeHorizonUC=int(SSVTimeStep/UCTimeStep)
NumberIntervals=TimeHorizonUC
NumberSSVTimeSteps=int(NumberUCTimeSteps*UCTimeStep/SSVTimeStep)
TimeHorizonSSV=NumberSSVTimeSteps
logger.info('Number of SSV time steps:'+str(NumberSSVTimeSteps)+' of duration:'+str(TimeHorizonUC)+' timesteps = '+str(durationSSVTimeStep))
# create dataframe with start and end dates of all SSV timesteps
datesSSV=pd.DataFrame(index=list(range(NumberSSVTimeSteps)),columns=['start','end'])
start=dates['UCBegin']
for i in range(NumberSSVTimeSteps):
datesSSV.loc[i]=[start,start+durationSSVTimeStep-pd.Timedelta('1 hours')]
start=start+durationSSVTimeStep
# create dataframe with start and end dates of all UC timesteps
datesUC=pd.DataFrame(index=list(range(NumberUCTimeSteps)),columns=['start','end'])
start=dates['UCBegin']
for i in range(NumberUCTimeSteps):
datesUC.loc[i]=[start,start+durationUCTimeStep]
start=start+durationUCTimeStep
# create dataframe with start and end dates of all UC timesteps
datesData=pd.DataFrame(columns=['start','end'])
start=dates['UCBeginData']
i=0
while start<=dates['UCEndData']:
datesData.loc[i]=[start,start+durationUCTimeStep]
start=start+durationUCTimeStep
i=i+1
# check if csv files have to be modified to include results of investment_solver
CreateDataPostInvest=False # True if csv files are to be re-created former computation of investments
if 'RecomputeCSV' in cfg['ParametersFormat']:
if cfg['ParametersFormat']['RecomputeCSV'] and os.path.isfile(cfg['path']+'results_invest/Solution_OUT.csv'):
CreateDataPostInvest=True
solInvest=check_and_read_csv(cfg, cfg['path']+'results_invest/Solution_OUT.csv',header=None)
indexSolInvest=0
# Read sheet ZP_ZonePartition
#################################################################################################################################################
if 'ZP_ZonePartition' in sheets:
if format=='excel':
ZP=pd.read_excel(p4r_excel,sheet_name='ZP_ZonePartition',skiprows=0,index_col=None)
else:
ZP=read_input_csv(cfg, 'ZP_ZonePartition', skiprows=0, index_col=None)
ZP=ZP.drop_duplicates()
Nodes=ZP[Coupling['Partition'].loc['ActivePowerDemand']]
NumberNodes=len(Nodes)
NumberSlackUnits=len(Nodes) # there is one slack unit per node
# create partitions
# Partition['Leveli'] is a dictionnary whose keys are the regions at level i and values are the list of nodes in each region
Partition=pd.Series(dtype=object)
for level in ZP.columns:
if level==Coupling['Partition'].loc['ActivePowerDemand']:
Partition.loc[level]=dict(zip(list(Nodes),[ [node] for node in list(Nodes)]))
else:
keys=list(set(list(ZP[level])))
values= []
for key in keys:
values.append(list(set(list(ZP.loc[ZP[level]==key][Coupling['Partition'].loc['ActivePowerDemand']]))))
Partition.loc[level]=dict(zip(keys,values))
if 'PrimaryDemand' in Coupling.index:
NumberPrimaryZones=len(Partition.loc[Coupling['Partition']['PrimaryDemand']])
else: NumberPrimaryZones=0
if 'SecondaryDemand' in Coupling.index:
NumberSecondaryZones=len(Partition.loc[Coupling['Partition']['SecondaryDemand']])
else: NumberSecondaryZones=0
if 'InertiaDemand' in Coupling.index:
NumberInertiaZones=len(Partition.loc[Coupling['Partition']['InertiaDemand']])
else: NumberInertiaZones=0
TotalNumberPollutantZones=sum(len(Partition.loc[Coupling['Partition'][elem]]) for elem in ListPollutants)
else:
logger.error('ZP_Partition missing')
log_and_exit(2, cfg['path'])
# Read sheet ZV_ZoneValues
#################################################################################################################################################
if 'ZV_ZoneValues' in sheets:
if format=='excel':
ZV=pd.read_excel(p4r_excel,sheet_name='ZV_ZoneValues',skiprows=0,index_col=['Type', 'Zone'])
else:
ZV=read_input_csv(cfg, 'ZV_ZoneValues',skiprows=0,index_col=['Type', 'Zone'])
ZV=ZV.drop_duplicates()
if 'Profile_Timeserie' in ZV.columns:
ZV['Profile_Timeserie']=ZV['Profile_Timeserie'].fillna('')
else:
ZV['Profile_Timeserie']=''
ZV['Profile_Timeserie']=ZV['Profile_Timeserie'].fillna('')
ZV=ZV.fillna(0)
else:
logger.error('ZV_ZoneValues missing')
log_and_exit(1, cfg['path'])
InstalledCapacity=pd.DataFrame(index=Nodes)
# Read sheet SS_SeasonalStorage
#################################################################################################################################################if 'TU_ThermalUnits' in sheets:
if 'SS_SeasonalStorage' in sheets:
if format=='excel':
SS=pd.read_excel(p4r_excel,sheet_name='SS_SeasonalStorage',skiprows=skip,index_col=['Name','Zone'])
else:
SS=read_input_csv(cfg, 'SS_SeasonalStorage',skiprows=skip,index_col=['Name','Zone'])
if not SS.empty:
SS=SS.drop( SS[ SS['NumberUnits']==0 ].index )
SS=SS.drop( SS[ SS['MaxPower']==0.0 ].index )
SS['InflowsProfile']=SS['InflowsProfile'].fillna('')
SS=SS.reset_index().drop_duplicates().set_index(['Name','Zone'])
if 'WaterValues' in SS:
SS['WaterValues']=SS['WaterValues'].fillna('')
TotalNumberHydroUnits=SS['NumberUnits'].sum()
if 'HydroSystem' in SS.columns:
NumberHydroSystems=int(SS['HydroSystem'].max()+1)
else:
NumberHydroSystems=1
SS['NumberReservoirs']=1
SS['NumberArcs']=1
for reservoir in SS.index:
if 'MinPower' in SS.columns and SS['MinPower'][reservoir]<0:
SS.loc[reservoir]['NumberReservoirs']=2
SS.loc[reservoir]['NumberArcs']=2
TotalNumberReservoirs=SS['NumberReservoirs'].sum()
HSSS=pd.Series(dtype=object)
for hs in range(NumberHydroSystems):
HSSS.loc[hs]=SS[ SS['HydroSystem']==hs ]
else:
logger.warning('No seasonal storage mix in this dataset')
NumberHydroSystems=0
else:
logger.warning('No seasonal storage mix in this dataset')
NumberHydroSystems=0
# Read sheet TU_ThermalUnits
#################################################################################################################################################
if 'TU_ThermalUnits' in sheets:
if format=='excel':
TU=pd.read_excel(p4r_excel,sheet_name='TU_ThermalUnits',skiprows=skip,index_col=['Name','Zone'])
else:
TU=read_input_csv(cfg, 'TU_ThermalUnits', skiprows=skip, index_col=['Name','Zone'])
TU=TU[TU['NumberUnits'] != 0]
TU=TU.reset_index().drop_duplicates().set_index(['Name','Zone'])
if CreateDataPostInvest:
save_input_csv(cfg, 'TU_ThermalUnits',TU)
for row in TU.index:
if (TU.loc[row,'MaxAddedCapacity']>0)+(TU.loc[row,'MaxRetCapacity']>0):
if solInvest[0].loc[indexSolInvest]>1:
TU.loc[row,'MaxAddedCapacity']=TU.loc[row,'MaxAddedCapacity']-(solInvest[0].loc[indexSolInvest]-1)*TU.loc[row,'MaxPower']
if TU.loc[row,'MaxAddedCapacity']<=cfg['ParametersCreate']['zerocapacity']:
TU.loc[row,'MaxAddedCapacity']=0
if solInvest[0].loc[indexSolInvest]<1:
TU.loc[row,'MaxRetCapacity']=TU.loc[row,'MaxRetCapacity']-(1-solInvest[0].loc[indexSolInvest])*TU.loc[row,'MaxPower']
if TU.loc[row,'MaxRetCapacity']<=cfg['ParametersCreate']['zerocapacity']:
TU.loc[row,'MaxRetCapacity']=0
logger.info('Added Capacity to TU '+str(row)+' :'+str(TU.loc[row,'MaxPower']*solInvest[0].loc[indexSolInvest]-TU.loc[row,'MaxPower']))
for c in ['MaxPower', 'MinPower', 'Capacity']:
if c in TU.columns:
TU.loc[row,c] = np.round(TU.loc[row,c]*solInvest[0].loc[indexSolInvest], decimals=cfg['ParametersFormat']['RoundDecimals'])
indexSolInvest=indexSolInvest+1
write_input_csv(cfg, 'TU_ThermalUnits',TU)
TU=TU.drop( TU[ TU['NumberUnits']==0 ].index )
if ('MaxAddedCapacity' not in TU.columns and 'MaxRetCapacity' not in TU.columns):
TU=TU.drop( TU[ TU['MaxPower']<=cfg['ParametersCreate']['zerocapacity'] ].index )
else:
TU=TU.drop( TU[ ( TU['MaxPower'] <=cfg['ParametersCreate']['zerocapacity'] ) \
& ( TU['MaxAddedCapacity']<=cfg['ParametersCreate']['zerocapacity'] ) \
& ( TU['MaxRetCapacity'] <=cfg['ParametersCreate']['zerocapacity'] ) ].index )
if 'MaxPowerProfile' in TU.columns:
TU['MaxPowerProfile']=TU['MaxPowerProfile'].fillna('')
NumberThermalUnits=TU['NumberUnits'].sum()
if ('MaxAddedCapacity' in TU.columns and 'MaxRetCapacity' in TU.columns):
NumberInvestedThermalUnits=len(TU[ (TU['MaxRetCapacity']>0) | (TU['MaxAddedCapacity']>0) ])
elif 'MaxAddedCapacity' in TU.columns:
NumberInvestedThermalUnits=len(TU[ TU['MaxAddedCapacity']>0 ])
elif 'MaxRetCapacity' in TU.columns:
NumberInvestedThermalUnits=len(TU[ TU['MaxRetCapacity']>0 ])
else:
NumberInvestedThermalUnits=0
else:
logger.warning('No thermal mix in this dataset')
NumberThermalUnits=0
# Read sheet RES_RenewableUnits
#################################################################################################################################################
if 'RES_RenewableUnits' in sheets:
if format=='excel':
RES=pd.read_excel(p4r_excel,sheet_name='RES_RenewableUnits',skiprows=skip,index_col=['Name','Zone'])
else:
RES=read_input_csv(cfg, 'RES_RenewableUnits',skiprows=skip,index_col=['Name','Zone'])
RES=RES.reset_index().drop_duplicates().set_index(['Name','Zone'])
if CreateDataPostInvest:
save_input_csv(cfg, 'RES_RenewableUnits',RES)
for row in RES.index:
if (RES.loc[row,'MaxAddedCapacity']>0)+(RES.loc[row,'MaxRetCapacity']>0):
if solInvest[0].loc[indexSolInvest]>1:
RES.loc[row,'MaxAddedCapacity']=RES.loc[row,'MaxAddedCapacity']-(solInvest[0].loc[indexSolInvest]-1)*RES.loc[row,'MaxPower']
if RES.loc[row,'MaxAddedCapacity']<=cfg['ParametersCreate']['zerocapacity']:
RES.loc[row,'MaxAddedCapacity']=0
if solInvest[0].loc[indexSolInvest]<1:
RES.loc[row,'MaxRetCapacity']=RES.loc[row,'MaxRetCapacity']-(1-solInvest[0].loc[indexSolInvest])*RES.loc[row,'MaxPower']
if RES.loc[row,'MaxRetCapacity']<=cfg['ParametersCreate']['zerocapacity']:
RES.loc[row,'MaxRetCapacity']=0
logger.info('Added Capacity to RES '+str(row)+' :'+str(RES.loc[row,'MaxPower']*solInvest[0].loc[indexSolInvest]-RES.loc[row,'MaxPower']))
for c in ['MaxPower', 'MinPower', 'Capacity']:
if c in RES.columns:
RES.loc[row,c] = np.round(RES.loc[row,c]*solInvest[0].loc[indexSolInvest], decimals=cfg['ParametersFormat']['RoundDecimals'])
indexSolInvest=indexSolInvest+1
write_input_csv(cfg, 'RES_RenewableUnits',RES)
RES=RES.drop( RES[ RES['NumberUnits']==0 ].index )
if ('MaxAddedCapacity' not in RES.columns and 'MaxRetCapacity' not in RES.columns):
RES=RES.drop( RES[ RES['MaxPower']<=cfg['ParametersCreate']['zerocapacity'] ].index )
else:
RES=RES.drop( RES[ (RES['MaxPower']<=cfg['ParametersCreate']['zerocapacity']) & ( RES['MaxAddedCapacity']<=cfg['ParametersCreate']['zerocapacity']) & (RES['MaxRetCapacity']<=cfg['ParametersCreate']['zerocapacity'] ) ].index )
if 'Energy_Timeserie' in RES.columns and 'Energy' in RES.columns:
RES['EnergyMaxPower']=RES.apply(lambda x: x.Energy if x.Name=="Hydro|Run of River" else x.Energy_Timeserie*x.MaxPower,axis=1)
RES['MaxPowerProfile']=RES['MaxPowerProfile'].fillna('')
NumberIntermittentUnits=RES['NumberUnits'].sum()
if ('MaxAddedCapacity' in RES.columns and 'MaxRetCapacity' in RES.columns):
NumberInvestedIntermittentUnits=len(RES[ (RES['MaxRetCapacity']>0) | (RES['MaxAddedCapacity']>0) ])
elif 'MaxAddedCapacity' in RES.columns:
NumberInvestedIntermittentUnits=len(RES[ RES['MaxAddedCapacity']>0 ])
elif 'MaxRetCapacity' in RES.columns:
NumberInvestedIntermittentUnits=len(RES[ RES['MaxRetCapacity']>0 ])
else:
NumberInvestedIntermittentUnits=0
else:
logger.warning('No intermittent generation mix in this dataset')
NumberIntermittentUnits=0
# Read sheet STS_ShortTermStorage
#################################################################################################################################################
if 'STS_ShortTermStorage' in sheets:
if format=='excel':
STS=pd.read_excel(p4r_excel,sheet_name='STS_ShortTermStorage',skiprows=skip,index_col=['Name','Zone'])
else:
STS=read_input_csv(cfg, 'STS_ShortTermStorage',skiprows=skip,index_col=['Name','Zone'])
STS=STS.reset_index().drop_duplicates().set_index(['Name','Zone'])
if CreateDataPostInvest:
save_input_csv(cfg, 'STS_ShortTermStorage',STS)
for row in STS.index:
if (STS.loc[row,'MaxAddedCapacity']>0)+(STS.loc[row,'MaxRetCapacity']>0):
if solInvest[0].loc[indexSolInvest]>1:
STS.loc[row,'MaxAddedCapacity']=STS.loc[row,'MaxAddedCapacity']-(solInvest[0].loc[indexSolInvest]-1)*STS.loc[row,'MaxPower']
if STS.loc[row,'MaxAddedCapacity']<=cfg['ParametersCreate']['zerocapacity']:
STS.loc[row,'MaxAddedCapacity']=0
if solInvest[0].loc[indexSolInvest]<1:
STS.loc[row,'MaxRetCapacity']=STS.loc[row,'MaxRetCapacity']-(1-solInvest[0].loc[indexSolInvest])*STS.loc[row,'MaxPower']
if STS.loc[row,'MaxRetCapacity']<=cfg['ParametersCreate']['zerocapacity']:
STS.loc[row,'MaxRetCapacity']=0
logger.info('Added Capacity to STS '+str(row)+' :'+str(STS.loc[row,'MaxPower']*solInvest[0].loc[indexSolInvest]-STS.loc[row,'MaxPower']))
for c in ['MaxPower', 'MinPower', 'Capacity','MaxVolume','MinVolume']:
if c in STS.columns:
STS.loc[row,c] = np.round(STS.loc[row,c]*solInvest[0].loc[indexSolInvest], decimals=cfg['ParametersFormat']['RoundDecimals'])
indexSolInvest=indexSolInvest+1
write_input_csv(cfg, 'STS_ShortTermStorage',STS)
STS=STS.drop( STS[ STS['NumberUnits']==0 ].index )
if ('MaxAddedCapacity' not in STS.columns and 'MaxRetCapacity' not in STS.columns):
STS=STS.drop( STS[ STS['MaxPower']<=cfg['ParametersCreate']['zerocapacity'] ].index )
else:
STS=STS.drop( STS[ (STS['MaxPower']<=cfg['ParametersCreate']['zerocapacity']) & (STS['MaxAddedCapacity']<=cfg['ParametersCreate']['zerocapacity']) & (STS['MaxRetCapacity']<=cfg['ParametersCreate']['zerocapacity'] ) ].index )
NumberBatteryUnits=STS['NumberUnits'].sum()
if ('MaxAddedCapacity' in STS.columns and 'MaxRetCapacity' in STS.columns):
NumberInvestedBatteryUnits=len(STS[ (STS['MaxRetCapacity']>0) | (STS['MaxAddedCapacity']>0) ])
elif 'MaxAddedCapacity' in STS.columns:
NumberInvestedBatteryUnits=len(STS[ STS['MaxAddedCapacity']>0 ])
elif 'MaxRetCapacity' in STS.columns:
NumberInvestedBatteryUnits=len(STS[ STS['MaxRetCapacity']>0 ])
else:
NumberInvestedBatteryUnits=0
else:
logger.warning('No short term storage mix in this dataset')
NumberBatteryUnits=0
# Read sheet SYN SynchCond
#################################################################################################################################################
if 'SYN_SynchCond' in sheets:
if format=='excel':
SYN=pd.read_excel(p4r_excel,sheet_name='SYN_SynchCond',skiprows=skip,index_col=None)
else:
SYN=pd.read_excel(cfg['inputpath']+cfg['csvfiles']['SYN_SynchCond'],skiprows=skip,index_col=None)
SYN=SYN.drop( SYN[ SYN['NumberUnits']==0 ].index )
SYN=SYN.drop( SYN[ SYN['MaxRotatingConsumption']==0.0 ].index )
SYN=SYN.drop_duplicates()
SYN=SYN.set_index(['Name','Zone'])
NumberSyncUnits=SYN['NumberUnits'].sum()
else:
logger.warning('No synchronous condensers mix in this dataset')
NumberSyncUnits=0
# Read sheet IN_Interconnections
#################################################################################################################################################
if 'IN_Interconnections' in sheets:
if format=='excel':
IN=pd.read_excel(p4r_excel,sheet_name='IN_Interconnections',skiprows=skip,index_col=0)
else:
IN=read_input_csv(cfg, 'IN_Interconnections', skiprows=skip,index_col=0)
if CreateDataPostInvest:
save_input_csv(cfg, 'IN_Interconnections',IN,index=True)
for row in IN.index:
if (IN.loc[row,'MaxAddedCapacity']>0)+(IN.loc[row,'MaxRetCapacity']>0):
if solInvest[0].loc[indexSolInvest]>1:
IN.loc[row,'MaxAddedCapacity']=IN.loc[row,'MaxAddedCapacity']-(solInvest[0].loc[indexSolInvest]-1)*IN.loc[row,'MaxPowerFlow']
if IN.loc[row,'MaxAddedCapacity']<=cfg['ParametersCreate']['zerocapacity']:
IN.loc[row,'MaxAddedCapacity']=0
if solInvest[0].loc[indexSolInvest]<1:
IN.loc[row,'MaxRetCapacity']=IN.loc[row,'MaxRetCapacity']-(1-solInvest[0].loc[indexSolInvest])*IN.loc[row,'MaxPowerFlow']
if IN.loc[row,'MaxRetCapacity']<=cfg['ParametersCreate']['zerocapacity']:
IN.loc[row,'MaxRetCapacity']=0
logger.info('Added Capacity to IN '+str(row)+' :'+str(IN.loc[row,'MaxPowerFlow']*solInvest[0].loc[indexSolInvest]-IN.loc[row,'MaxPowerFlow']))
for c in ['MaxPowerFlow', 'MinPowerFlow']:
if c in IN.columns:
IN.loc[row,c] = np.round(IN.loc[row,c]*solInvest[0].loc[indexSolInvest], decimals=cfg['ParametersFormat']['RoundDecimals'])
indexSolInvest=indexSolInvest+1
write_input_csv(cfg, 'IN_Interconnections',IN,index=True)
if ('MaxAddedCapacity' not in IN.columns and 'MaxRetCapacity' not in IN.columns):
IN=IN.drop( IN[ (IN['MaxPowerFlow']<=cfg['ParametersCreate']['zerocapacity']) & (IN['MinPowerFlow']>=(-1)*cfg['ParametersCreate']['zerocapacity']) ].index )
else:
IN=IN.drop( IN[ (IN['MaxPowerFlow']<=cfg['ParametersCreate']['zerocapacity']) & (IN['MinPowerFlow']>=(-1)*cfg['ParametersCreate']['zerocapacity']) & (IN['MaxAddedCapacity']<=cfg['ParametersCreate']['zerocapacity']) & (IN['MaxRetCapacity']<=cfg['ParametersCreate']['zerocapacity']) ].index )
IN=IN.drop_duplicates()
NumberLines=len(IN.index)
if ('MaxAddedCapacity' in IN.columns and 'MaxRetCapacity' in IN.columns):
NumberInvestedLines=len(IN[ (IN['MaxRetCapacity']>0) | (IN['MaxAddedCapacity']>0) ])
elif 'MaxAddedCapacity' in IN.columns:
NumberInvestedLines=len(IN[ IN['MaxAddedCapacity']>0 ])
elif 'MaxRetCapacity' in IN.columns:
NumberInvestedLines=len(IN[ IN['MaxRetCapacity']>0 ])
else:
NumberInvestedLines=0
else:
logger.warning('No interconnections in this dataset')
NumberLines=0
#################################################################################################################################################
# #
# Compute data #
# #
# #
#################################################################################################################################################
NumberUnits=NumberHydroSystems+NumberThermalUnits+NumberBatteryUnits+NumberIntermittentUnits+NumberSyncUnits+NumberSlackUnits
if NumberHydroSystems>0:
NumberArcs=SS['NumberArcs'].sum()
NumberHydroUnits=int(SS['NumberUnits'].sum())
else:
NumberArcs=0
NumberHydroUnits=0
NumberElectricalGenerators=NumberArcs+NumberThermalUnits+NumberBatteryUnits+NumberIntermittentUnits+NumberSyncUnits+NumberSlackUnits
logger.info(str(NumberHydroSystems)+' Hydrosystems')
logger.info(str(NumberHydroUnits)+' Hydro Units with '+str(NumberArcs)+' generators')
logger.info(str(NumberThermalUnits)+' Thermal Units')
logger.info(str(NumberBatteryUnits)+' Short term Storage Units')
logger.info(str(NumberIntermittentUnits)+' Intermittent Units')
logger.info(str(NumberSyncUnits)+' Synchronous condensers')
logger.info(str(NumberSlackUnits)+' Slack Units')
logger.info(str(NumberUnits)+' units, '+str(NumberElectricalGenerators)+' generators')
#################################################################################################################################################
# #
# Read timeseries #
# #
# #
#################################################################################################################################################
def ExtendAndResample(name,TS,isEnergy=True):
# change timeindex to adapt to dataset calendarb
beginSerie=TS.index[0]
if beginSerie>dates['UCBeginDataYearP4R']:
datesDelta=pd.Timedelta(beginSerie-dates['UCBeginDataYearP4R'])
TS.index=TS.index-datesDelta
else:
datesDelta=pd.Timedelta(dates['UCBeginDataYearP4R']-beginSerie)
TS.index=TS.index+datesDelta
# Extension is a copy of TS on the extended dates UCBeginExtendedData and UCEndExtendedData
Extension=TS[ TS.index>= dates['UCBeginExtendedData'] ]
Extension=Extension[ Extension.index<= dates['UCEndExtendedData'] ]
# resample
newfreq=str(UCTimeStep)+'h'
TS_freq=pd.infer_freq(TS.index)
# upsample=True means that timeseries is given at a frequency
# bigger than hour (eg 2 hours, daily, weekly)
upsample=False
# calcul de la frequence de la série en nombre d'heures
if 'D' in TS_freq or 'W' in TS_freq or 'M' in TS_freq:
upsample=True
if 'D' in TS_freq:
if len(TS_freq)>1:
Hours_freq=int(TS_freq[:-1])*24
else:
Hours_freq=24
if 'W' in TS_freq:
if '-' in TS_freq: TS_freq=TS_freq.split('-')[0]
if len(TS_freq)>1:
Hours_freq=int(TS_freq[:-1])*168
else:
Hours_freq=168
if 'M' in TS_freq:
if len(TS_freq)>1:
Hours_freq=int(TS_freq[:-1])*728
else:
Hours_freq=728
if 'H' in TS_freq or 'h' in TS_freq:
if len(TS_freq)>1:
Hours_freq=int(TS_freq[:-1])
else:
Hours_freq=1
if Hours_freq>int(UCTimeStep): upsample=True
duration_TS_timestep=pd.Timedelta(str(Hours_freq)+' hours')
if Hours_freq==1:
Extension.index=Extension.index+durationData
else:
Extension.index=Extension.index+pd.Timedelta(TS.index[-1]-TS.index[0])+pd.Timedelta(str(Hours_freq)+' hours')
TS=pd.concat([TS,Extension])
# case where timeserie is given at frequency bigger than hour
# resample to hour frequecy before resampling to the required frequency
if upsample:
TS=TS.resample('h').ffill() # convert to hourly frequency
# extend with missing dates: duplicate last dates
if TS.index[-1]< dates['UCEnd']:
dur_missing=dates['UCEnd']-TS.index[-1] # compute duration of missing data
Extension=TS[ TS.index> (TS.index[-1]-dur_missing) ] # take last period of TS of this duration
Extension.index=Extension.index+dur_missing # shift over time
TS=pd.concat([TS,Extension]) # add at end of serie
TS=TS.resample(newfreq).sum()
else:
TS=TS.resample(newfreq).sum()
# keep only period of dataset
TS=TS[ TS.index>= dates['UCBegin'] ]
TS=TS[ TS.index<= dates['UCEnd'] ]
# case where there is only one value in TS_freq
if len(TS.index)==1:
TS2=TS[ TS.index>= dates['UCBegin'] ]
TS2.index=TS2.index+pd.Timedelta(str(Hours_freq)+' hours')
TS=pd.concat([TS,TS2])
return TS
def read_deterministic_timeseries(IsDT):
if IsDT:
DeterministicTS=pd.read_csv(cfg['inputpath']+cfg['DeterministicTimeSeries'],index_col=0)
DeterministicTS.index=pd.to_datetime(DeterministicTS.index,dayfirst=cfg['Calendar']['dayfirst'])
DeterministicTS=ExtendAndResample('DET',DeterministicTS)
# add constant serie
DeterministicTS['One']=1.0
DeterministicTS['Zero']=0.0
else:
DeterministicTS=pd.DataFrame(index=datesData['start'])
DeterministicTS.index=pd.to_datetime(DeterministicTS.index)
DeterministicTS['One']=1.0
DeterministicTS['Zero']=0.0
DeterministicTS=ExtendAndResample('DET',DeterministicTS)
return DeterministicTS
def create_demand_scenarios():
DemandScenarios=pd.Series(dtype=object)
isEnergy=(cfg['ParametersFormat']['ScenarisedData']['ActivePowerDemand']['MultiplyTimeSerieBy']=='Energy')
for node in Nodes:
firstPart=True
for component in Coupling.loc['ActivePowerDemand']['Sum']:
nameTS=ZV.loc[component,node]['Profile_Timeserie']
valTS=ZV.loc[component,node]['value']
# case without a profile
if nameTS=='':
if firstPart:
DemandScenarios.loc[node]=pd.DataFrame(columns=ListScenarios)
for col in ListScenarios: DemandScenarios.loc[node][col]=DeterministicTimeSeries['One']
firstPart=False
else:
for col in ListScenarios: DemandScenarios.loc[node][col]=DemandScenarios.loc[node][col]+DeterministicTimeSeries['One']
# read timeserie if deterministic
elif '.csv' in nameTS: # stochastic OR deterministic series
isDeterministic=False
TS=read_input_timeseries(cfg, nameTS, skiprows=0,index_col=0)
if len(TS.columns)==1: isDeterministic=True # the serie is deterministic
TS.index=pd.to_datetime(TS.index,dayfirst=cfg['Calendar']['dayfirst'])
TS=ExtendAndResample(nameTS,TS,isEnergy)
if firstPart:
DemandScenarios[node]=pd.DataFrame(index=TS.index,columns=ListScenarios)
if isDeterministic:
for col in ListScenarios: DemandScenarios.loc[node][col]=valTS*TS[TS.columns.tolist()[0]]
else: DemandScenarios[node]=valTS*TS
firstPart=False
else:
if isDeterministic:
for col in ListScenarios: DemandScenarios.loc[node][col]=DemandScenarios.loc[node][col]+valTS*TS[TS.columns.tolist()[0]]
else: DemandScenarios[node]=DemandScenarios.loc[node]+valTS*TS
else:
# deterministic serie in DeterministicTimeSeries dataframe
DTS=valTS*DeterministicTimeSeries[nameTS]
if firstPart:
DemandScenarios.loc[node]=pd.DataFrame(columns=ListScenarios)
for col in ListScenarios: DemandScenarios.loc[node][col]=DTS
firstPart=False
else:
for col in ListScenarios: DemandScenarios.loc[node][col]=DemandScenarios.loc[node][col]+DTS
return DemandScenarios
def create_inflows_scenarios():
isEnergy=(cfg['ParametersFormat']['ScenarisedData']['Hydro:Inflows']['MultiplyTimeSerieBy']['reservoir']=='Energy')
InflowsScenarios=pd.Series(dtype=object,index=SS.index)
for reservoir in SS.index:
nameTS=SS.loc[reservoir]['InflowsProfile']
valTS=SS.loc[reservoir]['Inflows']
# read timeserie
# case without a profile
if nameTS=='':
InflowsScenarios[reservoir]=pd.DataFrame(columns=ListScenarios)
for col in ListScenarios: InflowsScenarios.loc[reservoir][col]=(valTS/cfg['ParametersFormat']['NumberHoursInYear'])*DeterministicTimeSeries['One'] # valTS is an energy per year
elif '.csv' in nameTS: # stochastic series
TS=read_input_timeseries(cfg, nameTS, index_col=0)
TS.index=pd.to_datetime(TS.index,dayfirst=cfg['Calendar']['dayfirst'])
TS=ExtendAndResample(nameTS,TS,isEnergy)
if len(TS.columns) > 1: # stochastic serie
InflowsScenarios[reservoir]=pd.DataFrame(index=TS.index,columns=TS.columns)
InflowsScenarios[reservoir]=valTS*TS
else: # deterministic serie
InflowsScenarios[reservoir]=pd.DataFrame(index=TS.index,columns=ListScenarios)
for col in ListScenarios: InflowsScenarios.loc[reservoir][col]=valTS*TS[TS.columns.tolist()[0]]
else: # deterministic series
DTS=valTS*DeterministicTimeSeries[nameTS]
InflowsScenarios.loc[reservoir]=pd.DataFrame(columns=ListScenarios)
for col in ListScenarios: InflowsScenarios.loc[reservoir][col]=DTS
return InflowsScenarios
def create_res_scenarios():
ResScenarios=pd.Series(dtype=object,index=RES.index)
newIndex=[]
for res in RES.index:
nameTS=RES.loc[res]['MaxPowerProfile']
valTS=RES.loc[res]['MaxPower']
nameAsset=res[0]
technoAsset = None
for namekind in cfg['technos']:
for nametechno in cfg['technos'][namekind]:
if nametechno in nameAsset:
technoAsset=namekind
if technoAsset is None:
logger.error('The techno for '+str(res)+' described in file RES_RenewableUnits.csv could not be identified. Check the data listed under the "technos" key in the configuration files.')
log_and_exit(2, cfg['path'])
isEnergy=(cfg['ParametersFormat']['ScenarisedData']['Renewable:MaxPowerProfile']['MultiplyTimeSerieBy'][technoAsset]=='Energy')
# read timeserie
if '.csv' in nameTS: # stochastic series
TS=read_input_timeseries(cfg, nameTS, skiprows=0,index_col=0)
TS.index=pd.to_datetime(TS.index,dayfirst=cfg['Calendar']['dayfirst'])
TS=ExtendAndResample(nameTS,TS,isEnergy)
if len(TS.columns) > 1: # stochastic serie
ResScenarios[res]=pd.DataFrame(index=TS.index,columns=TS.columns)
ResScenarios[res]=valTS*TS
else: #deterministic
ResScenarios[res]=pd.DataFrame(index=TS.index,columns=ListScenarios)
for col in ListScenarios: ResScenarios[res][col]=valTS*TS[TS.columns.tolist()[0]]
newIndex.append(res)
#
ResScenarios=ResScenarios[ newIndex ]
return ResScenarios
def create_thermal_scenarios():
# define wether there is one profile per techno/region, or one profile per unit
newIndex=[]
isEnergy=(cfg['ParametersFormat']['ScenarisedData']['Thermal:MaxPowerProfile']['MultiplyTimeSerieBy']=='Energy')
if True in np.column_stack(TU['MaxPowerProfile'].str.contains(r",", na=False)): # there exist multiple profiles for the same row
multipleTHSeries=True
listIndexes=[list(TU.index[0]),list(TU.index[1]),list(range(TU['NumberUnits'].max()))]
ThermalScenarios=pd.Series(dtype=object,index=pd.MultiIndex.from_tuples((list(product(*listIndexes)))))
for th in TU.index:
for unit in range(TU.loc[th]['NumberUnits']):
if ',' in str(TU.loc[th]['MaxPowerProfile']):
nameTS=TU.loc[th]['MaxPowerProfile'].split(',')[unit]
else:
nameTS=TU.loc[th]['MaxPowerProfile']
valTS=TU.loc[th]['MaxPower']
# read timeserie
if '.csv' in nameTS: # stochastic series
TS=read_input_timeseries(cfg, nameTS,skiprows=0,index_col=0)
TS.index=pd.to_datetime(TS.index,dayfirst=cfg['Calendar']['dayfirst'])
TS=ExtendAndResample(nameTS,TS,isEnergy)
if len(TS.columns) > 1: # stochastic serie
ThermalScenarios[th[0],th[1],unit]=pd.DataFrame(index=TS.index,columns=TS.columns)
ThermalScenarios[th[0],th[1],unit]=valTS*TS
else:
ThermalScenarios[th[0],th[1],unit]=pd.DataFrame(index=TS.index,columns=ListScenarios)
for col in ListScenarios: ThermalScenarios[th[0],th[1],unit]=valTS*TS[TS.columns.tolist()[0]]
newIndex.append( (th[0],th[1],unit) )
else:
multipleTHSeries=False
ThermalScenarios=pd.Series(dtype=object,index=TU.index)
for th in TU.index:
nameTS=TU.loc[th]['MaxPowerProfile']
valTS=TU.loc[th]['MaxPower']
# read timeserie
if '.csv' in nameTS: # stochastic series
TS=read_input_timeseries(cfg,nameTS,skiprows=0,index_col=0)
TS.index=pd.to_datetime(TS.index,dayfirst=cfg['Calendar']['dayfirst'])
TS=ExtendAndResample(nameTS,TS)
if len(TS.columns) > 1: # stochastic serie
ThermalScenarios[th]=pd.DataFrame(index=TS.index,columns=TS.columns)
ThermalScenarios[th]=valTS*TS
else:
ThermalScenarios[th]=pd.DataFrame(index=TS.index,columns=ListScenarios)
for col in ListScenarios: ThermalScenarios[th]=valTS*TS[TS.columns.tolist()[0]]
newIndex.append(th)
ThermalScenarios=ThermalScenarios[newIndex]
return ThermalScenarios
#################################################################################################################################################
# #
# Create netcDF files #
# #
# #
#################################################################################################################################################
# create the HydroUnitBlocks
def addHydroUnitBlocks(Block,indexUnitBlock,scenario,start,end,id):
for hydrosystem in range(NumberHydroSystems):
# create all hydrosystems
HSBlock=Block.createGroup('UnitBlock_'+str(indexUnitBlock))
HSBlock.type="HydroSystemUnitBlock"
NumberHydroUnitsInHydroSystem=len(HSSS.loc[hydrosystem].index)
HSBlock.createDimension("NumberHydroUnits",NumberHydroUnitsInHydroSystem)
indexHU=0
NumberReservoirsInHydroSystem=0
for hydrounit in HSSS.loc[hydrosystem].index:
# create all hydro units
for index_subunit in range(HSSS.loc[hydrosystem]['NumberUnits'][hydrounit]):
HBlock=HSBlock.createGroup('HydroUnitBlock_'+str(indexHU))
HBlock.type="HydroUnitBlock"
HBlock.setncattr("name",hydrounit[0]+'_'+hydrounit[1]+'_'+str(index_subunit))
NumberReservoirs=HSSS.loc[hydrosystem]['NumberReservoirs'][hydrounit]
NumberReservoirsInHydroSystem=NumberReservoirsInHydroSystem+NumberReservoirs
HBlock.createDimension("NumberReservoirs",NumberReservoirs)
NumberArcs=HSSS.loc[hydrosystem]['NumberArcs'][hydrounit]
HBlock.createDimension("NumberArcs",NumberArcs)
HBlock.createDimension("NumberIntervals",NumberIntervals)
# create arcs
StartArc=HBlock.createVariable("StartArc","u4",("NumberArcs"))
EndArc=HBlock.createVariable("EndArc","u4",("NumberArcs"))
if NumberArcs ==1:
StartArc[:]=[0]
EndArc[:]=[1]
elif NumberArcs ==2:
StartArc[:]=[0,1]
EndArc[:]=[1,0]
# create min and max volume
MaxVolumeData=HSSS.loc[hydrosystem]['MaxVolume'][hydrounit]
if type(MaxVolumeData)==str:
MaxVolumetric=HBlock.createVariable("MaxVolumetric",np.double,("NumberReservoirs","NumberIntervals"))
vmax=DeterministicTimeSeries[MaxVolumeData][ ( DeterministicTimeSeries.index >= start ) & ( DeterministicTimeSeries.index <= end ) ]
if NumberReservoirs==1:
MaxVolumetric[0,:]=vmax
else:
MaxVolumetric[0,:]=vmax
MaxVolumetric[1,:]=cfg['DownReservoirVolumeMultFctor']*vmax
else:
MaxVolumetric=HBlock.createVariable("MaxVolumetric",np.double,("NumberReservoirs"))
if NumberReservoirs==1:
MaxVolumetric[0]=[MaxVolumeData]
elif NumberReservoirs==2:
MaxVolumetric[0]=[MaxVolumeData]
MaxVolumetric[1]=[cfg['DownReservoirVolumeMultFctor']*MaxVolumeData]
vmax=MaxVolumeData*DeterministicTimeSeries['One'][ ( DeterministicTimeSeries.index >= start ) & ( DeterministicTimeSeries.index <= end ) ]
if 'MinVolume' in SS.columns:
MinVolumeData=HSSS.loc[hydrosystem]['MinVolume'][hydrounit]
if type(MinVolumeData)==str:
MinVolumetric=HBlock.createVariable("MinVolumetric",np.double,("NumberReservoirs","NumberIntervals"))
if NumberReservoirs==1:
MinVolumetric[0,:]=np.minimum(vmax,DeterministicTimeSeries[MinVolumeData][ ( DeterministicTimeSeries.index >= start ) & ( DeterministicTimeSeries.index <= end ) ])
elif NumberReservoirs==2:
MinVolumetric[0,:]=np.minimum(vmax,DeterministicTimeSeries[MinVolumeData][ ( DeterministicTimeSeries.index >= start ) & ( DeterministicTimeSeries.index <= end ) ])
MinVolumetric[1,:]=np.array(DeterministicTimeSeries['Zero'][ ( DeterministicTimeSeries.index >= start ) & ( DeterministicTimeSeries.index <= end ) ])
else:
if type(MaxVolumeData)==str and ( (MinVolumeData>vmax).isin([True]).sum()>0 ):
MinVolumetric=HBlock.createVariable("MinVolumetric",np.double,("NumberReservoirs","NumberIntervals"))
if NumberReservoirs==1:
MinVolumetric[0,:]=np.minimum(vmax,MinVolumeData*DeterministicTimeSeries['One'][ ( DeterministicTimeSeries.index >= start ) & ( DeterministicTimeSeries.index <= end ) ])
elif NumberReservoirs==2:
MinVolumetric[0,:]=np.minimum(vmax,MinVolumeData*DeterministicTimeSeries['One'][ ( DeterministicTimeSeries.index >= start ) & ( DeterministicTimeSeries.index <= end ) ])
MinVolumetric[1,:]=np.array(DeterministicTimeSeries['Zero'][ ( DeterministicTimeSeries.index >= start ) & ( DeterministicTimeSeries.index <= end ) ])
else:
MinVolumetric=HBlock.createVariable("MinVolumetric",np.double,("NumberReservoirs"))
if NumberReservoirs==1:
MinVolumetric[0]=[MinVolumeData]
elif NumberReservoirs==2:
MinVolumetric[0]=[MinVolumeData]
MinVolumetric[1]=[0.0]
# create inflows
if ('Inflows' in SS.columns) and ('InflowsProfile' in SS.columns):
Inflows=HBlock.createVariable("Inflows",np.double,("NumberReservoirs","NumberIntervals"))
InflowsData=HSSS.loc[hydrosystem]['Inflows'][hydrounit]
InflowsDataProfile=HSSS.loc[hydrosystem]['InflowsProfile'][hydrounit]
if cfg['IncludeScenarisedData'] and 'Hydro:Inflows' in ScenarisedData:
inflow=np.array(InflowsScenarios.loc[hydrounit][scenario][ ( InflowsScenarios.loc[hydrounit].index >= start ) & ( InflowsScenarios.loc[hydrounit].index <= end ) ])
else:
inflow=np.array(DeterministicTimeSeries['Zero'][ ( DeterministicTimeSeries.index >= start ) & ( DeterministicTimeSeries.index <= end ) ])
if NumberReservoirs==1:
Inflows[0,:]=inflow
elif NumberReservoirs==2:
Inflows[0,:]=inflow
Inflows[1,:]=np.array(DeterministicTimeSeries['Zero'][ ( DeterministicTimeSeries.index >= start ) & ( DeterministicTimeSeries.index <= end ) ])
elif ('Inflows' in SS.columns) and ('InflowsProfile' not in SS.columns):
InflowsData=HSSS.loc[hydrosystem]['Inflows'][hydrounit]
Inflows=HBlock.createVariable("Inflows",np.double,("NumberReservoirs"))
if NumberReservoirs==1:
Inflows[0]=[InflowsData]
elif NumberReservoirs==2:
Inflows[0]=[InflowsData]
Inflows[1]=[0.0]
elif ('Inflows' not in SS.columns) and ('InflowsProfile' in SS.columns):
Inflows=HBlock.createVariable("Inflows",np.double,("NumberReservoirs","NumberIntervals"))
InflowsDataProfile=HSSS.loc[hydrosystem]['InflowsProfile'][hydrounit]
if cfg['IncludeScenarisedData'] and 'Hydro:Inflows' in ScenarisedData:
inflow=np.array(InflowsScenarios.loc[hydrounit][scenario][ ( InflowsScenarios.loc[hydrounit].index >= start ) & ( InflowsScenarios.loc[hydrounit].index <= end ) ])
else:
inflow=np.array(DeterministicTimeSeries['Zero'][ ( DeterministicTimeSeries.index >= start ) & ( DeterministicTimeSeries.index <= end ) ])
if NumberReservoirs==1:
Inflows[0,:]=inflow
elif NumberReservoirs==2:
Inflows[0,:]=inflow
Inflows[1,:]=np.array(DeterministicTimeSeries['Zero'][ ( DeterministicTimeSeries.index >= start ) & ( DeterministicTimeSeries.index <= end ) ])
# create min and max power and flow
MaxPowerData=HSSS.loc[hydrosystem]['MaxPower'][hydrounit]
if 'TurbineEfficiency' in SS.columns: TurbineEfficiency=HSSS.loc[hydrosystem]['TurbineEfficiency'][hydrounit]
else: TurbineEfficiency=1
if 'PumpingEfficiency' in SS.columns: PumpingEfficiency=HSSS.loc[hydrosystem]['PumpingEfficiency'][hydrounit]
else: PumpingEfficiency=cfg['PumpingEfficiency']['reservoir']['Reservoir']
if type(MaxPowerData)==str:
MaxFlow=HBlock.createVariable("MaxFlow",np.double,("NumberIntervals","NumberArcs"))
MaxPower=HBlock.createVariable("MaxPower",np.double,("NumberIntervals","NumberArcs"))
pmax=DeterministicTimeSeries[MaxPowerData][ ( DeterministicTimeSeries.index >= start ) & ( DeterministicTimeSeries.index <= end ) ]
Pmax=pd.DataFrame(pmax)
if NumberArcs==1:
Pmax['Spillage']=CoeffSpillage*pmax
Pmax=Pmax.transpose()
Flow=(1+CoeffSpillage)*(1/TurbineEfficiency)*Pmax
Pmax['Spillage']=DeterministicTimeSeries['Zero'][ ( DeterministicTimeSeries.index >= start ) & ( DeterministicTimeSeries.index <= end ) ]
for t in range(NumberIntervals):
MaxPower[t,:]=np.array(Pmax[t])
MaxFlow[t,:]=np.array(Flow[t])
elif NumberArcs==2:
Pmax['zero']=0.0
Pmax['Spillage']=CoeffSpillage*pmax
Pmax=Pmax.transpose()
Flow=(1+CoeffSpillage)*(1/TurbineEfficiency)*Pmax
Pmax['Spillage']=DeterministicTimeSeries['Zero'][ ( DeterministicTimeSeries.index >= start ) & ( DeterministicTimeSeries.index <= end ) ]
for t in range(NumberIntervals):
MaxPower[t,:]=np.array(Pmax[t])
MaxFlow[t,:]=np.array(Flow[t])
else:
MaxFlow=HBlock.createVariable("MaxFlow",np.double,("NumberArcs"))
MaxPower=HBlock.createVariable("MaxPower",np.double,("NumberArcs"))