-
Notifications
You must be signed in to change notification settings - Fork 21
/
runbatch.py
1622 lines (1431 loc) · 70.6 KB
/
runbatch.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
#%% ===========================================================================
### --- IMPORTS ---
### ===========================================================================
import os
import queue
import threading
import time
import shutil
import csv
import numpy as np
import pandas as pd
import subprocess
import re
from datetime import datetime
import argparse
from builtins import input
from glob import glob
#%% Constants
LINUXORMAC = True if os.name == 'posix' else False
YAMPASERVERS = ['constellation01','cepheus','corvus','dorado','delphinus']
#%% ===========================================================================
### --- FUNCTIONS ---
### ===========================================================================
def writeerrorcheck(checkfile, errorcode=17):
"""
Inputs
------
checkfile: Filename to check. If it does not exist, stop the run.
errorcode: Value to return if check fails. Should be >0.
"""
if LINUXORMAC:
return f'if [ ! -f {checkfile} ]; then echo "missing {checkfile}"; exit {errorcode}; fi\n'
else:
return f'\nif not exist {checkfile} (\n echo file {checkfile} missing \n goto:eof \n) \n \n'
def writescripterrorcheck(script, errorcode=18):
"""
"""
if LINUXORMAC:
return f'if [ $? != 0 ]; then echo "{script} returned $?" >> gamslog.txt; exit {errorcode}; fi\n'
else:
return f'if not %errorlevel% == 0 (echo {script} returned %errorlevel%\ngoto:eof\n)\n'
def write_delete_file(checkfile, deletefile, PATH):
if LINUXORMAC:
PATH.writelines(f"if [ -f {checkfile} ]; then rm {deletefile}; fi\n")
else:
PATH.writelines("if exist " + checkfile + " (del " + deletefile + ')\n' )
def comment(text, PATH):
commentchar = '#' if LINUXORMAC else '::'
PATH.writelines(f'{commentchar} {text}\n')
def big_comment(text, PATH):
commentchar = '#' if LINUXORMAC else '::'
PATH.writelines(f'\n{commentchar}\n')
comment(text, PATH)
PATH.writelines(f'{commentchar}\n')
def get_ivt_numclass(reeds_path, casedir, caseSwitches):
"""
Extend ivt if necessary and calculate numclass
"""
ivt = pd.read_csv(
os.path.join(
reeds_path, 'inputs', 'userinput', 'ivt_{}.csv'.format(caseSwitches['ivt_suffix'])),
index_col=0)
ivt_step = pd.read_csv(os.path.join(reeds_path, 'inputs', 'userinput', 'ivt_step.csv'),
index_col=0).squeeze(1)
lastdatayear = max([int(c) for c in ivt.columns])
addyears = list(range(lastdatayear + 1, int(caseSwitches['endyear']) + 1))
num_added_years = len(addyears)
### Add v for the extra years
ivt_add = {}
for i in ivt.index:
vlast = ivt.loc[i,str(lastdatayear)]
if ivt_step[i] == 0:
### Use the same v forever
ivt_add[i] = [vlast] * num_added_years
else:
### Use the same spacing forever
forever = [[vlast + 1 + x] * ivt_step[i] for x in range(1000)]
forever = [item for sublist in forever for item in sublist]
ivt_add[i] = forever[:num_added_years]
ivt_add = pd.DataFrame(ivt_add, index=addyears).T
### Concat and resave
ivtout = pd.concat([ivt, ivt_add], axis=1)
ivtout.to_csv(os.path.join(casedir, 'inputs_case', 'ivt.csv'))
### Get numclass, which is used in b_inputs.gms
numclass = ivtout.max().max()
return numclass
def get_rev_paths(revswitches, caseSwitches):
# Expand on reV path based on where this run is happening
# when running on the HPC this links to the shared-projects folder
hpc = True if (int(os.environ.get('REEDS_USE_SLURM',0))) else False
if os.environ.get('NREL_CLUSTER') == 'kestrel':
hpc_path = '/kfs2/shared-projects/reeds/Supply_Curve_Data'
else:
hpc_path = '/shared-projects/reeds/Supply_Curve_Data'
if hpc:
rev_prefix = hpc_path
else:
hostname = os.environ.get('HOSTNAME')
if (hostname) and (hostname.split('.')[0] in YAMPASERVERS):
drive = '/data/shared/shared_data'
elif LINUXORMAC:
drive = '/Volumes'
else:
drive = '//nrelnas01'
rev_prefix = os.path.join(drive,'ReEDS','Supply_Curve_Data')
revswitches['hpc_sc_path'] = revswitches['sc_path'].apply(lambda row: os.path.join(hpc_path,row))
revswitches['sc_path'] = revswitches['sc_path'].apply(lambda row: os.path.join(rev_prefix,row))
revswitches['rev_path'] = revswitches.apply(lambda row: os.path.join(row.sc_path, "reV", row.rev_case), axis=1)
# link to the pre-processed reV supply curves from hourlize
def get_rev_sc_file_name(caseSwitches, rev_row, use_hpc=False):
if pd.isnull(rev_row.original_sc_file):
return ""
else:
if caseSwitches['GSw_RegionResolution'] == "county":
sc_folder_suffix = "_county"
else:
sc_folder_suffix = "_ba"
# link to HPC or other sc_path
if use_hpc:
sc_path = rev_row.hpc_sc_path
else:
sc_path = rev_row.sc_path
# supply curve name should be in format of {tech}_rev_supply_curves_raw.csv
# in the hourlize results folder (must match format in 'save_sc_outputs' function of hourlize/resource.py)
sc_file = os.path.join(sc_path,
rev_row.tech + "_" + rev_row.access_case + sc_folder_suffix,
"results",
rev_row.tech + "_supply_curve_raw.csv"
)
return sc_file
revswitches['sc_file'] = revswitches.apply(lambda row: get_rev_sc_file_name(caseSwitches, row), axis=1)
revswitches['hpc_sc_file'] = revswitches.apply(lambda row: get_rev_sc_file_name(caseSwitches, row, use_hpc=True), axis=1)
return revswitches
def check_compatibility(sw):
### Hourly resolution
if (
(int(sw['endyear']) > 2050)
or int(sw['GSw_ClimateHydro'])
or int(sw['GSw_ClimateDemand'])
or int(sw['GSw_ClimateWater'])
or int(sw['GSw_EFS_Flex'])
or (int(sw['GSw_Canada']) == 2)
):
raise NotImplementedError(
'At least one of GSw_Canada, GSw_ClimateHydro, GSw_ClimateDemand, GSw_ClimateWater, '
'endyear, GSw_EFS_Flex '
'are using a currently-unsupported setting.')
if 24 % (int(sw['GSw_HourlyWindowOverlap']) * int(sw['GSw_HourlyChunkLengthRep'])):
raise ValueError(
('24 must be divisible by GSw_HourlyWindowOverlap * GSw_HourlyChunkLengthRep:'
'\nGSw_HourlyWindowOverlap = {}\nGSw_HourlyChunkLengthRep = {}'.format(
sw['GSw_HourlyWindowOverlap'], sw['GSw_HourlyChunkLengthRep'])))
if int(sw['GSw_HourlyWindow']) <= int(sw['GSw_HourlyWindowOverlap']):
raise ValueError(
('GSw_HourlyWindow must be greater than GSw_HourlyWindowOverlap:'
'\nGSw_HourlyWindow = {}\nGSw_HourlyWindowOverlap = {}'.format(
sw['GSw_HourlyWindow'], sw['GSw_HourlyWindowOverlap'])))
if ((sw['GSw_HourlyClusterAlgorithm'] not in ['hierarchical','optimized'])
and ('user' not in sw['GSw_HourlyClusterAlgorithm'])
):
raise ValueError(
"GSw_HourlyClusterAlgorithm must be set to 'hierarchical' or 'optimized', or must "
"contain the substring 'user' and match a scenario in "
"inputs/variability/period_szn_user.csv"
)
if ((sw['GSw_PRM_StressModel'].lower() not in ['pras'])
and ('user' not in sw['GSw_PRM_StressModel'])):
raise ValueError(
"GSw_PRM_StressModel must be set to 'pras' or must "
"contain the substring 'user' and match a scenario at "
"inputs/variability/stressperiods_{GSw_PRM_StressModel}.csv"
)
if (int(sw['GSw_H2_PTC']) == 1) and (int(sw['GSw_H2']) != 2):
raise ValueError(
'When running with the H2 PTC enabled, GSw_H2 should be set to 2.\n'
f"GSw_H2_PTC={sw['GSw_H2_PTC']}, GSw_H2={sw['GSw_H2']}"
)
if ('usa' not in sw['GSw_Region'].lower()) and (int(sw['GSw_GasCurve']) != 2):
raise ValueError(
'Should use GSw_GasCurve=2 (fixed prices) when running sub-nationally\n'
f"GSw_Region={sw['GSw_Region']}, GSw_GasCurve={sw['GSw_GasCurve']}"
)
### Aggregation
if (sw['GSw_RegionResolution'] != 'aggreg') and (
(int(sw['GSw_NumCSPclasses']) != 12)
or (int(sw['GSw_NumDUPVclasses']) != 7)
):
raise NotImplementedError(
'Aggregated CSP/DUPV classes only work with aggregated regions. '
'At least one of GSw_NumCSPclasses and GSw_NumDUPVclasses are incompatible with '
'GSw_RegionResolution != aggreg')
### Parsed string switches
## Automatic inputs
reeds_path = os.path.dirname(__file__)
hierarchy = pd.read_csv(os.path.join(reeds_path,'inputs','hierarchy.csv'))
for threshold in sw['GSw_PRM_StressThreshold'].split('/'):
## Example: threshold = 'transgrp_10_EUE_sum'
allowed_levels = ['country','interconnect','nercr','transreg','transgrp','st','r']
(hierarchy_level, ppm, stress_metric, period_agg_method) = threshold.split('_')
if hierarchy_level not in allowed_levels:
raise ValueError(
f"GSw_PRM_StressThreshold: level={hierarchy_level} but must be in:\n"
+ '\n'.join(allowed_levels)
)
if period_agg_method.lower() not in ['sum','max']:
raise ValueError("Fix period agg method in GSw_PRM_StressThreshold")
if not (float(ppm) >= 0):
raise ValueError(
"ppm in GSw_PRM_StressThreshold must be a positive number "
f"but '{ppm}' was provided"
)
if stress_metric.upper() not in ['EUE','NEUE']:
raise ValueError(
"stress metric in GSw_PRM_StressThreshold must be 'EUE' or 'NEUE' "
f"but '{stress_metric}' was provided"
)
if sw['GSw_PRM_StressStorageCutoff'].lower() not in ['off','0','false']:
metric, value = sw['GSw_PRM_StressStorageCutoff'].split('_')
if metric.lower()[:3] not in ['eue', 'cap', 'abs']:
raise ValueError(
"The first argument of GSw_PRM_StressStorageCutoff must be in "
f"['eue', 'cap', 'abs'] but {metric} was provided"
)
try:
float(value)
except ValueError:
raise ValueError(
"The second argument of GSw_PRM_StressStorageCutoff must be a number "
f"but {value} was provided"
)
if (metric.lower()[:3] == 'abs') and (int(value) != 1):
raise NotImplementedError(
"GSw_PRM_StressStorageCutoff: only abs_1 is implemented for abs but "
f"{metric}_{value} was provided"
)
for keyval in sw['GSw_PRM_NetImportLimitScen'].split('/'):
err = (
"GSw_PRM_NetImportLimitScen accepts inputs in the format "
"{year1}_{'hist' or float}/{year2}_{float}/{year3}_{float} "
"or a single value given as {year1}_{'hist' or float}. Examples are "
"2024_hist/2035_40, 2025_20/2032_40, 2024_hist, 2025_20/2032_40/2050_60. "
f"You entered {sw['GSw_PRM_NetImportLimitScen']}."
)
year, limit = keyval.split('_')
try:
int(year)
except ValueError:
raise ValueError(err)
if limit not in ['hist', 'histmax']:
try:
float(limit)
except ValueError:
raise ValueError(err)
for bir in sw['GSw_PVB_BIR'].split('_'):
if not (float(bir) >= 0):
raise ValueError("Fix GSw_PVB_BIR")
for ilr in sw['GSw_PVB_ILR'].split('_'):
if not (float(ilr) >= 0):
raise ValueError("Fix GSw_PVB_ILR")
for pvbtype in sw['GSw_PVB_Types'].split('_'):
if not (1 <= int(pvbtype) <= 3):
raise ValueError("Fix GSw_PVB_Types")
scalars = pd.read_csv(
os.path.join(reeds_path,'inputs','scalars.csv'),
header=None, usecols=[0,1], index_col=0).squeeze(1)
ilr_upv = scalars['ilr_utility'] * 100
if (int(sw['GSw_PVB'])) and (sw['GSw_SitingUPV'] != 'reference'):
if (all(ilr != ilr_upv for ilr in sw['GSw_PVB_ILR'].split('_'))):
raise ValueError(f'PVB with ILR!={scalars["ilr_utility"]} only works with GSw_SitingUPV == "reference".'
'\nSet GSw_SitingUPV to "reference".')
if (int(sw['GSw_PVB'])) and (sw['GSw_RegionResolution'] == 'county'):
if (all(ilr != ilr_upv for ilr in sw['GSw_PVB_ILR'].split('_'))):
raise ValueError(f'PVB with ILR!={scalars["ilr_utility"]} does not work at county resolution.'
f'\nRemove any ILR!={scalars["ilr_utility"]} from GSw_PVB_ILR.')
for year in sw['resource_adequacy_years'].split('_'):
if not (2007 <= int(year) <= 2013):
raise ValueError("Fix resource_adequacy_years")
for year in sw['GSw_HourlyWeatherYears'].split('_'):
if not (2007 <= int(year) <= 2013):
raise ValueError("Fix GSw_HourlyWeatherYears")
if '/' in sw['GSw_Region']:
level, regions = sw['GSw_Region'].split('/')
if level not in hierarchy:
raise ValueError("Fix level in GSw_Region")
for region in regions.split('.'):
if region.lower() not in hierarchy[level].str.lower().values:
err = f'GSw_Region: {region} needs to be in {hierarchy[level].unique()}'
raise Exception(err)
else:
modeled_regions = pd.read_csv(
os.path.join(reeds_path,'inputs','userinput','modeled_regions.csv')
)
if sw['GSw_Region'] not in modeled_regions:
raise ValueError("No column in modeled_regions.csv matching GSw_Region")
### Compatible switch combinations
if sw['GSw_EFS1_AllYearLoad'] == 'historic' :
if ('demand_' + sw['demandscen'] +'.csv') not in os.listdir(os.path.join(reeds_path, 'inputs','load')) :
raise ValueError("The demand file specified by the demandscen switch is not in the inputs/load folder")
if sw['GSw_PRM_scenario'] == 'none':
if sw['GSw_PRM_CapCredit'] !=1 :
raise ValueError("To disable both the capacity credit and stress period formulations GSw_PRM_CapCredit must be set to 1")
### Dependent model availability
if (
((not int(sw['GSw_PRM_CapCredit'])) or (int(sw['pras']) == 2))
and (not os.path.isfile(os.path.join(reeds_path, 'Manifest.toml')))
):
err = (
"Manifest.toml does not exist. "
"Please set up julia by following the instructions at "
"https://pages.github.nrel.gov/ReEDS/ReEDS-2.0/internal/additional_setup.html#reeds2pras-julia-and-stress-periods-setup"
)
raise Exception(err)
### Land use and reeds_to_rev
if (int(sw['land_use_analysis'])) and (not int(sw['reeds_to_rev'])):
raise ValueError(
"'reeds_to_rev' must be enable for land_use analysis to run."
)
def solvestring_sequential(
batch_case, caseSwitches,
cur_year, next_year, prev_year, restartfile,
toLogGamsString=' logOption=4 logFile=gamslog.txt appendLog=1 ',
hpc=0, iteration=0, stress_year=None,
):
"""
Typical inputs:
* restartfile: batch_case if first solve year else {batch_case}_{prev_year}
* caseSwitches: loaded from {batch_case}/inputs_case/switches.csv
"""
savefile = f"{batch_case}_{cur_year}i{iteration}"
_stress_year = f"{cur_year}i0" if stress_year is None else stress_year
out = (
"gams d_solveoneyear.gms"
+ (" license=gamslice.txt" if hpc else '')
+ " o=" + os.path.join("lstfiles", f"{savefile}.lst")
+ " r=" + os.path.join("g00files", restartfile)
+ " gdxcompress=1"
+ " xs=" + os.path.join("g00files", savefile)
+ toLogGamsString
+ f" --case={batch_case}"
+ f" --cur_year={cur_year}"
+ f" --next_year={next_year}"
+ f" --prev_year={prev_year}"
+ f" --stress_year={_stress_year}"
+ ''.join([f" --{s}={caseSwitches[s]}" for s in [
'GSw_SkipAugurYear',
'GSw_HourlyType', 'GSw_HourlyWrapLevel', 'GSw_ClimateWater',
'GSw_Canada', 'GSw_ClimateHydro',
'GSw_HourlyChunkLengthRep', 'GSw_HourlyChunkLengthStress',
'GSw_StateCO2ImportLevel',
'GSw_PVB_Dur',
'GSw_ValStr', 'GSw_gopt', 'solver',
'debug',
]])
+ '\n'
)
return out
def setup_sequential_year(
cur_year, prev_year, next_year,
caseSwitches, hpc,
solveyears, casedir, batch_case, toLogGamsString, OPATH, ticker,
restart_switches,
):
## Get save file (for this year) and restart file (from previous year)
savefile = f"{batch_case}_{cur_year}i0"
restartfile = batch_case if cur_year == min(solveyears) else f"{batch_case}_{prev_year}i0"
## Run the ReEDS LP
if (
(not restart_switches['restart'])
or (cur_year > min(solveyears))
or (restart_switches['restart'] and not restart_switches['restart_Augur'])
):
## solve one year
OPATH.writelines(
solvestring_sequential(
batch_case, caseSwitches,
cur_year, next_year, prev_year, restartfile,
toLogGamsString, hpc,
))
OPATH.writelines(writescripterrorcheck(f"d_solveoneyear.gms_{cur_year}"))
OPATH.writelines('python {t} --year={y}\n'.format(t=ticker, y=cur_year))
if int(caseSwitches['GSw_ValStr']):
OPATH.writelines("python valuestreams.py" + '\n')
## check to see if the restart file exists
OPATH.writelines(writeerrorcheck(os.path.join("g00files",savefile + ".g*")))
## Run Augur if it not the final solve year and if not skipping Augur
if ((
(cur_year < max(solveyears))
and (next_year > int(caseSwitches['GSw_SkipAugurYear']))
) or (cur_year == max(solveyears))):
OPATH.writelines(
f"\npython Augur.py {next_year} {cur_year} {casedir}\n")
## Check to make sure Augur ran successfully; quit otherwise
OPATH.writelines(
writeerrorcheck(os.path.join(
"ReEDS_Augur", "augur_data", f"ReEDS_Augur_{cur_year}.gdx")))
## delete the previous restart file unless we're keeping them
if (cur_year > min(solveyears)) and (not int(caseSwitches['keep_g00_files'])):
write_delete_file(
checkfile=os.path.join("g00files", savefile + ".g00"),
deletefile=os.path.join("g00files", restartfile + '.g00'),
PATH=OPATH,
)
def setup_sequential(
caseSwitches, reeds_path, hpc,
solveyears, casedir, batch_case, toLogGamsString, OPATH, ticker,
restart_switches,
):
### loop over solve years
for i in range(len(solveyears)):
## current year is the value in solveyears
cur_year = solveyears[i]
if cur_year < max(solveyears):
## next year becomes the next item in the solveyears vector
next_year = solveyears[i+1]
## Get previous year if after first year
if i:
prev_year = solveyears[i-1]
else:
if restart_switches['restart']:
prev_year = restart_switches['restart_year']
else:
prev_year = solveyears[i]
### make an indicator in the batch file for what year is being solved
big_comment(f'Year: {cur_year}', OPATH)
### Write the tax credit phaseout call
OPATH.writelines(f"python tc_phaseout.py {cur_year} {casedir}\n\n")
### Write the GAMS LP and Augur calls
if (
int(caseSwitches['GSw_PRM_StressIterateMax'])
and (not int(caseSwitches['GSw_PRM_CapCredit']))
):
OPATH.writelines(
f"python d_solve_iterate.py {casedir} {cur_year}\n"
)
OPATH.writelines(writescripterrorcheck(f"d_solve_iterate.py_{cur_year}"))
else:
setup_sequential_year(
cur_year, prev_year, next_year,
caseSwitches, hpc,
solveyears, casedir, batch_case, toLogGamsString, OPATH, ticker,
restart_switches,
)
### Run Augur plots in background
OPATH.writelines(
f"python {os.path.join('ReEDS_Augur','diagnostic_plots.py')} "
f"--reeds_path={reeds_path} --casedir={casedir} --t={cur_year} &\n")
def setup_intertemporal(
caseSwitches, startiter, niter, ccworkers,
solveyears, endyear, batch_case, toLogGamsString, yearset_augur, OPATH,
):
### beginning year is passed to augurbatch
begyear = min(solveyears)
### first save file from d_solveprep is just the case name
savefile = batch_case
### if this is the first iteration
if startiter == 0:
## restart file becomes the previous calls save file
restartfile=savefile
## if this is not the first iteration...
if startiter > 0:
## restart file is now the case name plus the iteration number
restartfile = batch_case+"_"+startiter
### per the instructions, iterations are
### the number of iterations after the first solve
niter = niter+1
### for the number of iterations we have...
for i in range(startiter,niter):
## make an indicator in the batch file for what iteration is being solved
big_comment(f'Iteration: {i}', OPATH)
## call the intertemporal solve
savefile = batch_case+"_"+str(i)
if i==0:
## check to see if the restart file exists
## only need to do this with the zeroth iteration
## as the other checks will all be after the solves
OPATH.writelines(writeerrorcheck(os.path.join("g00files",restartfile + ".g*")))
OPATH.writelines(
"gams d_solveallyears.gms o="+os.path.join("lstfiles",batch_case + "_" + str(i) + ".lst")
+" r="+os.path.join("g00files",restartfile)
+ " gdxcompress=1 xs="+os.path.join("g00files",savefile) + toLogGamsString
+ " --niter=" + str(i) + " --case=" + batch_case + ' \n')
## check to see if the save file exists
OPATH.writelines(writeerrorcheck(os.path.join("g00files",savefile + ".g*")))
## start threads for cc/curt
## no need to run cc curt scripts for final iteration
if i < niter-1:
## batch out calls to augurbatch
OPATH.writelines(
"python augurbatch.py " + batch_case + " " + str(ccworkers) + " "
+ yearset_augur + " " + savefile + " " + str(begyear) + " "
+ str(endyear) + " " + caseSwitches['distpvscen'] + " "
+ str(caseSwitches['calc_csp_cc']) + " "
+ str(caseSwitches['GSw_DR']) + " "
+ str(caseSwitches['timetype']) + " "
+ str(caseSwitches['GSw_WaterMain']) + " " + str(i) + " "
+ str(caseSwitches['marg_vre_mw']) + " "
+ str(caseSwitches['marg_stor_mw']) + " "
+ str(caseSwitches['marg_dr_mw']) + " "
+ '\n')
## merge all the resulting gdx files
## the output file will be for the next iteration
nextiter = i+1
gdxmergedfile = os.path.join(
"ReEDS_Augur","augur_data","ReEDS_Augur_merged_" + str(nextiter))
OPATH.writelines(
"gdxmerge "+os.path.join("ReEDS_Augur","augur_data","ReEDS_Augur*")
+ " output=" + gdxmergedfile + ' \n')
## check to make sure previous calls were successful
OPATH.writelines(writeerrorcheck(gdxmergedfile+".gdx"))
## restart file becomes the previous save file
restartfile=savefile
if caseSwitches['GSw_ValStr'] != '0':
OPATH.writelines( "python valuestreams.py" + '\n')
def setup_window(
caseSwitches, startiter, niter, ccworkers, reeds_path,
batch_case, toLogGamsString, yearset_augur, OPATH,
):
### load the windows
win_in = list(csv.reader(open(
os.path.join(
reeds_path,"inputs","userinput",
"windows_{}.csv".format(caseSwitches['windows_suffix'])),
'r'), delimiter=","))
restartfile = batch_case
### for windows indicated in the csv file
for win in win_in[1:]:
## beginning year is the first column (start)
begyear = win[1]
## end year is the second column (end)
endyear = win[2]
## for the number of iterations we have...
for i in range(startiter,niter):
big_comment(f'Window: {win}', OPATH)
comment(f'Iteration: {i}', OPATH)
## call the window solve
savefile = batch_case+"_"+str(i)
## check to see if the save file exists
OPATH.writelines(writeerrorcheck(os.path.join("g00files",restartfile + ".g*")))
## solve via the window solve file
OPATH.writelines(
"gams d_solvewindow.gms o=" + os.path.join("lstfiles",batch_case + "_" + str(i) + ".lst")
+" r=" + os.path.join("g00files",restartfile)
+ " gdxcompress=1 xs=g00files\\"+savefile + toLogGamsString + " --niter=" + str(i)
+ " --maxiter=" + str(niter-1) + " --case=" + batch_case + " --window=" + win[0] + ' \n')
## start threads for cc/curt
OPATH.writelines(writeerrorcheck(os.path.join("g00files",savefile + ".g*")))
OPATH.writelines(
"python augurbatch.py " + batch_case + " " + str(ccworkers) + " "
+ yearset_augur + " " + savefile + " " + str(begyear) + " "
+ str(endyear) + " " + caseSwitches['distpvscen'] + " "
+ str(caseSwitches['calc_csp_cc']) + " "
+ str(caseSwitches['GSw_DR']) + " "
+ str(caseSwitches['timetype']) + " "
+ str(caseSwitches['GSw_WaterMain']) + " " + str(i) + " "
+ str(caseSwitches['marg_vre_mw']) + " "
+ str(caseSwitches['marg_stor_mw']) + " "
+ str(caseSwitches['marg_dr_mw']) + " "
+ '\n')
## merge all the resulting r2_in gdx files
## the output file will be for the next iteration
nextiter = i+1
## create names for then merge the curt and cc gdx files
gdxmergedfile = os.path.join(
"ReEDS_Augur","augur_data","ReEDS_Augur_merged_" + str(nextiter))
OPATH.writelines(
"gdxmerge " + os.path.join("ReEDS_Augur","augur_data","ReEDS_Augur*")
+ " output=" + gdxmergedfile + ' \n')
## check to make sure previous calls were successful
OPATH.writelines(writeerrorcheck(gdxmergedfile+".gdx"))
restartfile=savefile
if caseSwitches['GSw_ValStr'] != '0':
OPATH.writelines( "python valuestreams.py" + '\n')
#%% ===========================================================================
### --- PROCEDURE ---
### ===========================================================================
def setupEnvironment(
BatchName=False, cases_suffix=False, single='', simult_runs=0,
forcelocal=0, restart=False, skip_checks=False,
debug=False, debugnode=False):
# #%% Settings for testing
# BatchName = 'v20230508_prasM0_Pacific'
# cases_suffix = 'test'
# WORKERS = 1
# forcelocal = 0
# restart = False
#%% Automatic inputs
reeds_path = os.path.dirname(__file__)
#%% User inputs
print(" ")
print("------------- ")
print(" ")
print("WINDOWS USERS - This script will open multiple command prompts, the number of which")
print("is based on the number of simultaneous runs you've chosen")
print(" ")
print("MAC/LINUX USERS - Your cases will run in the background. All console output")
print("is written to the cases' appropriate gamslog.txt file in the cases' runs folders")
print(" ")
print("------------- ")
print(" ")
print(" ")
if not BatchName:
print("-- Specify the batch prefix --")
print(" ")
print("The batch prefix is attached to the beginning of all cases' outputs files")
print("Note - it must start with a letter and not a number or symbol")
print(" ")
print("A value of 0 will assign the date and time as the batch name (e.g. v20190520_072310)")
print(" ")
BatchName = str(input('Batch Prefix: '))
if BatchName == '0':
BatchName = 'v' + time.strftime("%Y%m%d_%H%M%S")
#check for period in batchname and replace with underscore
BatchName = BatchName.replace('.', '_')
if not cases_suffix:
print("\n\nSpecify the suffix for the cases_suffix.csv file")
print("A blank input will default to the cases.csv file\n")
cases_suffix = str(input('Case Suffix: '))
#%% Check whether to submit slurm jobs (if on HPC) or run locally
hpc = True if (int(os.environ.get('REEDS_USE_SLURM',0))) else False
hpc = False if forcelocal else hpc
### If on NREL HPC but NOT submitting slurm job, ask for confirmation
if ('NREL_CLUSTER' in os.environ) and (not hpc):
print(
"It looks like you're running on the NREL HPC but the REEDS_USE_SLURM environment "
"variable is not set to 1, meaning the model will run locally rather than being "
"submitted as a slurm job. Are you sure you want to run locally?"
)
confirm_local = str(input('Run job locally? y/[n]: ') or 'n')
if confirm_local not in ['y','Y','yes','Yes','YES']:
quit()
#%% Check whether the ReEDS conda environment is activated
if (not skip_checks) and (
('reeds2' not in os.environ['CONDA_DEFAULT_ENV'].lower())
or (not pd.__version__.startswith('2'))
):
print(
f"Your environment is {os.environ['CONDA_DEFAULT_ENV']} and your pandas "
f"version is {pd.__version__}.\nThe default environment is 'reeds2', with\n"
"pandas version 2.x, so the python parts of ReEDS are unlikely to work.\n"
"To build the environment for the first time, run:\n"
" `conda env create -f environment.yml`\n"
"To activate the created environment, run:\n"
" `conda activate reeds2` (or `activate reeds2` on Windows)\n"
"Do you want to continue without activating the environment?"
)
confirm_env = str(input("Continue? y/[n]: ") or 'n')
if confirm_env not in ['y','Y','yes','Yes','YES']:
quit()
#%% Load specified case file, infer other settings from cases.csv
df_cases = pd.read_csv(
os.path.join(reeds_path, 'cases.csv'), dtype=object, index_col=0)
cases_filename = 'cases.csv'
# If we have a case suffix, use cases_[suffix].csv for cases.
if cases_suffix not in ['','default']:
df_cases = df_cases[['Choices', 'Default Value']]
cases_filename = 'cases_' + cases_suffix + '.csv'
df_cases_suf = pd.read_csv(
os.path.join(reeds_path, cases_filename), dtype=object, index_col=0)
# Replace periods and spaces in case names with _
df_cases_suf.columns = [
c.replace(' ','_').replace('.','_') if c != 'Default Value' else c
for c in df_cases_suf.columns]
# Check to make sure user-specified cases file has up-to-date switches
missing_switches = [s for s in df_cases_suf.index if s not in df_cases.index]
if len(missing_switches):
error = ("The following switches are in {} but have changed names or are no longer "
"supported by ReEDS:\n\n{} \n\nPlease update your cases file; "
"for the full list of available switches see cases.csv."
"Note that switch names are case-sensitive."
).format(cases_filename, '\n'.join(missing_switches))
raise ValueError(error)
# First use 'Default Value' from cases_[suffix].csv to fill missing switches
# Later, we will also use 'Default Value' from cases.csv to fill any remaining holes.
if 'Default Value' in df_cases_suf.columns:
case_i = df_cases_suf.columns.get_loc('Default Value') + 1
casenames = df_cases_suf.columns[case_i:].tolist()
for case in casenames:
df_cases_suf[case] = df_cases_suf[case].fillna(df_cases_suf['Default Value'])
df_cases_suf.drop(['Choices','Default Value'], axis='columns',inplace=True, errors='ignore')
df_cases = df_cases.join(df_cases_suf, how='outer')
# Initiate the empty lists which will be filled with info from cases
caseList = []
caseSwitches = [] #list of dicts, one dict for each case
casenames = [c for c in df_cases.columns if c not in ['Description','Default Value','Choices']]
# Get the list of switch choices
choices = df_cases.Choices.copy()
for case in casenames:
#Fill any missing switches with the defaults in cases.csv
df_cases[case] = df_cases[case].fillna(df_cases['Default Value'])
# Ignore cases with ignore flag
if int(df_cases.loc['ignore',case]) == 1:
continue
# Ignore cases that don't match the "single" case
if len(single) and (case not in single.split(',')):
continue
# Check to make sure the switch setting is valid
for i, val in df_cases[case].items():
if skip_checks:
continue
### Split choices by either '; ' or ','
if choices[i] in ['N/A',None,np.nan]:
pass
elif choices[i].lower() in ['int','integer']:
try:
int(val)
except ValueError:
error = (
f'Invalid entry for "{i}" for case "{case}".\n'
f'Entered "{val}" but must be an integer.'
)
raise ValueError(error)
elif choices[i].lower() in ['float','numeric','number','num']:
try:
float(val)
except ValueError:
error = (
f'Invalid entry for "{i}" for case "{case}".\n'
f'Entered "{val}" but must be a float (number).'
)
raise ValueError(error)
else:
i_choices = [
str(j).strip() for j in
np.ravel([i.split(',') for i in choices[i].split(';')]).tolist()
]
matches = [re.match(choice, str(val)) for choice in i_choices]
if not any(matches):
error = (
f'Invalid entry for "{i}" for case "{case}".\n'
f'Entered "{val}" but must match one of the following:\n> '
+ '\n> '.join(i_choices)
+ '\n'
)
raise ValueError(error)
#Check GSw_Region switch and ask user to correct if commas are used instead of periods to list multiple regions
if ',' in (df_cases[case].loc['GSw_Region']) :
print("Please change the delimeter in the GSw_Region switch from ',' to '.'")
quit()
# Propagate debug setting
if debug:
df_cases.loc['debug',case] = str(debug)
# Add switch settings to list of options passed to GAMS
shcom = ' --case=' + BatchName + "_" + case
for i,v in df_cases[case].items():
#exclude certain switches that don't need to be passed to GAMS
if i not in ['file_replacements','keep_run_terminal']:
shcom = shcom + ' --' + i + '=' + v
caseList.append(shcom)
caseSwitches.append(df_cases[case].to_dict())
# ignore cases with ignore flag
casenames = [case for case in casenames if int(df_cases.loc['ignore',case]) != 1]
df_cases.drop(
df_cases.loc['ignore'].loc[df_cases.loc['ignore']=='1'].index, axis=1, inplace=True)
# If the "single" argument is provided, only run that case
if single:
for s in single.split(','):
if s not in df_cases:
err = (
f'Specified single={single} but available cases are:\n'
+ '\n> '.join([
c for c in df_cases.columns
if c not in ['Choices','Description','Default Value']
])
)
raise KeyError(err)
df_cases = df_cases[single.split(',')].copy()
casenames = single.split(',')
# Make sure the run folders don't already exist
outpaths = [os.path.join(reeds_path,'runs',f'{BatchName}_{case}') for case in casenames]
existing_outpaths = [i for i in outpaths if os.path.isdir(i)]
if len(existing_outpaths) and not restart:
print(
f'The following {len(existing_outpaths)} output directories already exist:\n'
+ 'vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv\n'
+ '\n'.join([os.path.basename(i) for i in existing_outpaths])
+ '\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n'
)
overwrite = str(input('Do you want to overwrite them? y/[n]: ') or 'n')
if overwrite in ['y','Y','yes','Yes','YES']:
for outpath in existing_outpaths:
shutil.rmtree(outpath)
else:
keep = [i for (i,c) in enumerate(outpaths) if c not in existing_outpaths]
caseList = [caseList[i] for i in keep]
casenames = [casenames[i] for i in keep]
caseSwitches = [caseSwitches[i] for i in keep]
print(
f"\nThe following {(len(keep))} output directories don't exist:\n"
+ 'vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv\n'
+ '\n'.join([f'{BatchName}_{c}' for c in casenames])
+ '\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n'
)
skip = str(input('Do you want to run them and skip the rest? [y]/n: ') or 'y')
if skip.lower() not in ['y','yes']:
raise IsADirectoryError('\n'+'\n'.join(existing_outpaths))
df_cases.drop(
['Choices','Description','Default Value'],
axis='columns', inplace=True, errors='ignore')
print("{} cases being run:".format(len(caseList)))
for case in casenames:
print(case)
print(" ")
reschoice = 0
startiter = 0
ccworkers = 5
niter = 5
#%% Set number of workers, with user input if necessary
if len(caseList)==1:
print("Only one case is to be run, therefore only one thread is needed")
WORKERS = 1
elif simult_runs < 0 or hpc:
WORKERS = len(caseList)
elif simult_runs > 0:
WORKERS = simult_runs
else:
WORKERS = int(input('Number of simultaneous runs [integer]: '))
print(WORKERS)
print("")
if 'int' in df_cases.loc['timetype'].tolist() or 'win' in df_cases.loc['timetype'].tolist():
ccworkers = int(input('Number of simultaneous CC/Curt runs [integer]: '))
print("")
print("The number of iterations defines the number of combinations of")
print(" solving the model and computing capacity credit and curtailment")
print(" Note this does not include the initial solve")
print("")
niter = int(input('How many iterations between the model and CC/Curt scripts: '))
# reschoice = int(input('Do you want to restart from a previous convergence attempt (0=no, 1=yes): '))
if reschoice==1:
startiter = int(input('Iteration to start from (recall it starts at zero): '))
envVar = {
'WORKERS': WORKERS,
'ccworkers': ccworkers,
'casenames': casenames,
'BatchName': BatchName,
'caseList': caseList,
'caseSwitches': caseSwitches,
'reeds_path' : reeds_path,
'niter' : niter,
'startiter' : startiter,
'cases_filename': cases_filename,
'hpc': hpc,
'restart': restart,
'debugnode': debugnode,
}
return envVar
def createmodelthreads(envVar):
q = queue.Queue()
num_worker_threads = envVar['WORKERS']
def worker():
while True:
ThreadInit = q.get()
if ThreadInit is None:
break
runModel(
options=ThreadInit['scen'],
caseSwitches=ThreadInit['caseSwitches'],
niter=ThreadInit['niter'],
reeds_path=ThreadInit['reeds_path'],
ccworkers=ThreadInit['ccworkers'],
startiter=ThreadInit['startiter'],
BatchName=ThreadInit['BatchName'],
case=ThreadInit['casename'],
cases_filename=ThreadInit['cases_filename'],
hpc=envVar['hpc'],
restart=envVar['restart'],
debugnode=envVar['debugnode'],
)
print(ThreadInit['batch_case'] + " has finished \n")
q.task_done()
threads = []
for i in range(num_worker_threads):
t = threading.Thread(target=worker)
t.start()
threads.append(t)
for i in range(len(envVar['caseList'])):
q.put({