forked from GOCompetition/Evaluation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata.py
More file actions
4573 lines (3900 loc) · 172 KB
/
data.py
File metadata and controls
4573 lines (3900 loc) · 172 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Data structures and read/write methods for input and output data file formats
Author: Jesse Holzer, jesse.holzer@pnnl.gov
Date: 2018-04-05
str(hex(x))[2:].upper()
"""
# data.py
# module for input and output data
# including data structures
# and read and write functions
import csv
import os
import sys
import math
import traceback
#from io import StringIO
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
# init_defaults_in_unused_field = True # do this anyway - it is not too big
read_unused_fields = True
write_defaults_in_unused_fields = False
write_values_in_unused_fields = True
gen_cost_dx_margin = 1.0e-6 # ensure that consecutive x points differ by at least this amount
gen_cost_dydx_min = 1.0e-6 # ensure that the marginal cost (i.e. cost function slope) never goes below this value ???
gen_cost_y_min = 1.0e-6 # ensure that the cost never goes below this value ???
gen_cost_ddydx_margin = 1.0e-6 # ensure that consecutive slopes differ by at least this amount
gen_cost_x_bounds_margin = 1.0e-2 # ensure that the pgen lower and upper bounds are covered by at least this amount
gen_cost_default_marginal_cost = 1.0e2 # default marginal cost (usd/mw-h) used if a cost function has an error
raise_extra_field = False # set to true to raise an exception if extra fields are encountered. This can be a problem if a comma appears in an end-of-line comment.
raise_con_quote = False # set to true to raise an exception if the con file has quotes. might as well accept this since we are rewriting the files
#gen_cost_revise = False # set to true to revise generator cost functions in the event of a problem, e.g. nonconvexity, not covering pmin, pmax, etc.
normalize_participation_factors = True # set to true to normalize the participation factors so they sum to 1
#extend_cost_functions_to_p_min_max = True # set to true to extend the first cost function segment through pmin - 1 and the last one through pmax + 1
#remove_inner_cost_function_points_nondistinct = True # set to true to remove the inner points in a cost function if they are too close
#remove_inner_cost_function_points_nonconvex = True # set to true to remove the inner points in a cost function if they violate convexity
id_str_ok_chars = [
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
default_branch_limit = 9999.0
do_check_pb_nonnegative = False # cannot fix this
do_check_id_str_ok = False # difficult fix
do_check_rate_pos = True # fixed in scrubber
do_check_swrem_zero = True # fixed by scrubber
do_check_bmin_le_binit_le_bmax = True # fixed by scrubber - with extra scrubber options below
do_combine_switched_shunt_blocks_steps = True # generally want this to be false
do_fix_binit = True # generally want this to be false
EMERGENCY_CAPACITY_FACTOR = 0.1
EMERGENCY_MARGINAL_COST_FACTOR = 5.0
def alert(alert_dict):
print(alert_dict)
def parse_token(token, val_type, default=None):
val = None
if len(token) > 0:
val = val_type(token)
elif default is not None:
val = val_type(default)
else:
try:
print('required field missing data, token: %s, val_type: %s' % (token, val_type))
raise Exception('empty field not allowed')
except Exception as e:
traceback.print_exc()
raise e
#raise Exception('empty field not allowed')
return val
def pad_row(row, new_row_len):
try:
if len(row) != new_row_len:
if len(row) < new_row_len:
print('missing field, row:')
print(row)
raise Exception('missing field not allowed')
elif len(row) > new_row_len:
row = remove_end_of_line_comment_from_row(row, '/')
if len(row) > new_row_len:
alert(
{'data_type': 'Data',
'error_message': 'extra field, please ensure that all rows have the correcct number of fields',
'diagnostics': str(row)})
if raise_extra_field:
raise Exception('extra field not allowed')
else:
row = remove_end_of_line_comment_from_row(row, '/')
except Exception as e:
traceback.print_exc()
raise e
return row
'''
row_len = len(row)
row_len_diff = new_row_len - row_len
row_new = row
if row_len_diff > 0:
row_new = row + row_len_diff * ['']
return row_new
'''
def check_row_missing_fields(row, row_len_expected):
try:
if len(row) < row_len_expected:
print('missing field, row:')
print(row)
raise Exception('missing field not allowed')
except Exception as e:
traceback.print_exc()
raise e
def check_two_char_id_str(x):
char_ok_alert_dict = {
'data_type':
'IdStr',
'error_message':
'id string has nonallowable characters - each character must be in ["%s"]' % ('","'.join(id_str_ok_chars)),
'diagnostics':
{'id': x}}
if len(x) > 2:
alert(
{'data_type':
'IdStr2Char',
'error_message':
'id string too long - must be 1 or 2 characters',
'diagnostics':
{'id': x}})
if len(x) <= 0:
alert(
{'data_type':
'IdStr2Char',
'error_message':
'id string too short - must be 1 or 2 characters',
'diagnostics':
{'id': x}})
if len(x) == 2:
x0 = x[0]
x1 = x[1]
isok = check_id_str_single_char_ok(x0)
if not isok:
alert(char_ok_alert_dict)
isok = check_id_str_single_char_ok(x1)
if not isok:
alert(char_ok_alert_dict)
if len(x) == 1:
x0 = x[0]
isok = check_id_str_single_char_ok(x0)
if not isok:
alert(char_ok_alert_dict)
def check_id_str_single_char_ok(x):
if do_check_id_str_ok:
isok = False
if x in id_str_ok_chars:
isok = True
else:
isok = True
return isok
def remove_end_of_line_comment_from_row_first_occurence(row, end_of_line_str):
index = [r.find(end_of_line_str) for r in row]
len_row = len(row)
entries_with_end_of_line_strs = [i for i in range(len_row) if index[i] > -1]
num_entries_with_end_of_line_strs = len(entries_with_end_of_line_strs)
if num_entries_with_end_of_line_strs > 0:
first_entry_with_end_of_line_str = min(entries_with_end_of_line_strs)
len_row_new = first_entry_with_end_of_line_str + 1
row_new = [row[i] for i in range(len_row_new)]
row_new[len_row_new - 1] = remove_end_of_line_comment(row_new[len_row_new - 1], end_of_line_str)
else:
row_new = [r for r in row]
return row_new
def remove_end_of_line_comment_from_row(row, end_of_line_str):
index = [r.find(end_of_line_str) for r in row]
len_row = len(row)
entries_with_end_of_line_strs = [i for i in range(len_row) if index[i] > -1]
num_entries_with_end_of_line_strs = len(entries_with_end_of_line_strs)
if num_entries_with_end_of_line_strs > 0:
#last_entry_with_end_of_line_str = min(entries_with_end_of_line_strs)
#len_row_new = last_entry_with_end_of_line_str + 1
row_new = [r for r in row]
#row_new = [row[i] for i in range(len_row_new)]
for i in entries_with_end_of_line_strs:
row_new[i] = remove_end_of_line_comment(row_new[i], end_of_line_str)
#row_new[len_row_new - 1] = remove_end_of_line_comment(row_new[len_row_new - 1], end_of_line_str)
else:
#row_new = [r for r in row]
row_new = row
return row_new
def remove_end_of_line_comment(token, end_of_line_str):
token_new = token
index = token_new.find(end_of_line_str)
if index > -1:
token_new = token_new[0:index]
return token_new
class Data:
'''In physical units, i.e. data convention, i.e. input and output data files'''
def __init__(self):
self.raw = Raw()
self.rop = Rop()
self.inl = Inl()
self.con = Con()
def read(self, raw_name, rop_name, inl_name, con_name):
self.raw.read(raw_name)
self.rop.read(rop_name)
self.inl.read(inl_name)
self.con.read(con_name)
def write(self, raw_name, rop_name, inl_name, con_name):
self.raw.write(raw_name)
self.rop.write(rop_name)
self.inl.write(inl_name)
self.con.write(con_name)
def check(self):
'''Checks Grid Optimization Competition assumptions'''
self.raw.check()
self.rop.check()
self.inl.check()
self.con.check()
self.check_gen_implies_cost_gen()
self.check_cost_gen_implies_gen()
self.check_gen_cost_x_margin()
self.check_no_offline_generators_in_contingencies()
self.check_no_offline_lines_in_contingencies()
self.check_no_offline_transformers_in_contingencies()
self.check_no_generators_in_con_not_in_raw()
self.check_no_branches_in_con_not_in_raw()
def scrub(self):
'''modifies certain data elements to meet Grid Optimization Competition assumptions'''
if do_combine_switched_shunt_blocks_steps:
self.raw.switched_shunts_combine_blocks_steps()
self.raw.scrub()
self.rop.scrub()
self.inl.scrub()
#if gen_cost_revise:
# self.check_gen_cost_revise()
self.scrub_gen_costs()
self.remove_contingencies_with_offline_generators()
self.remove_contingencies_with_offline_lines()
self.remove_contingencies_with_offline_transformers()
self.remove_contingencies_with_generators_not_in_raw()
self.remove_contingencies_with_branches_not_in_raw()
def convert(self):
'''converts for study 1'''
self.add_gen_emergency_capacity_and_cost_point()
#self.add_load_gens()
def convert_to_offline(self):
'''converts the operating point to the offline starting point'''
self.raw.set_operating_point_to_offline_solution()
def add_gen_emergency_capacity_and_cost_point(self):
self.raw.add_gen_emergency_capacity()
self.rop.add_gen_emergency_cost_point()
def check_gen_implies_cost_gen(self):
gen_set = set([(g.i, g.id) for g in self.raw.get_generators()])
cost_gen_set = set(self.rop.generator_dispatch_records.keys())
gen_not_cost_gen = gen_set.difference(cost_gen_set)
if len(gen_not_cost_gen) > 0:
alert(
{'data_type':
'Data',
'error_message':
'fails no generators in RAW file not in ROP file. Please ensure that every generator in the RAW file is also in the ROP file.',
'diagnostics':
{'num gens': len(gen_not_cost_gen),
'gens': [
{'gen i': g[0], 'gen id': g[1]}
for g in gen_not_cost_gen]}})
def check_cost_gen_implies_gen(self):
gen_set = set([(g.i, g.id) for g in self.raw.get_generators()])
cost_gen_set = set(self.rop.generator_dispatch_records.keys())
cost_gen_not_gen = cost_gen_set.difference(gen_set)
if len(cost_gen_not_gen) > 0:
alert(
{'data_type':
'Data',
'error_message':
'fails no generators in ROP file not in RAW file. Please ensure that every generator in the ROP file is also in the RAW file.',
'diagnostics':
{'num gens': len(cost_gen_not_gen),
'gens': [
{'gen i': g[0], 'gen id': g[1]}
for g in cost_gen_not_gen]}})
def scrub_gen_costs(self):
for g in self.raw.get_generators():
g_i = g.i
g_id = g.id
g_pt = g.pt
g_pb = g.pb
gdr = self.rop.generator_dispatch_records[(g_i, g_id)]
apdr = self.rop.active_power_dispatch_records[gdr.dsptbl]
plcf = self.rop.piecewise_linear_cost_functions[apdr.ctbl]
np = len(plcf.points)
plcf.scrub(g_pb, g_pt)
"""
def check_gen_cost_revise(self):
for g in self.raw.get_generators():
g_i = g.i
g_id = g.id
g_pt = g.pt
g_pb = g.pb
gdr = self.rop.generator_dispatch_records[(g_i, g_id)]
apdr = self.rop.active_power_dispatch_records[gdr.dsptbl]
plcf = self.rop.piecewise_linear_cost_functions[apdr.ctbl]
np = len(plcf.points)
if np != plcf.npairs:
alert(
{'data_type':
'Data',
'error_message':
'revising generator piecewise linear cost function, np!=npairs',
'diagnostics':
{'gen i': g_i,
'gen id': g_id,
'gen pt': g_pt,
'gen pb': g_pb,
'np': np,
'npairs': plcf.npairs}})
plcf.revise(g_pb, g_pt)
continue
if np < 2:
alert(
{'data_type':
'Data',
'error_message':
'revising generator piecewise linear cost function, np<2',
'diagnostics':
{'gen i': g_i,
'gen id': g_id,
'gen pt': g_pt,
'gen pb': g_pb,
'np': np,
'npairs': plcf.npairs}})
plcf.revise(g_pb, g_pt)
continue
x = [p.x for p in plcf.points]
xmin = min(x)
if xmin > g_pb - gen_cost_x_bounds_margin:
alert(
{'data_type':
'Data',
'error_message':
'revising generator piecewise linear cost function, xmin > pmin - margin',
'diagnostics':
{'gen i': g_i,
'gen id': g_id,
'gen pt': g_pt,
'gen pb': g_pb,
'np': np,
'npairs': plcf.npairs,
'x': x}})
plcf.revise(g_pb, g_pt)
continue
xmax = max(x)
if xmax < g_pt + gen_cost_x_bounds_margin:
alert(
{'data_type':
'Data',
'error_message':
'revising generator piecewise linear cost function, xmax < pmax + margin',
'diagnostics':
{'gen i': g_i,
'gen id': g_id,
'gen pt': g_pt,
'gen pb': g_pb,
'np': np,
'npairs': plcf.npairs,
'x': x}})
plcf.revise(g_pb, g_pt)
continue
dx = [x[i + 1] - x[i] for i in range(np - 1)]
if any([dxi < gen_cost_dx_margin for dxi in dx]):
alert(
{'data_type':
'Data',
'error_message':
'revising generator piecewise linear cost function, dx < margin',
'diagnostics':
{'gen i': g_i,
'gen id': g_id,
'gen pt': g_pt,
'gen pb': g_pb,
'np': np,
'npairs': plcf.npairs,
'x': x,
'dx': dx}})
plcf.revise(g_pb, g_pt)
continue
if np > 2:
y = [p.y for p in plcf.points]
dy = [y[i + 1] - y[i] for i in range(np - 1)]
dydx = [dy[i] / dx[i] for i in range(np - 1)]
ddydx = [dydx[i + 1] - dydx[i] for i in range(np - 2)]
if any([ddydxi < gen_cost_ddydx_margin for ddydxi in ddydx]):
alert(
{'data_type':
'Data',
'error_message':
'revising generator piecewise linear cost function, ddydx < margin',
'diagnostics':
{'gen i': g_i,
'gen id': g_id,
'gen pt': g_pt,
'gen pb': g_pb,
'np': np,
'npairs': plcf.npairs,
'x': x,
'dx': dx,
'dy': dy,
'dydx': dydx,
'ddydx': ddydx}})
plcf.revise(g_pb, g_pt)
continue
"""
def check_gen_cost_x_margin(self):
for g in self.raw.get_generators():
g_i = g.i
g_id = g.id
g_pt = g.pt
g_pb = g.pb
gdr = self.rop.generator_dispatch_records[(g_i, g_id)]
apdr = self.rop.active_power_dispatch_records[gdr.dsptbl]
plcf = self.rop.piecewise_linear_cost_functions[apdr.ctbl]
plcf.check_x_max_margin(g_pt)
plcf.check_x_min_margin(g_pb)
def check_no_generators_in_con_not_in_raw(self):
'''check that no generators in the contingencies are not in the raw file.'''
ctgs = self.con.get_contingencies()
raw_gens = self.raw.get_generators()
raw_gens_id = sorted(list(set([(g.i, g.id) for g in raw_gens])))
gen_ctgs = [c for c in ctgs if len(c.generator_out_events) > 0]
gen_ctgs_event = [c.generator_out_events[0] for c in gen_ctgs]
con_gens_id = sorted(list(set([(g.i, g.id) for g in gen_ctgs_event])))
con_gens_not_raw_gens = sorted(list(set(con_gens_id) - set(raw_gens_id)))
for g in con_gens_not_raw_gens:
alert(
{'data_type':
'Data',
'error_message':
'fails no generators mentioned in contingencies that do not exist in RAW file.',
'diagnostics':
{'gen i': g[0],
'gen id': g[1]}})
def check_no_branches_in_con_not_in_raw(self):
'''check that no branches in the contingencies are not in the raw file.'''
ctgs = self.con.get_contingencies()
raw_branches = self.raw.get_nontransformer_branches() + self.raw.get_transformers()
raw_branches_id = sorted(list(set([(b.i, b.j, b.ckt) for b in raw_branches])))
branch_ctgs = [c for c in ctgs if len(c.branch_out_events) > 0]
branch_ctgs_event = [c.branch_out_events[0] for c in branch_ctgs]
con_branches_id = sorted(list(set([(b.i, b.j, b.ckt) for b in branch_ctgs_event])))
con_branches_not_raw_branches = sorted(list(set(con_branches_id) - set(raw_branches_id)))
for b in con_branches_not_raw_branches:
alert(
{'data_type':
'Data',
'error_message':
'fails no branches mentioned in contingencies that do not exist in RAW file.',
'diagnostics':
{'branch i': b[0],
'branch j': b[1],
'branch ckt': b[2]}})
def check_no_offline_generators_in_contingencies(self):
'''check that no generators that are offline in the base case
are going out of service in a contingency'''
gens = self.raw.get_generators()
offline_gen_keys = [(g.i, g.id) for g in gens if not (g.stat > 0)]
ctgs = self.con.get_contingencies()
gen_ctgs = [c for c in ctgs if len(c.generator_out_events) > 0]
gen_ctg_out_event_map = {
c:c.generator_out_events[0]
for c in gen_ctgs}
gen_ctg_gen_key_ctg_map = {
(v.i, v.id):k
for k, v in gen_ctg_out_event_map.items()}
offline_gens_outaged_in_ctgs_keys = set(offline_gen_keys) & set(gen_ctg_gen_key_ctg_map.keys())
for g in offline_gens_outaged_in_ctgs_keys:
gen = self.raw.generators[g]
ctg = gen_ctg_gen_key_ctg_map[g]
alert(
{'data_type':
'Data',
'error_message':
'fails no offline generators going out of service in contingencies. Please ensure that every generator that goes out of service in a contingency is in service in the base case, i.e. has stat=1.',
'diagnostics':
{'gen i': gen.i,
'gen id': gen.id,
'gen stat': gen.stat,
'ctg label': ctg.label,
'ctg gen event i': ctg.generator_out_events[0].i,
'ctg gen event id': ctg.generator_out_events[0].id}})
def remove_contingencies_with_generators_not_in_raw(self):
'''remove any contingencies where a generator that is not
present in the RAW file is going out of service'''
ctgs_label_to_remove = []
gens = self.raw.get_generators()
gens_key = [(g.i, g.id) for g in gens]
ctgs = self.con.get_contingencies()
gen_ctgs = [c for c in ctgs if len(c.generator_out_events) > 0]
gen_ctg_gen_key_map = {
c:(c.generator_out_events[0].i, c.generator_out_events[0].id)
for c in gen_ctgs}
gen_ctg_gens_key = list(set(gen_ctg_gen_key_map.values()))
gens_key_missing = list(set(gen_ctg_gens_key).difference(set(gens_key)))
num_gens = len(gens_key)
num_gens_missing = len(gens_key_missing)
gens_dict = {gens_key[i]:i for i in range(num_gens)}
gens_missing_dict = {gens_key_missing[i]:(num_gens + i) for i in range(num_gens_missing)}
gens_dict.update(gens_missing_dict)
ctgs_to_remove = [c for c in gen_ctgs if gens_dict[gen_ctg_gen_key_map[c]] >= num_gens]
ctgs_label_to_remove = [c.label for c in ctgs_to_remove]
for k in ctgs_label_to_remove:
alert(
{'data_type':
'Data',
'error_message':
'removing generator contingency where the generator does not exist in the RAW file',
'diagnostics':
{'ctg label': k}})
del self.con.contingencies[k]
def remove_contingencies_with_branches_not_in_raw(self):
'''remove any contingencies where a branch that is not
present in the RAW file is going out of service'''
ctgs_label_to_remove = []
lines = self.raw.get_nontransformer_branches()
transformers = self.raw.get_transformers()
branches_key = [(l.i, l.j, l.ckt) for l in (lines + transformers)]
ctgs = self.con.get_contingencies()
branch_ctgs = [c for c in ctgs if len(c.branch_out_events) > 0]
branch_ctg_branch_key_map = {
c:(c.branch_out_events[0].i, c.branch_out_events[0].j, c.branch_out_events[0].ckt)
for c in branch_ctgs}
branch_ctg_branches_key = list(set(branch_ctg_branch_key_map.values()))
branches_key_missing = list(set(branch_ctg_branches_key).difference(set(branches_key)))
num_branches = len(branches_key)
num_branches_missing = len(branches_key_missing)
branches_dict = {branches_key[i]:i for i in range(num_branches)}
branches_missing_dict = {branches_key_missing[i]:(num_branches + i) for i in range(num_branches_missing)}
branches_dict.update(branches_missing_dict)
ctgs_to_remove = [c for c in branch_ctgs if branches_dict[branch_ctg_branch_key_map[c]] >= num_branches]
ctgs_label_to_remove = [c.label for c in ctgs_to_remove]
for k in ctgs_label_to_remove:
alert(
{'data_type':
'Data',
'error_message':
'removing branch contingency where the branch does not exist in the RAW file',
'diagnostics':
{'ctg label': k}})
del self.con.contingencies[k]
def remove_contingencies_with_offline_generators(self):
'''remove any contingencies where a generator that is offline in
the base case is going out of service'''
ctgs_label_to_remove = []
gens = self.raw.get_generators()
offline_gen_keys = [(g.i, g.id) for g in gens if not (g.stat > 0)]
ctgs = self.con.get_contingencies()
gen_ctgs = [c for c in ctgs if len(c.generator_out_events) > 0]
gen_ctg_out_event_map = {
c:c.generator_out_events[0]
for c in gen_ctgs}
gen_ctg_gen_key_ctg_map = {
(v.i, v.id):k
for k, v in gen_ctg_out_event_map.items()}
offline_gens_outaged_in_ctgs_keys = set(offline_gen_keys) & set(gen_ctg_gen_key_ctg_map.keys())
ctgs_label_to_remove = list(set(
[gen_ctg_gen_key_ctg_map[g].label
for g in offline_gens_outaged_in_ctgs_keys]))
for k in ctgs_label_to_remove:
alert(
{'data_type':
'Data',
'error_message':
'removing generator contingency where the generator is out of service in the base case',
'diagnostics':
{'ctg label': k}})
del self.con.contingencies[k]
def check_no_offline_lines_in_contingencies(self):
'''check that no lines (nontranformer branches) that are offline in the base case
are going out of service in a contingency'''
lines = self.raw.get_nontransformer_branches()
offline_line_keys = [(g.i, g.j, g.ckt) for g in lines if not (g.st > 0)]
ctgs = self.con.get_contingencies()
branch_ctgs = [c for c in ctgs if len(c.branch_out_events) > 0]
branch_ctg_out_event_map = {
c:c.branch_out_events[0]
for c in branch_ctgs}
branch_ctg_branch_key_ctg_map = {
(v.i, v.j, v.ckt):k
for k, v in branch_ctg_out_event_map.items()}
offline_lines_outaged_in_ctgs_keys = set(offline_line_keys) & set(branch_ctg_branch_key_ctg_map.keys())
for g in offline_lines_outaged_in_ctgs_keys:
line = self.raw.nontransformer_branches[g]
ctg = branch_ctg_branch_key_ctg_map[g]
alert(
{'data_type':
'Data',
'error_message':
'fails no offline lines going out of service in contingencies. Please ensure that every line (nontransformer branch) that goes out of service in a contingency is in service in the base case, i.e. has st=1.',
'diagnostics':
{'line i': line.i,
'line j': line.j,
'line ckt': line.ckt,
'line st': line.st,
'ctg label': ctg.label,
'ctg branch event i': ctg.branch_out_events[0].i,
'ctg branch event j': ctg.branch_out_events[0].j,
'ctg branch event ckt': ctg.branch_out_events[0].ckt}})
def remove_contingencies_with_offline_lines(self):
'''remove any contingencies where a line that is offline in
the base case is going out of service'''
ctgs_label_to_remove = []
lines = self.raw.get_nontransformer_branches()
offline_line_keys = [(g.i, g.j, g.ckt) for g in lines if not (g.st > 0)]
ctgs = self.con.get_contingencies()
branch_ctgs = [c for c in ctgs if len(c.branch_out_events) > 0]
branch_ctg_out_event_map = {
c:c.branch_out_events[0]
for c in branch_ctgs}
branch_ctg_branch_key_ctg_map = {
(v.i, v.j, v.ckt):k
for k, v in branch_ctg_out_event_map.items()}
offline_lines_outaged_in_ctgs_keys = set(offline_line_keys) & set(branch_ctg_branch_key_ctg_map.keys())
ctgs_label_to_remove = list(set(
[branch_ctg_branch_key_ctg_map[g].label
for g in offline_lines_outaged_in_ctgs_keys]))
for k in ctgs_label_to_remove:
alert(
{'data_type':
'Data',
'error_message':
'removing line contingency where the line is out of service in the base case',
'diagnostics':
{'ctg label': k}})
del self.con.contingencies[k]
def check_no_offline_transformers_in_contingencies(self):
'''check that no branches that are offline in the base case
are going out of service in a contingency'''
transformers = self.raw.get_transformers()
offline_transformer_keys = [(g.i, g.j, g.ckt) for g in transformers if not (g.stat > 0)]
ctgs = self.con.get_contingencies()
branch_ctgs = [c for c in ctgs if len(c.branch_out_events) > 0]
branch_ctg_out_event_map = {
c:c.branch_out_events[0]
for c in branch_ctgs}
branch_ctg_branch_key_ctg_map = {
(v.i, v.j, v.ckt):k
for k, v in branch_ctg_out_event_map.items()}
offline_transformers_outaged_in_ctgs_keys = set(offline_transformer_keys) & set(branch_ctg_branch_key_ctg_map.keys())
for g in offline_transformers_outaged_in_ctgs_keys:
transformer = self.raw.transformers[g]
ctg = branch_ctg_branch_key_ctg_map[g]
alert(
{'data_type':
'Data',
'error_message':
'fails no offline transformers going out of service in contingencies. Please ensure that every transformer that goes out of service in a contingency is in service in the base case, i.e. has stat=1.',
'diagnostics':
{'transformer i': transformer.i,
'transformer j': transformer.j,
'transformer ckt': transformer.ckt,
'transformer stat': transformer.stat,
'ctg label': ctg.label,
'ctg branch event i': ctg.branch_out_events[0].i,
'ctg branch event j': ctg.branch_out_events[0].j,
'ctg branch event ckt': ctg.branch_out_events[0].ckt}})
def remove_contingencies_with_offline_transformers(self):
'''remove any contingencies where a transformer that is offline in
the base case is going out of service'''
ctgs_label_to_remove = []
transformers = self.raw.get_transformers()
offline_transformer_keys = [(g.i, g.j, g.ckt) for g in transformers if not (g.stat > 0)]
ctgs = self.con.get_contingencies()
branch_ctgs = [c for c in ctgs if len(c.branch_out_events) > 0]
branch_ctg_out_event_map = {
c:c.branch_out_events[0]
for c in branch_ctgs}
branch_ctg_branch_key_ctg_map = {
(v.i, v.j, v.ckt):k
for k, v in branch_ctg_out_event_map.items()}
offline_transformers_outaged_in_ctgs_keys = set(offline_transformer_keys) & set(branch_ctg_branch_key_ctg_map.keys())
ctgs_label_to_remove = list(set(
[branch_ctg_branch_key_ctg_map[g].label
for g in offline_transformers_outaged_in_ctgs_keys]))
for k in ctgs_label_to_remove:
alert(
{'data_type':
'Data',
'error_message':
'removing transformer contingency where the transformer is out of service in the base case',
'diagnostics':
{'ctg label': k}})
del self.con.contingencies[k]
class Raw:
'''In physical units, i.e. data convention, i.e. input and output data files'''
def __init__(self):
self.case_identification = CaseIdentification()
self.buses = {}
self.loads = {}
self.fixed_shunts = {}
self.generators = {}
self.nontransformer_branches = {}
self.transformers = {}
self.areas = {}
self.switched_shunts = {}
def scrub(self):
self.scrub_switched_shunts()
self.scrub_nontransformer_branches()
self.scrub_transformers()
def check(self):
self.check_case_identification()
self.check_buses()
self.check_loads()
self.check_fixed_shunts()
self.check_generators()
self.check_nontransformer_branches()
self.check_transformers()
self.check_areas()
self.check_switched_shunts()
def add_gen_emergency_capacity(self):
'''Add emergency capacity to each generator.
for study 1.
increase pmax by a fixed fraction = EMERGENCY_CAPACITY_FACTOR'''
for r in self.get_generators():
r.add_emergency_capacity()
def scrub_switched_shunts(self):
for r in self.get_switched_shunts():
r.scrub()
def scrub_nontransformer_branches(self):
for r in self.get_nontransformer_branches():
r.scrub()
def scrub_transformers(self):
for r in self.get_transformers():
r.scrub()
def check_case_identification(self):
self.case_identification.check()
def check_buses(self):
for r in self.get_buses():
r.check()
def check_loads(self):
for r in self.get_loads():
r.check()
def check_fixed_shunts(self):
for r in self.get_fixed_shunts():
r.check()
def check_generators(self):
for r in self.get_generators():
r.check()
def check_nontransformer_branches(self):
for r in self.get_nontransformer_branches():
r.check()
def check_transformers(self):
for r in self.get_transformers():
r.check()
def check_areas(self):
for r in self.get_areas():
r.check()
def check_switched_shunts(self):
for r in self.get_switched_shunts():
r.check()
def set_areas_from_buses(self):
area_i_set = set([b.area for b in self.buses.values()])
def area_set_i(area, i):
area.i = i
return area
self.areas = {i:area_set_i(Area(), i) for i in area_i_set}
def get_buses(self):
return sorted(self.buses.values(), key=(lambda r: r.i))
def get_loads(self):
return sorted(self.loads.values(), key=(lambda r: (r.i, r.id)))
def get_fixed_shunts(self):
return sorted(self.fixed_shunts.values(), key=(lambda r: (r.i, r.id)))
def get_generators(self):
return sorted(self.generators.values(), key=(lambda r: (r.i, r.id)))
def get_nontransformer_branches(self):
return sorted(self.nontransformer_branches.values(), key=(lambda r: (r.i, r.j, r.ckt)))
def get_transformers(self):
return sorted(self.transformers.values(), key=(lambda r: (r.i, r.j, r.k, r.ckt)))
def get_areas(self):
return sorted(self.areas.values(), key=(lambda r: r.i))
def get_switched_shunts(self):
return sorted(self.switched_shunts.values(), key=(lambda r: r.i))
def construct_case_identification_section(self):
#out_str = StringIO.StringIO()
out_str = StringIO()
#writer = csv.writer(out_str, quotechar="'", quoting=csv.QUOTE_NONNUMERIC)
writer = csv.writer(out_str, quoting=csv.QUOTE_NONE)
if write_values_in_unused_fields:
rows = [
[self.case_identification.ic, self.case_identification.sbase,
self.case_identification.rev, self.case_identification.xfrrat,
self.case_identification.nxfrat, self.case_identification.basfrq],
["%s" % self.case_identification.record_2], # no quotes here - typical RAW file
["%s" % self.case_identification.record_3]] # no quotes here - typical RAW file
#["'%s'" % self.case_identification.record_2],
#["'%s'" % self.case_identification.record_3]]
#["''"],
#["''"]]
elif write_defaults_in_unused_fields:
rows = [
[0, self.case_identification.sbase, 33, 0, 1, 60.0],
["''"],
["''"]]
else:
rows = [
[None, self.case_identification.sbase, 33, None, None, None],
["''"],
["''"]]
writer.writerows(rows)
return out_str.getvalue()
def construct_bus_section(self):
# note use quote_none and quote the strings manually
# values of None then are written as empty fields, which is what we want
out_str = StringIO()
writer = csv.writer(out_str, quoting=csv.QUOTE_NONE)
if write_values_in_unused_fields:
rows = [
[r.i, "'%s'" % r.name, r.baskv, r.ide, r.area, r.zone, r.owner, r.vm, r.va, r.nvhi, r.nvlo, r.evhi, r.evlo]
#for r in self.buses.values()] # might as well sort
for r in self.get_buses()]
elif write_defaults_in_unused_fields:
rows = [
[r.i, "' '", 0.0, 1, r.area, 1, 1, r.vm, r.va, r.nvhi, r.nvlo, r.evhi, r.evlo]
for r in self.get_buses()]
else:
rows = [
[r.i, None, None, None, r.area, None, None, r.vm, r.va, r.nvhi, r.nvlo, r.evhi, r.evlo]
for r in self.get_buses()]
writer.writerows(rows)
writer = csv.writer(out_str, quoting=csv.QUOTE_NONE)
writer.writerows([['0 / END OF BUS DATA BEGIN LOAD DATA']]) # no comma allowed without escape character
#out_str.write('0 / END OF BUS DATA, BEGIN LOAD DATA\n')
return out_str.getvalue()
def construct_load_section(self):
out_str = StringIO()
writer = csv.writer(out_str, quoting=csv.QUOTE_NONE)
if write_values_in_unused_fields:
rows = [
[r.i, "'%s'" % r.id, r.status, r.area, r.zone, r.pl, r.ql, r.ip, r.iq, r.yp, r.yq, r.owner, r.scale, r.intrpt]
for r in self.get_loads()]
elif write_defaults_in_unused_fields:
rows = [
[r.i, "'%s'" % r.id, r.status, self.buses[r.i].area, 1, r.pl, r.ql, 0.0, 0.0, 0.0, 0.0, 1, 1, 0]
for r in self.get_loads()]
else:
rows = [
[r.i, "'%s'" % r.id, r.status, None, None, r.pl, r.ql, None, None, None, None, None, None, None]
for r in self.get_loads()]
writer.writerows(rows)
writer = csv.writer(out_str, quoting=csv.QUOTE_NONE)
writer.writerows([['0 / END OF LOAD DATA BEGIN FIXED SHUNT DATA']])
return out_str.getvalue()
def construct_fixed_shunt_section(self):
out_str = StringIO()
writer = csv.writer(out_str, quoting=csv.QUOTE_NONE)
if write_values_in_unused_fields:
rows = [
[r.i, "'%s'" % r.id, r.status, r.gl, r.bl]
for r in self.get_fixed_shunts()]
elif write_defaults_in_unused_fields:
rows = [
[r.i, "'%s'" % r.id, r.status, r.gl, r.bl]
for r in self.get_fixed_shunts()]
else:
rows = [
[r.i, "'%s'" % r.id, r.status, r.gl, r.bl]
for r in self.get_fixed_shunts()]
writer.writerows(rows)
writer = csv.writer(out_str, quoting=csv.QUOTE_NONE)
writer.writerows([['0 / END OF FIXED SHUNT DATA BEGIN GENERATOR DATA']])
return out_str.getvalue()
def construct_generator_section(self):
out_str = StringIO()
writer = csv.writer(out_str, quoting=csv.QUOTE_NONE)
if write_values_in_unused_fields:
rows = [
[r.i, "'%s'" % r.id, r.pg, r.qg, r.qt, r.qb,
r.vs, r.ireg, r.mbase, r.zr, r.zx, r.rt, r.xt, r.gtap,
r.stat, r.rmpct, r.pt, r.pb, r.o1, r.f1, r.o2,