/
flextoolrunner.py
1967 lines (1792 loc) · 98.1 KB
/
flextoolrunner.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
import csv
import math
import subprocess
import logging
import sys
import os
import xml.etree.ElementTree as ET
import pandas as pd
import shutil
from collections import OrderedDict
from collections import defaultdict
#return_codes
#0 : Success
#-1: Failure (Defined in the Toolbox)
#1: Infeasible or unbounded problem (not implemented in the toolbox, functionally same as -1. For a possiblity of a graphical depiction)
class FlexToolRunner:
"""
Define Class to run the model and read and recreate the required config files:
"""
def __init__(self) -> None:
logging.basicConfig(
stream=sys.stderr,
level=logging.DEBUG,
format='%(asctime)s %(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
)
translation = {39: None}
# delete highs.log from previous run
if os.path.exists("./HiGHS.log"):
os.remove("./HiGHS.log")
# make a directory for model unit tests
if not os.path.exists("./tests"):
os.makedirs("./tests")
# read the data in
self.timelines = self.get_timelines()
self.model_solve = self.get_solves()
self.solve_modes = self.get_solve_modes("solve_mode")
self.roll_counter = self.make_roll_counter()
self.highs_presolve = self.get_solve_modes("highs_presolve")
self.highs_method = self.get_solve_modes("highs_method")
self.highs_parallel = self.get_solve_modes("highs_parallel")
self.solve_period_years_represented = self.get_solve_period_years_represented()
self.solvers = self.get_solver()
self.timeblocks = self.get_timeblocks()
self.timeblocks__timeline = self.get_timeblocks_timelines()
self.stochastic_branches = self.get_stochastic_branches()
self.stochastic_timesteps = defaultdict(list)
self.solver_precommand = self.get_solver_precommand()
self.solver_arguments = self.get_solver_arguments()
self.contains_solves = self.get_contains_solves()
self.hole_multipliers = self.get_hole_multipliers()
self.rolling_times = self.get_rolling_times()
self.new_step_durations = self.get_new_step_durations()
self.original_timeline = defaultdict()
self.create_timeline_from_timestep_duration()
self.first_of_complete_solve = []
self.last_of_solve = []
self.timeblocks_used_by_solves = {**self.get_timeblocks_used_by_solves(), **self.get_2d_timeblocks_used_by_solves()}
self.invest_periods = self.get_list_of_tuples('input/solve__invest_period.csv') + self.get_2d_map_periods('input/solve__invest_period_2d_map.csv')
self.realized_periods = self.get_list_of_tuples('input/solve__realized_period.csv') + self.get_2d_map_periods('input/solve__realized_period_2d_map.csv')
self.realized_invest_periods = self.get_list_of_tuples('input/solve__realized_invest_period.csv') + self.get_2d_map_periods('input/solve__realized_invest_period_2d_map.csv')
self.fix_storage_periods = self.get_list_of_tuples('input/solve__fix_storage_period.csv') + self.get_2d_map_periods('input/solve__fix_storage_period_2d_map.csv')
#self.write_full_timelines(self.timelines, 'steps.csv')
def get_2d_timeblocks_used_by_solves(self):
with open('input/timeblocks_in_use_2d.csv', 'r') as blk:
filereader = csv.reader(blk, delimiter=',')
headers = next(filereader)
timeblocks_used_by_solves = defaultdict(list)
while True:
try:
datain = next(filereader)
new_name = datain[0]+"_"+datain[1]
self.duplicate_solve(datain[0],new_name)
timeblocks_used_by_solves[new_name].append((datain[2], datain[3]))
except StopIteration:
break
return timeblocks_used_by_solves
def get_2d_map_periods(self,input_filename):
with open(input_filename, 'r') as blk:
filereader = csv.reader(blk, delimiter=',')
headers = next(filereader)
period_list = []
while True:
try:
datain = next(filereader)
new_name = datain[0]+"_"+datain[1]
self.duplicate_solve(datain[0],new_name)
period_list.append((new_name,datain[2]))
new_period_timeblockset_list = []
for solve, period__timeblockset_list in list(self.timeblocks_used_by_solves.items()):
if solve == datain[0]:
for period__timeblockset in period__timeblockset_list:
if period__timeblockset[0] == datain[2]:
new_period_timeblockset_list.append(period__timeblockset)
if new_name not in self.timeblocks_used_by_solves.keys():
self.timeblocks_used_by_solves[new_name] = new_period_timeblockset_list
else:
for item in new_period_timeblockset_list:
if item not in self.timeblocks_used_by_solves[new_name]:
self.timeblocks_used_by_solves[new_name].append(item)
except StopIteration:
break
return period_list
def duplicate_solve(self, old_solve, new_name):
if new_name not in self.model_solve.values() and new_name not in self.contains_solves.values():
dup_map_list=[
self.solve_modes,
self.roll_counter,
self.highs_presolve,
self.highs_method,
self.highs_parallel,
self.solve_period_years_represented,
self.solvers,
self.solver_precommand,
self.solver_arguments,
self.contains_solves,
self.rolling_times
]
for dup_map in dup_map_list:
if old_solve in dup_map.keys():
dup_map[new_name]=dup_map[old_solve]
for model, solves in list(self.model_solve.items()):
if old_solve in solves:
solves.remove(old_solve)
if new_name not in solves:
solves.append(new_name)
self.model_solve[model] = solves
def get_solves(self):
"""
read in
the list of solves, return it as a list of strings
:return:
"""
with open("input/model__solve.csv", 'r') as blk:
filereader = csv.reader(blk, delimiter=',')
headers = next(filereader)
model__solve = defaultdict(list)
while True:
try:
datain = next(filereader)
model__solve[datain[0]].append((datain[1]))
except StopIteration:
break
return model__solve
def get_solve_modes(self, parameter):
"""
read in
the list of solve modes, return it as a list of strings
:return:
"""
with open("input/solve_mode.csv", 'r') as solvefile:
header = solvefile.readline()
solves = solvefile.readlines()
params = []
right_params = {}
for solve in solves:
solve_stripped = solve.rstrip()
params.append(solve_stripped.split(","))
for param in params:
if param[0] == parameter:
right_params[param[1]] = param[2]
return right_params
def make_roll_counter(self):
roll_counter_map={}
for key, mode in list(self.solve_modes.items()):
if mode == "rolling_window":
roll_counter_map[key] = 0
return roll_counter_map
def get_solve_period_years_represented(self):
"""
read the years presented by each period in a solve
:return: dict : (period name, years represented)
"""
with open('input/solve__period__years_represented.csv', 'r') as blk:
filereader = csv.reader(blk, delimiter=',')
headers = next(filereader)
years_represented = defaultdict(list)
while True:
try:
datain = next(filereader)
years_represented[datain[0]].append((datain[1], datain[2]))
except StopIteration:
break
return years_represented
def get_solver(self):
"""
read in
the list of solvers for each solve. return it as a list of strings
:return:
"""
with open('input/solver.csv', 'r') as blk:
filereader = csv.reader(blk, delimiter=',')
headers = next(filereader)
solver_dict = defaultdict()
while True:
try:
datain = next(filereader)
solver_dict[datain[0]] = datain[1]
except StopIteration:
break
#with open("input/solver.csv", 'r') as solvefile:
# header = solvefile.readline()
# solvers = solvefile.readlines()
# for solver in solvers:
# solve__period = solver.split(",")
# solver_dict[solve__period[0]] = solve__period[1]
return solver_dict
def get_solver_precommand(self):
"""
read in
the solver_precommand for each solve. return it as a list of strings
:return:
"""
with open('input/solver_precommand.csv', 'r') as blk:
filereader = csv.reader(blk, delimiter=',')
headers = next(filereader)
solver_precommand_dict = defaultdict()
while True:
try:
datain = next(filereader)
solver_precommand_dict[datain[0]] = datain[1]
except StopIteration:
break
return solver_precommand_dict
def get_solver_arguments(self):
"""
read in
the solver commands for each solve. return it as a list of strings
:return:
"""
with open('input/solver_arguments.csv', 'r') as blk:
filereader = csv.reader(blk, delimiter=',')
headers = next(filereader)
solver_arguments_dict = defaultdict(list)
while True:
try:
datain = next(filereader)
solver_arguments_dict[datain[0]].append((datain[1]))
except StopIteration:
break
return solver_arguments_dict
def get_contains_solves(self):
"""
read in
the contains_solves for each solve. return it as a dict of list of strings
:return:
"""
with open('input/solve__contains_solve.csv', 'r') as blk:
filereader = csv.reader(blk, delimiter=',')
headers = next(filereader)
contains_solves_dict = defaultdict(list)
while True:
try:
datain = next(filereader)
contains_solves_dict[datain[0]]= datain[1]
except StopIteration:
break
return contains_solves_dict
def get_hole_multipliers(self):
"""
read in
the hole multipliers for each solve. return it as a dict of list of strings
:return:
"""
with open('input/solve_hole_multiplier.csv', 'r') as blk:
filereader = csv.reader(blk, delimiter=',')
headers = next(filereader)
hole_multipliers = defaultdict(list)
while True:
try:
datain = next(filereader)
hole_multipliers[datain[0]] = datain[1]
except StopIteration:
break
return hole_multipliers
def get_rolling_times(self):
"""
read in
the rolling_times for each solve. return it as a dict of list of ints
:return:
"""
with open('input/solve__rolling_times.csv', 'r') as blk:
filereader = csv.reader(blk, delimiter=',')
headers = next(filereader)
rolling_parameters = defaultdict(list)
while True:
try:
datain = next(filereader)
rolling_parameters[datain[0]].append((datain[1],datain[2]))
except StopIteration:
break
rolling_times=defaultdict(list)
for solve, data in list(rolling_parameters.items()):
horizon = 0
jump = 0
duration = -1
for param_value in data:
if "rolling_duration" in param_value[0]:
duration = float(param_value[1])
if "rolling_solve_horizon" in param_value[0]:
horizon = float(param_value[1])
if "rolling_solve_jump" in param_value[0]:
jump = float(param_value[1])
if self.solve_modes[solve] == 'rolling_window' and (horizon == 0 or jump == 0):
logging.error("When using rolling_window solve mode, rolling_solve_horizon and rolling_solve_jump must defined and not be 0")
exit(-1)
rolling_times[solve] = [jump,horizon,duration]
return rolling_times
def create_timeline_from_timestep_duration(self):
for timeblockSet_name, timeblockSet in list(self.timeblocks.items()):
if timeblockSet_name in self.new_step_durations.keys():
step_duration= float(self.new_step_durations[timeblockSet_name])
#create the new timeline
timeline_name = self.timeblocks__timeline[timeblockSet_name][0]
old_steps = self.timelines[timeline_name]
new_steps = []
new_timeblocks = []
for timeblock in timeblockSet:
first_step = timeblock[0]
first_index = [step[0] for step in old_steps].index(timeblock[0])
step_counter = 0 #float(old_steps[first_index][1])
last_index = first_index + int(float(timeblock[1]))
added_steps = 0
for step in old_steps[first_index:last_index]:
if step_counter >= step_duration:
new_steps.append((first_step,str(step_counter)))
first_step = step[0]
step_counter=0
added_steps += 1
if step_counter> step_duration:
logging.warning("Warning: All new steps are not the size of the given step duration. The new step duration has to be multiple of old step durations for this to happen.")
step_counter += float(step[1])
new_steps.append((first_step,str(step_counter)))
added_steps += 1
new_timeblocks.append((timeblock[0], added_steps))
self.timeblocks[timeblockSet_name] = new_timeblocks
new_timeline_name = timeline_name+ "_"+ timeblockSet_name
self.timelines[new_timeline_name] = new_steps
self.timeblocks__timeline[timeblockSet_name] = [new_timeline_name]
self.original_timeline[new_timeline_name] = timeline_name
def create_averaged_timeseries(self,solve):
timeseries_map={
'pt_node_inflow.csv': "sum",
'pt_node.csv': "average",
'pt_process.csv': "average",
'pt_profile.csv': "average",
'pt_process_source.csv': "average",
'pt_process_sink.csv': "average",
'pt_reserve__upDown__group.csv': "average",
'pbt_node_inflow.csv': "sum",
'pbt_node.csv': "average",
'pbt_process.csv': "average",
'pbt_profile.csv': "average",
'pbt_process_source.csv': "average",
'pbt_process_sink.csv': "average",
'pbt_reserve__upDown__group.csv': "average"
}
create = False
for period_timeblock in self.timeblocks_used_by_solves[solve]:
if period_timeblock[1] in self.new_step_durations.keys():
create = True
if not create:
for timeseries in timeseries_map.keys():
shutil.copy('input/'+timeseries,'solve_data/'+timeseries)
else:
timelines=[]
for period, timeblockSet in self.timeblocks_used_by_solves[solve]:
timeline = self.timeblocks__timeline[timeblockSet][0]
if timeline not in timelines:
if len(timelines) != 0:
logging.error("Error: More than one timeline in the solve or the same timeline with different step durations in different timeblockSets")
exit(-1)
timelines.append(timeline)
for timeseries in timeseries_map.keys():
with open('input/'+ timeseries,'r') as blk:
filereader = csv.reader(blk, delimiter=',')
with open('solve_data/'+timeseries,'w', newline='') as solve_file:
filewriter = csv.writer(solve_file,delimiter=',')
headers = next(filereader)
filewriter.writerow(headers)
#assumes that the data is in the format:
#[group1, group2, ... group_last, time, numeric_value]
#ie. the numeric data is the last column and the timestep is the one before it.
#and that there are no rows from other groups between the rows of one group
time_index = headers.index('time')
while True:
try:
datain = next(filereader)
timeline_step_duration = None
for timeline in timelines:
new_timeline = self.timelines[timeline]
for timeline_row in new_timeline:
if timeline_row[0] == datain[time_index]:
timeline_step_duration = int(float(timeline_row[1]))
break
if timeline_step_duration != None:
values = []
row = datain[0:time_index + 1]
values.append(float(datain[time_index + 1]))
for i in range(timeline_step_duration - 1):
datain = next(filereader)
values.append(float(datain[time_index + 1]))
if timeseries_map[timeseries] == "average":
out_value = round(sum(values) / len(values), 6)
else:
out_value = sum(values)
row.append(out_value)
filewriter.writerow(row)
except Exception:
break
#constaint inflow to a longer step size
node__inflow = []
with open('input/'+ 'p_node.csv','r') as blk:
filereader = csv.reader(blk, delimiter=',')
read_header = next(filereader)
while True:
try:
datain = next(filereader)
if datain[1] == 'inflow':
node__inflow.append([datain[0],datain[2]])
except Exception:
break
with open('solve_data/'+ 'pt_node_inflow.csv','a', newline='') as blk:
filewriter = csv.writer(blk, delimiter=',')
for timeline in timelines:
new_timeline = self.timelines[timeline]
for node__value in node__inflow:
for timeline_row in new_timeline:
timeline_step_duration = int(float(timeline_row[1]))
value = float(node__value[1])*timeline_step_duration
row = [node__value[0],timeline_row[0],value]
filewriter.writerow(row)
def get_new_step_durations(self):
"""
read the new step duration for each solve
:return: dict : (period name, step_duration (hours))
"""
with open('input/timeblockSet__new_stepduration.csv', 'r') as blk:
filereader = csv.reader(blk, delimiter=',')
headers = next(filereader)
step_durations = defaultdict()
while True:
try:
datain = next(filereader)
step_durations[datain[0]]=datain[1]
except StopIteration:
break
return step_durations
def get_timeblocks_used_by_solves(self):
"""
timeblocks_in_use.csv contains three columns
solve: name of the solve
period: name of the time periods used for a particular solve
timeblocks: timeblocks used by the period
:return list of tuples in a dict of solves : (period name, timeblock name)
"""
with open('input/timeblocks_in_use.csv', 'r') as blk:
filereader = csv.reader(blk, delimiter=',')
headers = next(filereader)
timeblocks_used_by_solves = defaultdict(list)
while True:
try:
datain = next(filereader)
timeblocks_used_by_solves[datain[0]].append((datain[1], datain[2]))
# blockname needs to be in both block_start and timeblock_lengths.csv
# assert datain[1] in self.starts.keys(), "Block {0} not in block_starts.csv".format(datain[1])
# assert datain[1] in self.steps.keys(), "Block {0} not in block_steps.csv".format(datain[1])
except StopIteration:
break
#except AssertionError as e:
# logging.error(e)
# sys.exit(-1)
return timeblocks_used_by_solves
def get_timelines(self):
"""
read in the timelines including step durations for all simulation steps
timeline is the only inputfile that contains the full timelines for all timeblocks.
:return: list of tuples in a dict timeblocks : (timestep name, duration)
"""
with open('input/timeline.csv', 'r') as blk:
filereader = csv.reader(blk, delimiter=',')
headers = next(filereader)
timelines = defaultdict(list)
while True:
try:
datain = next(filereader)
timelines[datain[0]].append((datain[1], datain[2]))
except StopIteration:
break
return timelines
def get_timeblocks_timelines(self):
"""
read in the timelines including step durations for all simulation steps
timeline is the only inputfile that contains the full timelines for all timeblocks.
:return: list of tuples in a dict timeblocks : (timestep name, duration)
"""
with open('input/timeblocks__timeline.csv', 'r') as blk:
filereader = csv.reader(blk, delimiter=',')
headers = next(filereader)
timeblocks__timeline = defaultdict(list)
while True:
try:
datain = next(filereader)
timeblocks__timeline[datain[0]].append((datain[1]))
except StopIteration:
break
return timeblocks__timeline
def get_timeblocks(self):
"""
read in the timeblock definitions that say what each set of timeblock contains (timeblock start and length)
:return: list of tuples in a dict of timeblocks : (start timestep name, timeblock length in timesteps)
:return: list of tuples that hold the timeblock length in timesteps
"""
with open('input/timeblocks.csv', 'r') as blk:
filereader = csv.reader(blk, delimiter=',')
headers = next(filereader)
timeblocks = defaultdict(list)
#timeblock_lengths = []
while True:
try:
datain = next(filereader)
timeblocks[datain[0]].append((datain[1], datain[2]))
""" This assert should check the list of timelines inside the dict, but didn't have time to formulate it yet
assert timeblocks[datain[0]] in self.timelines[datain[0]], "Block {0} start time {1} not found in timelines".format(
datain[0], datain[1])
"""
#timeblock_lengths.append[(datain[0], datain[1])] = datain[2]
except StopIteration:
break
""" Once the assert works, this can be included
except AssertionError as e:
logging.error(e)
sys.exit(-1)
"""
return timeblocks
def get_stochastic_branches(self):
"""
read stochastic data
:return a 5d array (solve, period, branch, weight, realized):
"""
with open('input/stochastic_branches.csv', 'r') as blk:
filereader = csv.reader(blk, delimiter=',')
headers = next(filereader)
map_5d = defaultdict(list)
while True:
try:
datain = next(filereader)
map_5d[datain[0]].append([datain[1], datain[2], datain[3], datain[4], datain[5]])
except StopIteration:
break
return map_5d
def get_list_of_tuples(self, filename):
"""
read in invest_period
:return a list of tuples that say when it's ok to invest (solve, period):
"""
with open(filename, 'r') as blk:
filereader = csv.reader(blk, delimiter=',')
headers = next(filereader)
tuple_list = []
while True:
try:
datain = next(filereader)
tuple_list.append((datain[0], datain[1]))
except StopIteration:
break
return tuple_list
def make_steps(self, start, stop):
"""
make a list of timesteps available
:param start: Start index of of the block
:param stop: Stop index of the block
:param steplist: list of steps, read from steps.csv
:return: list of timesteps
"""
active_step = start
steps = []
while active_step <= stop:
steps.append(self.steplist[active_step])
active_step += 1
return steps
def write_full_timelines(self, stochastic_timesteps, period__timeblocks_in_this_solve, timeblocks__timeline, timelines, filename):
"""
write to file a list of timestep as defined in timelines.
:param filename: filename to write to
:param steplist: list of timestep indexes
:return:
"""
with open(filename, 'w') as outfile:
# prepend with a header
outfile.write('period,step\n')
for period__timeblock in period__timeblocks_in_this_solve:
for timeline in timelines:
for timeblock_in_timeline, tt in timeblocks__timeline.items():
if period__timeblock[1] == timeblock_in_timeline:
if timeline == tt[0]:
for item in timelines[timeline]:
outfile.write(period__timeblock[0] + ',' + item[0] + '\n')
for step in stochastic_timesteps:
outfile.write(step[0] + ',' + step[1] + '\n')
def write_active_timelines(self, timeline, filename, complete = False):
"""
write to file a list of timesteps as defined by the active timeline of the current solve
:param filename: filename to write to
:param timeline: list of tuples containing the period and the timestep
:return: nothing
"""
if not complete:
with open(filename, 'w') as outfile:
# prepend with a header
outfile.write('period,step,step_duration\n')
for period_name, period in timeline.items():
for item in period:
outfile.write(period_name + ',' + item[0] + ',' + item[2] + '\n')
else:
with open(filename, 'w') as outfile:
# prepend with a header
outfile.write('period,step,complete_step_duration\n')
for period_name, period in timeline.items():
for item in period:
outfile.write(period_name + ',' + item[0] + ',' + item[2] + '\n')
def write_years_represented(self, period__branch, years_represented, filename):
"""
write to file a list of periods with the number of years the period represents before the next period starts
:param filename: filename to write to
:param years_represented: dict of periods with the number of years represented
:return: nothing
"""
with open(filename, 'w') as outfile:
# prepend with a header
outfile.write('period,years_from_solve,p_years_from_solve,p_years_represented\n')
year_count = 0
for period__years in years_represented:
for i in range(int(max(1.0, float(period__years[1])))):
years_to_cover_within_year = min(1, float(period__years[1]))
outfile.write(period__years[0] + ',y' + str(year_count) + ',' + str(year_count) + ','
+ str(years_to_cover_within_year) + '\n')
for pd in period__branch:
if pd[0] in period__years[0] and pd[0] != pd[1]:
outfile.write(pd[1]+ ',y' + str(year_count) + ',' + str(year_count) + ','
+ str(years_to_cover_within_year) + '\n')
year_count = year_count + years_to_cover_within_year
def write_hole_multiplier(self, solve, filename):
with open(filename, 'w') as holefile:
holefile.write("solve,p_hole_multiplier\n")
if self.hole_multipliers[solve]:
holefile.write(solve + "," + self.hole_multipliers[solve] + "\n")
def write_period_years(self, stochastic_branches, years_represented, filename):
"""
write to file a list of timesteps as defined by the active timeline of the current solve
:param filename: filename to write to
:param timeline: list of tuples containing the period and the timestep
:return: nothing
"""
with open(filename, 'w') as outfile:
# prepend with a header
outfile.write('period,param\n')
year_count = 0
for period__year in years_represented:
outfile.write(period__year[0] + ',' + str(year_count) + '\n')
for pd in stochastic_branches:
if pd[0] in period__year[0] and pd[0] != pd[1]:
outfile.write(pd[1] + ',' + str(year_count) + '\n')
year_count += float(period__year[1])
def make_block_timeline(self, start, length):
"""
make a block timeline, there might be multiple blocks per solve so these blocks might need to be combined for a run
:param start: start of block
:param length: length of block
:return: block timeline
"""
steplist = []
startnum = self.steplist.index(start)
for i in range(startnum, math.ceil(startnum + float(length))):
steplist.append(self.steplist[i])
return steplist
def model_run(self, current_solve):
"""
run the model executable once
:return the output of glpsol.exe:
"""
try:
solver = self.solvers[current_solve]
except KeyError:
logging.warning(f"No solver defined for {current_solve}. Defaulting to highs.")
solver = "highs"
if solver == "glpsol":
only_glpsol = ['glpsol', '--model', 'flexModel3.mod', '-d', 'FlexTool3_base_sets.dat', '--cbg','-w', 'glpsol_solution.txt'] + sys.argv[1:]
completed = subprocess.run(only_glpsol)
if completed.returncode != 0:
logging.error(f'glpsol failed: {completed.returncode}')
exit(completed.returncode)
#checking if solution is infeasible. This is quite clumsy way of doing this, but the solvers do not give infeasible exitstatus
with open('glpsol_solution.txt','r') as inf_file:
inf_content = inf_file.read()
if 'INFEASIBLE' in inf_content:
logging.error(f"The model is infeasible. Check the constraints.")
exit(1)
elif solver == "highs" or solver == "cplex":
highs_step1 = ['glpsol', '--check', '--model', 'flexModel3.mod', '-d', 'FlexTool3_base_sets.dat',
'--wfreemps', 'flexModel3.mps'] + sys.argv[1:]
completed = subprocess.run(highs_step1)
if completed.returncode != 0:
logging.error(f'glpsol mps writing failed: {completed.returncode}')
exit(completed.returncode)
print("GLPSOL wrote the problem as MPS file\n")
#check if the problem has columns(nodes)
with open('flexModel3.mps','r') as mps_file:
mps_content = mps_file.read()
if 'Columns: 0' in mps_content:
logging.error(f"The problem has no columns. Check that the model has nodes.")
exit(-1)
if solver == "highs":
highs_step2 = "highs flexModel3.mps --options_file=highs.opt --presolve=" \
+ self.highs_presolve.get(current_solve, "on") + " --solver=" \
+ self.highs_method.get(current_solve, "choose") + " --parallel=" \
+ self.highs_parallel.get(current_solve, "off")
completed = subprocess.run(highs_step2)
if completed.returncode != 0:
logging.error(f'Highs solver failed: {completed.returncode}')
exit(completed.returncode)
print("HiGHS solved the problem\n")
#checking if solution is infeasible. This is quite clumsy way of doing this, but the solvers do not give infeasible exitstatus
with open('HiGHS.log','r') as inf_file:
inf_content = inf_file.read()
if 'Model status : Infeasible' in inf_content:
logging.error(f"The model is infeasible. Check the constraints.")
exit(1)
elif solver == "cplex": #or gurobi
if current_solve not in self.solver_precommand.keys():
s_wrapper = ''
else:
s_wrapper = self.solver_precommand[current_solve]
if solver == "cplex":
if current_solve not in self.solver_arguments.keys():
cplex_step = [s_wrapper, 'cplex', '-c', 'read flexModel3.mps','opt', 'write flexModel3_cplex.sol', 'quit'] + sys.argv[1:]
else:
cplex_step = [s_wrapper, 'cplex', '-c', 'read flexModel3.mps']
cplex_step += self.solver_arguments[current_solve]
cplex_step += ['opt', 'write flexModel3_cplex.sol', 'quit']
cplex_step += sys.argv[1:]
completed = subprocess.run(cplex_step)
if completed.returncode != 0:
logging.error(f'Cplex solver failed: {completed.returncode}')
exit(completed.returncode)
completed = self.cplex_to_glpsol("flexModel3_cplex.sol","flexModel3.sol")
highs_step3 = ['glpsol', '--model', 'flexModel3.mod', '-d', 'FlexTool3_base_sets.dat', '-r',
'flexModel3.sol'] + sys.argv[1:]
completed = subprocess.run(highs_step3)
if completed.returncode == 0:
print("GLPSOL wrote the results into csv files\n")
else:
logging.error(f"Unknown solver '{solver}'. Currently supported options: highs, glpsol, cplex.")
exit(-1)
return completed.returncode
def cplex_to_glpsol(self,cplexfile,solutionfile):
try:
tree = ET.parse(cplexfile)
except (OSError):
logging.error('The CPLEX solver does not produce a solution file if the problem is infeasible. Check the constraints, more info at cplex.log')
exit(-1)
root = tree.getroot()
if root.find('header').get('solutionStatusString') == "optimal":
with open(solutionfile,'w') as glpsol_file:
obj = root.find('header').get('objectiveValue')
for constraint in root.iter('constraint'):
rows = constraint.get('index')
rows = int(rows) + 2
for variable in root.iter('variable'):
col = variable.get('index')
col = int(col) + 1
glpsol_file.write("s bas "+str(rows)+" "+str(col)+" f f "+obj+"\n")
#For some reason the glpsol constraint the first variable row to be the objective function value.
#This is not stated anywhere in the glpk documentation
glpsol_file.write("i 1 b "+obj+" 0\n")
for constraint in root.iter("constraint"):
slack = constraint.get('slack')
index = int(constraint.get('index')) + 2
status = constraint.get('status')
dual = constraint.get('dual')
if status == "BS":
status = 'b'
elif status == "LL":
status = 'l'
elif status == "UL":
status = 'u'
glpsol_file.write("i"+" "+str(index)+" "+status+" "+slack+" "+dual+"\n")
for variable in root.iter('variable'):
val = variable.get('value')
index = int(variable.get('index')) +1
status = variable.get('status')
reduced = variable.get('reducedCost')
if status == "BS":
status = 'b'
elif status == "LL":
status = 'l'
elif status == "UL":
status = 'u'
glpsol_file.write("j"+" "+str(index)+" "+status+" "+val+" "+reduced+"\n")
glpsol_file.write("e o f")
elif root.find('header').get('solutionStatusString') == "integer optimal solution":
with open(solutionfile,'w') as glpsol_file:
obj = root.find('header').get('objectiveValue')
for constraint in root.iter('constraint'):
rows = constraint.get('index')
rows = int(rows) + 2
for variable in root.iter('variable'):
col = variable.get('index')
col = int(col) + 1
glpsol_file.write("s mip "+str(rows)+" "+str(col)+" o "+obj+"\n")
#For some reason the glpsol requires the first constraint row to be the objective function value.
#This is not stated anywhere in the glpk documentation
glpsol_file.write("i 1 "+obj+"\n")
for constraint in root.iter("constraint"):
slack = constraint.get('slack')
index = int(constraint.get('index')) + 2
glpsol_file.write("i"+" "+str(index)+" "+slack+"\n")
for variable in root.iter('variable'):
val = variable.get('value')
index = int(variable.get('index')) +1
glpsol_file.write("j"+" "+str(index)+" "+val+"\n")
glpsol_file.write("e o f")
else:
logging.error(f"Optimality could not be reached. Check the flexModel3_cplex.sol file for more")
exit(1)
return 0
def get_active_time(self, current_solve, timeblocks_used_by_solves, timeblocks, timelines, timeblocks__timelines):
"""
retunr all block codes that are included in solve
:param solve:
:param blocklist:
:return:
"""
active_time = defaultdict(list)
for solve in timeblocks_used_by_solves:
if solve == current_solve:
for period_timeblock in timeblocks_used_by_solves[solve]:
for timeblocks__timeline_key, timeblocks__timeline_value in timeblocks__timelines.items():
if timeblocks__timeline_key == period_timeblock[1]:
for timeline in timelines:
if timeline == timeblocks__timeline_value[0]:
for single_timeblock_def in timeblocks[timeblocks__timeline_key]:
for index, timestep in enumerate(timelines[timeline]):
if timestep[0] == single_timeblock_def[0]:
for block_step in range(int(float(single_timeblock_def[1]))):
active_time[period_timeblock[0]].append((
timelines[timeline][index + block_step][0],
index + block_step,
timelines[timeline][index + block_step][1]))
break
if len(active_time.keys()) == 0:
logging.error(current_solve + " could not connect to a timeline. Check that object solve has period_timeblockSet [Map], correct realized_periods [Array], objects timeblockSet [Map] and timeline [Map] are defined and that relation timeblockSet_timeline exists")
exit(-1)
return active_time
def make_step_jump(self, active_time_list, period__branch, solve_branch__time_branch_list):
"""
make a file that indicates the length of jump from one simulation step to next one.
the final line should always contain a jump to the first line.
length of jump is the number of lines needed to advance in the timeline specified in step_duration.csv
:param steplist: active steps used in the solve
:param duration: duration of every timestep
:return:
"""
step_lengths = []
period_start_pos = 0
period_counter = -1
first_period_name = list(active_time_list)[0]
last_period_name = list(active_time_list)[-1]
for period, active_time in reversed(active_time_list.items()):
period_counter -= 1
period_last = len(active_time)
block_last = len(active_time) - 1
if period == first_period_name:
previous_period_name = last_period_name
else:
previous_period_name = list(active_time_list)[period_counter]
for i, step in enumerate(reversed(active_time)):
j = period_last - i - 1
if j > 0: # handle the first element of the period separately below
jump = active_time[j][1] - active_time[j - 1][1]
if jump > 1:
step_lengths.insert(period_start_pos, (period, step[0], active_time[j - 1][0], active_time[block_last][0], period, active_time[j - 1][0], jump))
block_last = j - 1
else:
step_lengths.insert(period_start_pos, (period, step[0], active_time[j - 1][0], active_time[j - 1][0], period, active_time[j - 1][0], jump))
else: # first time step of the period is handled here
#three options (period,period) is the realized, (period, branch) are the branches in the realized period,
#(other_period,branch): continuing branch to the next period
if (period, period) not in period__branch:
for i in period__branch:
if i[1] == period:
original_period = i[0]
if (original_period,original_period) in period__branch and original_period in active_time_list.keys():
jump = active_time[j][1] - active_time_list[original_period][-1][1]
step_lengths.insert(period_start_pos, (period, step[0], active_time[j - 1][0], active_time[block_last][0], original_period, active_time_list[original_period][-1][0], jump))
elif (original_period,original_period) in period__branch:
#if branching happens in the first timestep of a period
#find the last realized period
past = False
previous_realized_period = None
for solve_period, a_t in reversed(active_time_list.items()):
if past:
if (solve_period, solve_period) in period__branch:
previous_realized_period = solve_period
break
else:
if solve_period == period:
past = True
jump = active_time[j][1] - active_time_list[previous_realized_period][-1][1]
step_lengths.insert(period_start_pos, (period, step[0], active_time[j - 1][0], active_time[block_last][0], previous_realized_period, active_time_list[previous_realized_period][-1][0], jump))
else:
#if branch continuing in the next period
#find the previous branch with the same time_branch
for sb_tb in solve_branch__time_branch_list: