-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.py
712 lines (593 loc) · 32.3 KB
/
main.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
import os
import warnings
import argparse
import datetime
import sys
import multiprocessing as mp
import psutil
import time
import timeit
# Importing global constants and variables useful for the execution of the code
from src import *
LIST_OF_MODELS = ['AVRI', 'IEEE9', 'IEEE14', 'SMIB', 'TwoAreas']
parser = argparse.ArgumentParser()
parser.add_argument("function", help = HELP_FUNCTION)
# Arguments to `nyiso` (download NYISO data)
parser.add_argument("--year", help = HELP_YEAR, type = int)
parser.add_argument("--path", help = HELP_PATH)
# Arguments to `run_pf`
parser.add_argument("--version", help = HELP_VERSION) # also needed for `val_pf`
parser.add_argument("--window", help = HELP_WINDOW)
parser.add_argument("--date", help = HELP_DATE)
parser.add_argument("--loads", help = HELP_LOADS, type = int)
parser.add_argument("--delete", help = HELP_DELETE, type = bool)
parser.add_argument("--seed", help = HELP_SEED, type = int)
parser.add_argument("--model", help = HELP_MODEL) # also needed for `val_pf`, `run_sim`, and `extract`
# Arguments to `val_pf` and `run_sim`
parser.add_argument("--tool", help = HELP_TOOL) # also needed for extract
parser.add_argument("--proc", help = HELP_PROC, type = int)
parser.add_argument("--cores", help = HELP_CORES, type = int)
parser.add_argument("--pc", help = HELP_PC)
# Arguments to `run_sim`
parser.add_argument("--n_pf", help = HELP_POWER_FLOWS, type = int)
parser.add_argument("--n_sc", help = HELP_SCENARIOS, type = int)
parser.add_argument("--n_sim", help = HELP_NSIM, type = int)
# Arguments to `extract`
parser.add_argument("--mu", help = HELP_MU, type = float)
parser.add_argument("--sigma", help = HELP_SIGMA, type = float)
args = parser.parse_args()
_function = args.function
if __name__ == "__main__":
# Recording execution time
start_time = timeit.default_timer()
# Validating function and arguments
if args.function:
_function = args.function
if _function not in ['nyiso', 'run_pf', 'val_pf', 'run_sim', 'extract']:
raise ValueError('Function not available')
else:
################################################
## DOWNLOADING NYISO DATA
################################################
if _function == 'nyiso':
# Importing dependencies (just those required to speed up code execution)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
from src.nyiso_data import *
print(f"\n{'':=^45}")
print(f"{'DOWNLOADING NYISO DATA':^45}")
print(f"{'':=^45}\n")
if args.year:
_year = args.year
else:
_year = CURRENT_YEAR
print(f"NYISO data download starts by default from {_year}\n")
if args.path:
_path = args.path
else:
_path = os.path.join(os.getcwd(), "data")
print(f"Download path for NYISO data not specified. Defaulting to: \n{_path}\n")
download_nyiso_data(start_year = _year, destination_folder = _path, verbose = False)
print(f"\nDownload NYISO data from {_year} to {CURRENT_YEAR} complete")
################################################
## RUNNING TIME-SERIES POWER FLOW
################################################
if _function == 'run_pf':
# Importing dependencies (just those required to speed up code execution)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
from src.pf2rec import *
from src.nyiso_data import *
print(f"\n{'':=^45}")
print(f"RUNNING TIME-SERIES POWER FLOW WITH NYISO DATA")
print(f"{'':=^45}\n")
if args.version:
_version = args.version
if _version not in ['1.5.0', '2.0.0']:
raise ValueError("Not compatible OpenIPSL version")
else:
_version = '1.5.0'
print(f"OpenIPSL version defaults to {_version}\n")
if args.model:
_model = args.model
if _model not in LIST_OF_MODELS:
raise ValueError("Model not available")
else:
_model = 'IEEE14'
print(f"Model not specified. Defaulting to {_model}")
_model_name = f"{_model}_Base_Case"
if _version == '2.0.0':
print("Warning: All quantities in OpenIPSL > 2.0.0 are in SI units. I will do my best to parse them correctly. Proceed with caution.\n")
_model_lib = '_new'
elif _version == '1.5.0':
_model_lib = '_old'
if args.window:
_window = args.window
if _window not in ['day', 'week', 'month']:
raise ValueError("Time window for power flow computation not valid")
else:
_window = 'day'
print(f"Time window defaults to {_window}\n")
if args.loads:
_loads = args.loads
if _loads > 11:
# Making sure the number of loads does not exceed the maximum number of zones in NYISO
print(f"Warning: Specified loads to vary ({_loads}) exceeds the number of NYISO zones. Defaulting to 11.")
_loads = 11
else:
_loads = 5
print(f"Number of loads to vary defaults to {_loads}")
if args.delete:
_delete = args.delete
else:
print(f"Deleting previous power flow results (entire 'PF_Data' subfolder). Change --delete to 'False' to keep them")
_delete = True
if args.date:
_date = args.date
# Function to validate date
if validate_date(_date, _window):
pass
else:
raise ValueError("Invalid date. Date might be in the future")
pass
else:
# Date defaults to the day before today
_date = f"{PREV_NOW.month:02d}/{PREV_NOW.day:02d}/{PREV_NOW.year}"
print(f"Date defaults to {_date}\n")
if args.seed:
_seed = args.seed
else:
_seed = 0
print(f"No seed value specified. Defaults to {_seed}")
# Getting NYISO data
load_profiles = dict.fromkeys(NYISO_ZONES)
print("Loading power flow data from NYISO:")
for lp in tqdm(load_profiles):
data = dict.fromkeys(['load', 'best', 'worst'])
if _window == 'day':
time_stamps, load, best, worst = visualize_load_forecast(_date, lp, "data", False)
elif _window == 'week':
time_stamps, load, best, worst = get_weekly_behavior(_date, lp, "data", False)
elif _window == 'month':
_output_dict = get_monthly_behavior(_date, lp, "data", False)
_monthly_data = _output_dict['monthly']
time_stamps, load, best, worst = _monthly_data['Time_Stamp'], _monthly_data['Actual_Load'], _monthly_data['Best_Forecast'], _monthly_data['Worst_Forecast']
# Saving as numpy arrays (for memory)
data['load'] = np.asarray(load, dtype = np.float32)
data['best'] = np.asarray(best, dtype = np.float32)
data['worst'] = np.asarray(worst, dtype = np.float32)
load_profiles[lp] = data
data = None
print(f"\n{'':-^45}")
print('Summary of power flow computation')
print(f"{'':-^45}")
print(f"{'Model':<30} {_model} ({_model_name})")
print(f"{'OpenIPSL':<30} {_version:<20}")
print(f"{'Window':<30} {_window:<20}")
print(f"{'Given date':<30} {_date:<20}")
print(f"{'Varying loads':<30} {_loads:<20}")
print(f"{'Number of power flows':<30} {len(time_stamps)*3}")
print(f"{'':-^45}\n")
# Pack arguments in a dictionary
args_ts = dict()
args_ts['_model'] = _model
args_ts['_model_name'] = _model_name
args_ts['_loads'] = _loads
args_ts['_window'] = _window
args_ts['_model_lib'] = _model_lib
args_ts['_version'] = _version
args_ts['_verbose'] = False
args_ts['_delete'] = _delete
args_ts['_seed'] = _seed
# Running time-series power flow
ts_powerflow(args_ts, _date, _load_profiles = load_profiles,
_time_stamps = time_stamps)
################################################
## VALIDATING POWER FLOW RESULTS
################################################
if _function == "val_pf":
# Importing dependencies (just those required to speed up code execution)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
from src.validate_pf import *
print(f"\n{'':=^45}")
print(f"VALIDATING POWER FLOWS FOR DYNAMIC SIMULATIONS")
print(f"{'':=^45}\n")
if args.tool:
_tool = args.tool
if _tool not in ['dymola', 'om']:
raise ValueError("Invalid tool. Only 'dymola' and 'om' (OpenModelica) are supported")
else:
print("No tool specified. Using 'dymola' by default")
_tool = 'dymola'
if args.version:
_version = args.version
if _version not in ['1.5.0', '2.0.0']:
raise ValueError('Invalid version. Only OpenIPSL 1.5.0 and 2.0.0 are supported')
else:
print("No OpenIPSL version specified. Defaulting to '1.5.0'") # TBD
_version = '1.5.0'
if args.model:
_model = args.model
if _model not in LIST_OF_MODELS:
raise ValueError("Model not available")
else:
_model = 'IEEE14'
print(f"Model not specified. Defaulting to {_model}")
_model_name = f"{_model}_Base_Case"
_model_package = _model
if args.pc:
_type_pc = args.pc
if _type_pc not in ['pc', 'vm']:
raise ValueError("Type of PC not supported")
else:
_type_pc = "pc"
if _type_pc == 'vm':
# Loading validation parameters
with open(r'val_parameters_vm.yaml') as f:
val_params = yaml.load(f, Loader = yaml.FullLoader)
elif _type_pc == 'pc':
# Loading validation parameters
with open(r'val_parameters_pc.yaml') as f:
val_params = yaml.load(f, Loader = yaml.FullLoader)
# Converting relative path to absolute paths
if _version == '1.5.0':
_data_path_old = f"models/_old/{_model}/PF_Data"
_model_path_old = f"models/_old/{_model}/package.mo"
_data_path = os.path.abspath(os.path.join(os.getcwd(), _data_path_old))
_model_path = os.path.abspath(os.path.join(os.getcwd(), _model_path_old))
elif _version == '2.0.0':
_data_path_new = f"models/_new/{_model}/PF_Data"
_model_path_new = f"models/_new/{_model}/package.mo"
_data_path = os.path.abspath(os.path.join(os.getcwd(), _data_path_new))
_model_path = os.path.abspath(os.path.join(os.getcwd(), _model_path_new))
if args.proc:
_n_proc = args.proc
else:
_n_proc = 1
print(f"Multiprocessing not specified. Defaulting to serial processing (n_proc = {_n_proc})")
if args.cores:
_n_cores = args.cores
else:
if psutil.cpu_count(logical = False) == 1:
_n_cores = 1
else:
_n_cores = psutil.cpu_count(logical = False) - 1
print("Cores to use for simulation not specified")
print(f"Setting number of cores to {_n_cores}")
if _n_proc*_n_cores > (psutil.cpu_count(logical = False) - 1):
_n_proc = psutil.cpu_count(logical = False) - 1
if psutil.cpu_count(logical = False) == 1:
_n_proc = 1
_n_cores = 1
print(f"Too many processes/cores. I can handle maximum {psutil.cpu_count(logical = False) - 1} processes/cores")
print(f"Setting number of processes to {psutil.cpu_count(logical = False) - 1}")
print(f"Setting number of cores to {_n_cores}")
val_params['version'] = _version
val_params['n_cores'] = _n_cores
val_params['n_proc'] = _n_proc
val_params['model_path'] = _model_path
val_params['model_package'] = _model_package
val_params['model_name'] = _model_name
# Getting power flow list from `PF_Data` directory
pf_list = get_pf_files(_data_path)
# Distributing scenarios among specified number of processes
pf_dist = distribute_scenarios(pf_list, _n_proc)
print(f"\n{'':-^45}")
print('Summary of power flow validation')
print(f"{'':-^45}")
print(f"{'Model name':<30} {_model_name} in package {_model_package}")
print(f"{'OpenIPSL version:':<30} {_version}")
print(f"{'Tool':<30} {_tool:<20}")
print(f"{'Process(es)':<30} {_n_proc:<20}")
print(f"{'Core(s) per process':<30} {_n_cores:<20}")
print(f"{'Power flow validations':<30} {len(pf_list):<20}\n")
# Commanding parallel simulations using multiprocessing
p = mp.Pool()
# List of running processes
process = []
for np in range(_n_proc):
if _tool == 'dymola':
if _n_proc == 1:
dymola_validation(pf_list, _data_path, val_params, np + 1)
# apfun = p.apply_async(dymola_validation,
# args = (pf_dist, _data_path, val_params, np + 1, ))
# process.append(apfun)
else:
# dymola_validation(pf_dist, _data_path, val_params, np + 1)
apfun = p.apply_async(dymola_validation,
args = (pf_dist[np], _data_path, val_params, np + 1, ))
process.append(apfun)
elif _tool == 'om':
if _n_proc == 1:
om_validation(pf_list, _data_path, val_params, np + 1)
# apfun = p.apply_async(om_validation,
# args = (pf_dist, _data_path, val_params, np + 1, ))
# process.append(apfun)
else:
# om_validation(pf_dist, _data_path, val_params, np + 1)
apfun = p.apply_async(om_validation,
args = (pf_dist[np], _data_path, val_params, np + 1, ))
process.append(apfun)
p.close()
p.join()
if _function == "run_sim":
# Importing dependencies (just those required to speed up code execution)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
from src.automated_simulation import *
print(f"\n{'':=^45}")
print(f"RUNNING DYNAMIC SIMULATIONS")
print(f"{'':=^45}\n")
if args.tool:
_tool = args.tool
if _tool not in ['dymola', 'om']:
raise ValueError("Invalid tool. Only 'dymola' and 'om' (OpenModelica) are supported")
else:
print("No tool specified. Using 'dymola' by default")
_tool = 'dymola'
if args.version:
_version = args.version
if _version not in ['1.5.0', '2.0.0']:
raise ValueError('Invalid version. Only OpenIPSL 1.5.0 and 2.0.0 are supported')
else:
print("No OpenIPSL version specified. Defaulting to '1.5.0'")
_version = '1.5.0'
if args.model:
_model = args.model
if _model not in LIST_OF_MODELS:
raise ValueError("Model not available")
else:
_model = 'IEEE14'
print(f"Model not specified. Defaulting to {_model}")
_model_name = f"{_model}_Base_Case"
_model_package = _model
if args.pc:
_type_pc = args.pc
if _type_pc not in ['pc', 'vm']:
raise ValueError("Type of PC not supported")
else:
_type_pc = "pc"
print(f"Setting simulations to run on {_type_pc}")
if _type_pc == 'vm':
# Loading simulation parameters for virtual machine
with open(r'sim_parameters_vm.yaml') as f:
sim_params = yaml.load(f, Loader = yaml.FullLoader)
elif _type_pc == 'pc':
with open(r'sim_parameters_pc.yaml') as f:
sim_params = yaml.load(f, Loader = yaml.FullLoader)
# Converting relative path to absolute paths
if _version == '1.5.0':
_data_path_old = f"models/_old/{_model}/PF_Data"
_model_path_old = f"models/_old/{_model}/package.mo"
_data_path = os.path.abspath(os.path.join(os.getcwd(), _data_path_old))
_model_path = os.path.abspath(os.path.join(os.getcwd(), _model_path_old))
elif _version == '2.0.0':
_data_path_new = f"models/_new/{_model}/PF_Data"
_model_path_new = f"models/_new/{_model}/package.mo"
_data_path = os.path.abspath(os.path.join(os.getcwd(), _data_path_new))
_model_path = os.path.abspath(os.path.join(os.getcwd(), _model_path_new))
if args.proc:
_n_proc = args.proc
else:
_n_proc = 1
print(f"Multiprocessing not specified. Defaulting to serial processing (n_proc = {_n_proc})")
if args.cores:
_n_cores = args.cores
else:
if psutil.cpu_count(logical = False) == 1:
_n_cores = 1
else:
_n_cores = psutil.cpu_count(logical = False) - 1
print("Cores to use for simulation not specified")
print(f"Setting number of cores to {_n_cores}")
# Validating number of processes and cores
if _n_proc*_n_cores > (psutil.cpu_count(logical = False) - 1):
_n_proc = psutil.cpu_count(logical = False) - 1
if psutil.cpu_count(logical = False) == 1:
_n_proc = 1
_n_cores = 1
print(f"Too many processes/cores. I can handle maximum {psutil.cpu_count(logical = False) - 1} processes/cores")
print(f"Setting number of processes to {psutil.cpu_count(logical = False) - 1}")
print(f"Setting number of cores to {_n_cores}")
sim_params['version'] = _version
sim_params['n_cores'] = _n_cores
sim_params['n_proc'] = _n_proc
sim_params['model_path'] = _model_path
sim_params['model_package'] = _model_package
sim_params['model_name'] = _model_name
##################################################
### SELECTING POWER FLOWS
##################################################
# Getting power flow list from `PF_Data` directory
pf_list = get_pf_files(_data_path)
# Number of power flows (user input)
if args.n_pf:
_n_pf = args.n_pf
else:
_n_pf = len(pf_list)
print(f"No power flow number specified. Working with {len(pf_list)} power flows")
if _n_pf > len(pf_list):
_n_pf = len(pf_list)
print(f"Number of power flows exceeds available records. Defaults to {_n_pf}")
# Extracting power flows from the given list
pf_list = np.random.choice(pf_list, _n_pf, replace = False)
# Distributing scenarios among specified number of processes
# pf_dist = distribute_scenarios(pf_list, _n_proc)
##################################################
### SELECTING CONTINGENCY SCENARIOS
##################################################
_mo_model_folder = os.path.dirname(_model_path)
_mo_model_path = os.path.join(_mo_model_folder, _model_name + ".mo")
_components = generate_component_list(_mo_model_path)
# Extracting lines
_lines = _components['lines']
# Creating line contingency strings
_line_contingencies = generate_contingencies(_lines)
if args.n_sc:
_n_sc = args.n_sc
else:
print("Number of contingencies not specified")
_n_sc = 50
if _n_sc > len(_line_contingencies['scenarios']):
_n_sc = len(_line_contingencies['scenarios'])
print(f"Working with {_n_sc} contingency scenarios")
scenarios = randomize_scenarios(_line_contingencies, _n_sc)
_n_scenarios = len(scenarios)
sc_dist = distribute_scenarios(scenarios, _n_proc)
# Creating a temporary directory to allow multiple power flow
# simulations in parallel
_temp_dir_models = os.path.join(os.getcwd(), '_temp')
if os.path.exists(_temp_dir_models):
# Removing temporary directory if it exists
shutil.rmtree(_temp_dir_models)
else:
os.mkdir(_temp_dir_models) # could be removed but test it
if args.n_sim:
_max_simulations = args.n_sim
else:
print("Maximum number of simulations not specified.")
_max_simulations = 2000
if _max_simulations > _n_sc*_n_pf:
_max_simulations = min(1000, _n_sc*_n_pf)
print(f"Working with ~ {_max_simulations} simulations (exactly ({_n_proc * int(_max_simulations/_n_proc)}))")
# Adding the maximum number of simulations to `sim_params`
sim_params['max_simulations'] = int(_max_simulations/_n_proc)
##################################################
### DISPATCHING SIMULATIONS
##################################################
print(f"\n{'':-^45}")
print('Summary of time-domain simulation')
print(f"{'':-^45}")
print(f"{'Model name':<30} {_model_name} in package {_model_package}")
print(f"{'OpenIPSL version:':<30} {_version}")
print(f"{'Tool':<30} {_tool:<20}")
print(f"{'Process(es)':<30} {_n_proc:<20}")
print(f"{'Core(s) per process':<30} {_n_cores:<20}")
print(f"{'Power flows':<30} {_n_pf:<20}")
print(f"{'Contingency scenarios':<30} {_n_scenarios:<20}")
print(f"{'Total simulations:':<30} {'~ '}{int(_max_simulations/_n_proc)}{'/process ('}{int(_max_simulations/_n_proc)*_n_proc}{')':<20} \n") # Commanding parallel simulations using multiprocessing
p = mp.Pool()
# List of running processes
process = []
for np in range(_n_proc):
if _tool == 'dymola':
if _n_proc == 1:
dymola_simulation(pf_list, scenarios, sim_params, np + 1)
# apfun = p.apply_async(dymola_simulation,
# args = (pf_dist, _data_path, sim_params, np + 1, ))
# process.append(apfun)
else:
# dymola_simulation(pf_dist, scenarios, _data_path, sim_params, np + 1)
apfun = p.apply_async(dymola_simulation,
args = (pf_list, sc_dist[np], sim_params, np + 1, ))
process.append(apfun)
elif _tool == 'om':
if _n_proc == 1:
om_simulation(pf_list, scenarios, sim_params, np + 1)
# apfun = p.apply_async(om_simulation,
# args = (pf_dist, _data_path, sim_params, np + 1, ))
# process.append(apfun)
else:
# om_simulation(pf_dist, scenarios, _data_path, sim_params, np + 1)
apfun = p.apply_async(om_simulation,
args = (pf_list, sc_dist[np], sim_params, np + 1, ))
process.append(apfun)
p.close()
p.join()
# Deleting temporary directory
if os.path.exists(_temp_dir_models):
shutil.rmtree(_temp_dir_models)
if _function == 'extract':
# Importing dependencies (just those required to speed up code execution)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
from src.extract_data import *
print(f"\n{'':=^45}")
print(f"EXTRACTING DATA FROM DYNAMIC SIMULATION RESULTS")
print(f"{'':=^45}\n")
# Validating user inputs
if args.tool:
_tool = args.tool
if _tool not in ['dymola', 'om']:
raise ValueError("Invalid tool. Only 'dymola' and 'om' (OpenModelica) are supported")
else:
# Raising warning. Directory may not exist. Continuing with caution
_tool = 'dymola'
warnings.warn("No tool specified. Using 'dymola' by default. Output directory may not exist");
if args.model:
_model = args.model
if _model not in LIST_OF_MODELS:
raise ValueError("Model not available")
else:
_model = 'IEEE14'
warnings.warn(f"Model not specified. Defaulting to {_model}. Output directory may not exist");
if args.version:
_version = args.version
if _version not in ['1.5.0', '2.0.0']:
raise ValueError('Invalid version. Only OpenIPSL 1.5.0 and 2.0.0 are supported')
else:
print("No OpenIPSL version specified. Defaulting to '1.5.0'")
_version = '1.5.0'
warnings.warn("Please specify the version of OpenIPSL employed for data generation. The extraction script may fail defaulting to OpenIPSL 1.5.0.")
if args.mu:
_mu = args.mu
else:
_mu = 0.0
print("No mean for Gaussian noise in measurements. Assumed mean = 0")
if args.sigma:
_sigma = args.sigma
else:
_sigma = 0.01
print(f"No standard deviation for Gaussian noise in measurements. Assumed sigma = {_sigma}")
if args.pc:
_type_pc = args.pc
if _type_pc not in ['pc', 'vm']:
raise ValueError("Type of PC not supported")
else:
_type_pc = "pc"
print(f"Loading simulations results of {_type_pc}")
if _type_pc == 'vm':
# Loading simulation parameters for virtual machine
with open(r'sim_parameters_vm.yaml') as f:
sim_params = yaml.load(f, Loader = yaml.FullLoader)
elif _type_pc == 'pc':
with open(r'sim_parameters_pc.yaml') as f:
sim_params = yaml.load(f, Loader = yaml.FullLoader)
# Getting working directory (according to tool and OS)
if platform.system() == 'Windows':
if _tool == 'dymola':
_working_directory = os.path.join(os.path.abspath(sim_params['working_directory_windows']), _model)
elif _tool == 'om':
_working_directory = os.path.join(os.path.abspath(sim_params['om_working_directory_windows']), _model)
elif platform.system() == 'Linux':
if _tool == 'dymola':
_working_directory = os.path.join(os.path.abspath(sim_params['working_directory_linux']), _model)
elif _tool == 'om':
_working_directory = os.path.join(os.path.abspath(sim_params['om_working_directory_linux']), _model)
# Validating whether the current working directory exists or not
if not os.path.exists(_working_directory):
raise ValueError('Working directory does not exist. Dynamic simulations may not have been dispatched (or results might have been removed)')
# Creating path to save data for experiment
_path = os.path.join(os.getcwd(), "data", "sim_res", _model)
# Creating path to save results (if it does not exist)
if not os.path.exists(_path):
os.makedirs(_path)
# Printing working directory and tool
print(f"\n{'':-^45}")
print('Summary for time-domain simulation data extraction')
print(f"{'':-^45}")
print(f"{'Model name':<30} {_model}")
print(f"{'Tool':<30} {_tool}")
print(f"{'Working directory':<30}\n {_working_directory}")
print(f"{'Experiment result path':<30}\n {_path}")
# Extracting data
extract_data(_tool, _model, _version, _path, _working_directory, _mu, _sigma)
if _function == 'label':
# Driver for labeling code
pass
# Finishing recording of execution time
stop_time = timeit.default_timer()
# Printing execution time
execution_time = stop_time - start_time
print(f"\nProgram executed in {execution_time:.4f} s ({execution_time/60:.4f} min / {execution_time/3600:.4f} h)")