-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPowerML.py
1966 lines (1569 loc) · 97.4 KB
/
PowerML.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "Ugwumadu Chinonso, Jose Tabares, and Anup Pandey"
__affiliation__ = "A-1 Group, Los Alamos National Laboratory, NM, USA."
__credits__ = ["Ugwumadu Chinonso, Jose Tabares, and Anup Pandey"]
__version__ = "0.0.1"
__email__ = "[email protected]"
print("######################################## S T A R T O F T H E A L G O R I T M ##########################################################")
print()
print('Greetings! I am PowerModel-AI, born from the research publication "PowerModel-AI: A First On-the-fly Machine-Learning Predictor for AC Power Flow Solutions." \n\
Feel free to use my capabilities for non-profit endeavors, but please remember to cite my paper in your work.\nThank you, and enjoy exploring my features!\n')
#****************************************************************** Introduction ********************************************************************#
# This script contains the algorithm for PowerModel-AI. It is associated to our manuscript titled: PowerModel-AI: A First On-the-fly Machine-Learning
# Predictor for AC Power Flow Solutions.
# While this script is totally free for academic (non-profit) use, We would appreciate citation of our paper when you use any part of this script for
# your own work. Thank You and Enjoy!
#***************************************************************************************************************************************************#
welcome = 'Greetings! I am PowerModel-AI, born from the research publication "PowerModel-AI: A First On-the-fly Machine-Learning Predictor for AC Power Flow Solutions." \n \n\
Feel free to use my capabilities for non-profit endeavors, but please remember to cite my paper in your work.\n \nThank you, and enjoy exploring my features!\n'
# Import libraries
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
import os
import julia
from scipy.stats import gaussian_kde
import numpy as np
import matplotlib.pyplot as plt
import json
import plotly.express as px
import plotly.graph_objects as go
import streamlit as st
import random as ran
import numpy as np
import pandas as pd
import time
#----------------------------------------------------------- End: Library Imports ---------------------------------------------------------#
#******************************************************************************************************************************************#
#******************************************************************************************************************************************#
#******************************************************************************************************************************************#
#******************************************************************************************************************************************#
#******************************************************************************************************************************************#
#----------------------------------------------------------- Set-UP Stage 1 ---------------------------------------------------------------#
## Page Set up
st.set_page_config(
page_title=f"PowerModel-AI",
page_icon="⚡",
layout="wide"
)
#----------------- Parameters ---------------------------------#
logo = "./etc/Setup Files/PM_LOGO.png"
lanl_logo = "./etc/Setup Files/LANL_LOGO.png"
domain_file = "/Training Domain.txt"
gen_power_limit_file = "/Gen Power Limits.txt"
julia_params = "./etc/Setup Files/Julia Parameters.txt"
retrain_folder = "./etc/on-the-fly"
#--------------------------------------------------------------#
welcome = '\n\n\n\n # Hello there! 👋 \
\n \n \n ###### I am :blue[PowerModel-AI] :robot_face:, conceived from the research publication titled: ***PowerModel-AI: A First On-the-fly Machine-Learning Predictor for AC Power Flow Solutions.***\
\n \n ###### Feel free to use my capabilities for :blue-background[non-profit endeavors] :100:, but please remember to :violet[cite my parents] :point_up_2: in your work.\
\n \n ###### Thank you, and enjoy exploring my features! :tada:\n'
#----------------- Functions ----------------------------------#
def stream_data():
for word in welcome.split(" "):
yield word + " "
time.sleep(0.08)
def readTrainingDomain(txt_path):
"""
Reads the new training domain limit from a text file.
The function expects the text file to contain domain limits, where the first line is ignored, and the second line
contains the new training domain limit as a numeric value.
Parameters
----------
txt_path : str
Path to the text file containing the training domain limits.
Returns
-------
float
The new training domain limit as a float value.
Notes
-----
The text file format should be similar to:
```
base_training_domain_limit: <base_value>
new_training_domian_limit: <new_value>
```
Example
-------
Assuming `domain_limits.txt` contains:
```
base_training_domain_limit: 100
new_training_domian_limit: 150
```
Calling `readTrainingDomain('domain_limits.txt')` will return:
```
150.0
```
"""
with open(txt_path, "r") as f:
a = f.readline()
line = f.readline()
upper_domain_st = np.array(line.rstrip('\t').split()[1]).astype(np.float64)
return float(upper_domain_st)
#*******************************************************************************************#
def writeTrainingDomain(txt_path, new_domain, base_training_domain_limit):
"""
Writes training domain limits to a text file.
The file will contain two key-value pairs:
- The base training domain limit.
- The new training domain limit.
Parameters
----------
txt_path : str
Path to the output text file where the domain limits will be written.
new_domain : str
The new training domain limit to be written in the file.
base_training_domain_limit : str
The base training domain limit to be written in the file.
Returns
-------
None
Notes
-----
The output file will have the following format:
```
base_training_domain_limit: <base_training_domain_limit_value>
new_training_domian_limit: <new_domain_value>
```
Example
-------
If `base_training_domain_limit = "100"`, `new_domain = "150"`, and `txt_path = "domain_limits.txt"`,
the file `domain_limits.txt` will contain:
```
base_training_domain_limit: 100
new_training_domian_limit: 150
```
"""
with open(txt_path, "w") as o:
o.write("base_training_domain_limit:" + "\t" + base_training_domain_limit + '\n')
o.write("new_training_domian_limit:" + "\t" + new_domain)
#*******************************************************************************************#
def readGenPowerLimit(txt_path):
"""
Reads generator power limits from a text file.
The text file is expected to have two lines:
- The first line contains space-separated variable names (e.g., generator IDs or labels).
- The second line contains corresponding numeric power limit values.
Parameters
----------
txt_path : str
Path to the text file containing generator power limit data.
Returns
-------
tuple
power_limit_var : list of str
A list of variable names representing generator identifiers.
power_limit_val : numpy.ndarray
A NumPy array of generator power limits as float values.
Notes
-----
The text file format should follow this structure:
- First line: variable names (strings).
- Second line: space-separated numeric values (floats) for each generator.
Example
-------
Assuming `power_limits.txt` contains the following:
```
Gen1 Gen2 Gen3
100.0 200.0 300.0
```
Calling `readGenPowerLimit('power_limits.txt')` will return:
```
(['Gen1', 'Gen2', 'Gen3'], array([100.0, 200.0, 300.0]))
```
"""
with open(txt_path, "r") as f:
lines = f.readlines()
power_limit_var = lines[0].rstrip('\n').split()
power_limit_val = np.array(lines[1].rstrip('\n').split()).astype(np.float64)
return power_limit_var, power_limit_val
#*******************************************************************************************#
def writeGenPowerLimit(txt_path, gen_power_limit_dict):
"""
Writes generator power limits to a text file.
The file will contain two lines:
- The first line consists of variable names (generator IDs or labels) separated by tabs.
- The second line contains the corresponding power limit values, also separated by tabs.
Parameters
----------
txt_path : str
Path to the output text file where the generator power limits will be written.
gen_power_limit_dict : dict
A dictionary where keys are generator variable names (str) and values are the corresponding power limits (float or int).
Returns
-------
None
Notes
-----
The output file will have the following format:
```
Gen1 Gen2 Gen3
100 200 300
```
Example
-------
If `gen_power_limit_dict = {"Gen1": 100, "Gen2": 200, "Gen3": 300}` and `txt_path = "gen_limits.txt"`,
the file `gen_limits.txt` will contain:
```
Gen1 Gen2 Gen3
100 200 300
```
"""
with open(txt_path, 'w') as o:
line_one = [var_name + "\t\t" for var_name in gen_power_limit_dict.keys()]
o.write("".join(line_one) + '\n')
line_two = [str(val) + "\t\t\t" for val in gen_power_limit_dict.values()]
o.write("".join(line_two) + '\n')
#*******************************************************************************************#
def writeJuliaPath(txt_path, julia_path):
"""
Writes the specified Julia installation path to a text file.
Parameters
----------
txt_path : str
Path to the output text file where the Julia path will be written.
julia_path : str
The Julia installation path to be written in the file.
Returns
-------
None
Example
-------
If `julia_path = "/usr/local/bin/julia"` and `txt_path = "julia_path.txt"`,
the file `julia_path.txt` will contain:
```
/usr/local/bin/julia
```
"""
with open(txt_path, "w") as o:
o.write(julia_path)
#*******************************************************************************************#
def cleanSlate():
if "training_domain" in st.session_state:
del st.session_state["training_domain"]
def getUpperBound():
if "training_domain_UB" in st.session_state:
st.session_state["training_domain_UB"] = readTrainingDomain(retrain_folder+ "//" + selected_dirname + domain_file)
#*******************************************************************************************#
def disableCaseSelect(b):
"""
Disables or enables case selection and removes the training domain from session state if it exists.
Args:
b (bool): Boolean indicating whether to disable (True) or enable (False) case selection.
Returns:
None
Side Effects:
- Sets `st.session_state["disableCaseSelect"]` to the value of `b`.
- Deletes `st.session_state["training_domain"]` if it is present in session state.
Example:
Disable case selection and clear training domain:
>>> disableCaseSelect(True)
Enable case selection:
>>> disableCaseSelect(False)
"""
st.session_state["disableCaseSelect"] = b
cleanSlate()
#*******************************************************************************************#
def disableRetrain(b):
"""
Disables or enables the retraining option in session state.
Args:
b (bool): Boolean indicating whether to disable (True) or enable (False) retraining.
Returns:
None
Side Effects:
- Sets `st.session_state["disableRetrain"]` to the value of `b`.
Example:
Disable retraining:
>>> disableRetrain(True)
Enable retraining:
>>> disableRetrain(False)
"""
st.session_state["disableRetrain"] = b
#*******************************************************************************************#
def retainBuses():
"""
Retains the current state of `load_changes` in the session state.
If `load_changes` exists in `st.session_state`, it will reassign the value of
`st.session_state.load_changes` to itself, ensuring the value is retained.
Returns:
None
Side Effects:
- Reassigns `st.session_state.load_changes` to itself if it exists.
Example:
To retain the value of `load_changes`:
>>> retain()
"""
if "load_changes" in st.session_state:
st.session_state.load_changes = st.session_state.load_changes
getUpperBound() #NEW
def runPowerModelJL():
st.session_state.run = True
#----------------------------------------------------------- End: Set-UP Stage 1 ----------------------------------------------------------#
#******************************************************************************************************************************************#
#******************************************************************************************************************************************#
#******************************************************************************************************************************************#
#******************************************************************************************************************************************#
#******************************************************************************************************************************************#
#----------------------------------------------------------- Set-UP Stage 2 ---------------------------------------------------------------#
## More set-up initializations
st.markdown("## PowerModel-AI")
st.sidebar.image(logo, width=200)
st.session_state.getButton = 0
num_buses = 10
dir_path='./CaseModels'
dir_names = os.listdir(dir_path)
# The power grid is selected using this select box
selected_dirname = st.sidebar.selectbox('Select Bus Case:', dir_names, index = None, placeholder="Select Power Grid",key="selected_directory", on_change=disableCaseSelect, args=(False,), help="Select bus case to analyze.")
if selected_dirname:
# Read the base model training domain
with open(retrain_folder+ "//" + selected_dirname + domain_file, "r") as f:
line1 = f.readline()
base_training_domain_limit = float(line1.rstrip('\t').split()[1])
# Get the name for the current workifn directory.
num_buses = int(selected_dirname[3:].replace("-Bus", "").replace("K","000"))
st.session_state.dir_name_st = os.path.join(dir_path, selected_dirname) #file_selector()
dir_name = st.session_state.dir_name_st
# Get the upper training limit in file.
st.session_state.training_domain_limit = readTrainingDomain(retrain_folder+ "//" + selected_dirname + domain_file)
training_domain_limit = st.session_state.training_domain_limit
# this initialize the training domains to be used later
if "training_domain" not in st.session_state:
st.session_state.training_domain = 2.5 # the max to which we have trained the model
training_domain = st.session_state.training_domain
st.session_state.training_domain_UB = training_domain_limit
training_domain_UB = st.session_state.training_domain_UB
st.session_state.training_domain_LB = 0.01
training_domain_LB = st.session_state.training_domain_LB
#*** Debug ***#
print(f"A: After training domain was added to session state for: {selected_dirname}")
print(f"A: {selected_dirname}, {base_training_domain_limit}, {training_domain_UB}, {training_domain_limit}")
#*** Debug ***#
if "training_domain" in st.session_state:
training_domain = st.session_state.training_domain
training_domain_LB = st.session_state.training_domain_LB
training_domain_UB = np.round(st.session_state.training_domain_UB,2)
#*** Debug ***#
print(f"C: While training domain exist in session state for: {selected_dirname}")
print(f"C: {selected_dirname}, {base_training_domain_limit}, {training_domain_UB}, {training_domain_limit}")
#*** Debug ***#
#----------------------------------------------------------- End: Set-UP Stage 2 ----------------------------------------------------------#
#******************************************************************************************************************************************#
#******************************************************************************************************************************************#
#******************************************************************************************************************************************#
#******************************************************************************************************************************************#
#******************************************************************************************************************************************#
#----------------------------------------------------------- Set-UP Stage 3 ---------------------------------------------------------------#
## File Name Initialization for the Model and Associated Parameters
st.session_state.gen_model_name_MW = '/_genModel_MW.pth'
gen_model_name_MW = st.session_state.gen_model_name_MW
st.session_state.gen_model_name_Mvar = '/_genModel_Mvar.pth'
gen_model_name_Mvar = st.session_state.gen_model_name_Mvar
st.session_state.gen_features = "/_genFeatures.npz"
gen_features = st.session_state.gen_features
st.session_state.gen_targets_MW = "/_genTargets_MW.npz"
gen_targets_MW= st.session_state.gen_targets_MW
st.session_state.gen_targets_Mvar = "/_genTargets_Mvar.npz"
gen_targets_Mvar= st.session_state.gen_targets_Mvar
st.session_state.base_model_name_vpu = '/_baseModel_vpu.pth'
base_model_name_vpu = st.session_state.base_model_name_vpu
st.session_state.base_model_name_vang = '/_baseModel_vang.pth'
base_model_name_vang = st.session_state.base_model_name_vang
st.session_state.base_features_vpu = "/_baseFeatures_vpu.npz"
base_features_vpu= st.session_state.base_features_vpu
st.session_state.base_features_vang = "/_baseFeatures_vang.npz"
base_features_vang= st.session_state.base_features_vang
st.session_state.base_targets_vpu = "/_baseTargets_vpu.npz"
base_targets_vpu = st.session_state.base_targets_vpu
st.session_state.base_targets_vang = "/_baseTargets_vang.npz"
base_targets_vang = st.session_state.base_targets_vang
st.session_state.updated_model_name_vpu = '/_updatedModel_vpu.pth'
updated_model_name_vpu = st.session_state.updated_model_name_vpu
st.session_state.updated_model_name_vang = '/_updatedModel_vang.pth'
updated_model_name_vang = st.session_state.updated_model_name_vang
st.session_state.retrain_bus_features_vpu = "/_updatedFeatures_vpu.npz"
retrain_bus_features_vpu = st.session_state.retrain_bus_features_vpu
st.session_state.retrain_bus_features_vang = "/_updatedFeatures_vang.npz"
retrain_bus_features_vang = st.session_state.retrain_bus_features_vang
st.session_state.retrain_bus_targets_vpu = "/_updatedTargets_vpu.npz"
retrain_bus_targets_vpu = st.session_state.retrain_bus_targets_vpu
st.session_state.retrain_bus_targets_vang = "/_updatedTargets_vang.npz"
retrain_bus_targets_vang = st.session_state.retrain_bus_targets_vang
st.session_state.updated_gen_model_name_MW = '/_updatedGenModel_MW.pth'
updated_gen_model_name_MW = st.session_state.updated_gen_model_name_MW
st.session_state.updated_gen_model_name_Mvar = '/_updatedGenModel_Mvar.pth'
updated_gen_model_name_Mvar = st.session_state.updated_gen_model_name_Mvar
st.session_state.retrain_gen_features = "/_updatedGenFeatures.npz"
retrain_gen_features = st.session_state.retrain_gen_features
st.session_state.retrain_gen_targets_MW = "/_updatedGenTargets_MW.npz"
retrain_gen_targets_MW = st.session_state.retrain_gen_targets_MW
st.session_state.retrain_gen_targets_Mvar = "/_updatedGenTargets_Mvar.npz"
retrain_gen_targets_Mvar = st.session_state.retrain_gen_targets_Mvar
#------------------ END OF Model and Feature File Names ------------------#
## Used to filter the bus nodes whose power demands are being updated
st.session_state.change_list = []
change_list = st.session_state.change_list
## More Functions
#----------------------- Maps in Tab 2 -----------------------------------------#
def plot_map(state, plot_container, buses, branches, map_title, result_type):
"""
Plots a map displaying bus locations and branch connections using Plotly.
The map visualizes bus data and connections between them based on the specified result type,
which determines the color coding for the buses.
Parameters
----------
state : object
The current application state (not used directly in the function).
plot_container : object
The Streamlit container where the plot will be displayed.
buses : DataFrame
A DataFrame containing bus data with columns for latitude, longitude, size, and bus numbers.
branches : DataFrame
A DataFrame containing branch data with columns for latitude, longitude, and nominal voltages.
map_title : str
The title of the map to be displayed.
result_type : str
The type of result to determine the color scheme for the bus markers.
Acceptable values are "vpu" for voltage per unit or any other value for voltage angle.
Returns
-------
None
Example
-------
To plot a map with bus and branch data:
>>> plot_map(state, plot_container, buses, branches, "Network Map", "vpu")
"""
if result_type == "vpu":
v_color='vpu'
else:
v_color = 'vangle'
fig = px.scatter_mapbox(buses,
lat='Latitude:1',
lon='Longitude:1',
color = v_color,
color_continuous_scale= px.colors.qualitative.Dark2_r,
size='size',
size_max=12,
zoom=9,
hover_name = "BusNum",
)
branch_data = {
'lats' : [],
'lons' : [],
'kvs' : [],
}
for index, row in branches.iterrows():
branch_data['lats'].extend([row['Latitude'], row['Latitude:1'], None])
branch_data['lons'].extend([row['Longitude'], row['Longitude:1'], None])
branch_data['kvs'].extend([row['BusNomVolt'], row['BusNomVolt'], None])
fig2 = px.line_mapbox(
lat=branch_data['lats'],
lon=branch_data['lons'],
)
fig2.update_traces(line=dict(color="gray", width=2))
fig.add_traces(fig2.data)
fig.update_layout(mapbox_style="carto-positron",
title=map_title,
width=800, height=800,
)
plot_container.plotly_chart(fig, theme="streamlit", use_container_width=True)
def get_name(self, row, state, id):
"""
Generates a name for the specified row based on the type of object it represents.
This method constructs a name string depending on the object's type (Buses, ACLines, Transformers,
Generators, or Loads) and adds the generated name to the row.
Parameters
----------
self : object
The instance of the class this method belongs to.
row : pandas.Series
A row of data containing information about the object.
state : object
The current application state (not used directly in this method).
id : object
An identifier (not used directly in this method).
Returns
-------
pandas.Series
The updated row with the generated name added as a new key-value pair.
Example
-------
To get a name for a bus row:
>>> row = pd.Series({"Bus": 1})
>>> updated_row = get_name(instance, row, state, id)
>>> print(updated_row['name'])
"1"
To get a name for a transformer row:
>>> row = pd.Series({"Bus From": 1, "To Bus": 2, "Ckt": "1"})
>>> updated_row = get_name(instance, row, state, id)
>>> print(updated_row['name'])
"(1,2,1)"
"""
if self.name == "Buses":
name = str(row["Bus"])
elif self.name == "ACLines" or self.name == "Transformers":
name = "({},{},{})".format(row["Bus From"], row["To Bus"], row['Ckt'])
elif self.name == "Generators" or self.name == "Loads":
name = "({},{})".format(row['Bus'], row['ID'])
row['name'] = name
return row
def update_voltage(row, v):
"""
Updates the voltage values in a row based on the provided voltage data.
This function modifies the given row by setting the voltage per unit (vpu) and voltage angle (vangle)
values from the provided voltage dictionary or array `v`, using the bus number from the row.
Parameters
----------
row : pandas.Series
A row of data containing information about the bus, including its bus number.
v : dict or array-like
A collection of voltage values, where the index/key corresponds to the bus number.
Returns
-------
pandas.Series
The updated row with the voltage values set.
Example
-------
To update the voltage for a specific row:
>>> row = pd.Series({"BusNum": 1})
>>> v = {1: 0.95, 2: 0.98}
>>> updated_row = update_voltage(row, v)
>>> print(updated_row["vpu"], updated_row["vangle"])
0.95 0.95
"""
row["vpu"] = v[row["BusNum"]]
row["vangle"] = v[row["BusNum"]]
return row
#----------------------------------------------------------- E N D M A P S ------------------------------------------------------------#
#******************************************************************************************************************************************#
#******************************************************************************************************************************************#
#******************************************************************************************************************************************#
#******************************************************************************************************************************************#
#******************************************************************************************************************************************#
#------------------------------------------------- Wrapper Class for PowerModels.jl -------------------------------------------------------#
class mld:
"""
Class for generating a Julia file for power system modeling and analysis.
This class provides methods to create and write to a Julia file, setting up the necessary imports,
parsing data from a specified model file, and executing power flow analysis.
Attributes
----------
jlFile : str
The name of the Julia file to be created.
modelFile : str
The name of the model file to be parsed.
samples : int
The number of samples for Power Demand Multiplier (to be set externally).
LB : float
Lower bound for Power demand change percentage (to be set externally).
UB : float
Upper bound for Power demand change percentage (to be set externally).
jsonName : str
The name of the JSON file where results will be saved.
Parameters
----------
jl_file_name : str
The name of the Julia file to be created.
model_file : str
The name of the model file to be parsed.
"""
def __init__(self, jl_file_name, model_file):
"""
Initializes the mld class with the provided Julia and model file names.
Parameters
----------
jl_file_name : str
The name of the Julia file to be created.
model_file : str
The name of the model file to be parsed.
"""
self.jlFile = jl_file_name
self.modelFile = model_file
def createJLFile(self):
"""
Creates and opens a new Julia file for writing.
Returns
-------
None
"""
self.io = open(self.jlFile, "w+")
def writeJLHeader(self):
"""
Writes the header information and necessary imports to the Julia file.
Returns
-------
None
"""
if not hasattr(self, "io"):
self.createJLFile()
self.io.write(f"using PowerModels\n")
self.io.write(f"import InfrastructureModels\n")
self.io.write(f"import Memento\n")
self.io.write(f'Memento.setlevel!(Memento.getlogger(InfrastructureModels), "error")\n')
self.io.write(f'PowerModels.logger_config!("error")\n')
self.io.write(f'import Ipopt\n')
self.io.write(f'import Random\n')
self.io.write(f'using StatsBase\n')
self.io.write(f'using Distributions\n')
self.io.write(f'import JuMP\n')
self.io.write(f'import Random\n')
self.io.write(f'using JSON\n\n')
self.io.write(f'start_time = time()\n')
def writeJLParse(self):
"""
Parses the model file and extracts generator information into the Julia file.
Returns
-------
None
"""
file = self.modelFile
file = file.replace('//', "////")
self.io.write(f'data = PowerModels.parse_file("{file}")\n')
# Shut off shunts (Future Plan)
self.io.write(f'buses = []\n')
self.io.write('for (i, gen) in data["gen"]\n')
self.io.write('\tif !(gen["gen_bus"] in buses)\n')
self.io.write('\t\tappend!(buses,gen["gen_bus"])\n')
self.io.write('\tend\n')
self.io.write('end\n')
self.io.write('gen_dict = Dict{String, Any}()\n')
self.io.write('genfuel = Dict{String, Any}()\n')
self.io.write('gentype = Dict{String, Any}()\n')
self.io.write('lookup_buses = Dict{Int, Any}()\n')
self.io.write('counter = 1\n')
self.io.write('for (i, gen) in data["gen"]\n')
self.io.write('\tif gen["gen_bus"] in keys(lookup_buses) && gen["gen_status"] == 1\n')
self.io.write('\t\tindx = lookup_buses[gen["gen_bus"]]\n')
self.io.write('\t\tgen_dict[indx]["pg"] += gen["pg"]\n')
self.io.write('\t\tgen_dict[indx]["qg"] += gen["qg"]\n')
self.io.write('\t\tgen_dict[indx]["pmax"] += gen["pmax"]\n')
self.io.write('\t\tgen_dict[indx]["pmin"] += gen["pmin"]\n')
self.io.write('\t\tgen_dict[indx]["qmax"] += gen["qmax"]\n')
self.io.write('\t\tgen_dict[indx]["qmin"] += gen["qmin"]\n')
self.io.write('\telseif gen["gen_status"] == 1\n')
self.io.write('\t\tgen["index"] = counter\n')
self.io.write('\t\tgen_dict["$(counter)"] = gen\n')
self.io.write('\t\tgenfuel["$(counter)"] = data["genfuel"][i]\n')
self.io.write('\t\tgentype["$(counter)"] = data["gentype"][i]\n')
self.io.write('\t\tlookup_buses[gen["gen_bus"]] = "$(counter)"\n')
self.io.write('\t\tglobal counter += 1\n')
self.io.write('\tend\n')
self.io.write('end\n')
self.io.write('data["gen"] = gen_dict\n')
self.io.write('data["genfuel"] = genfuel\n')
self.io.write('data["gentype"] = gentype\n')
def writeJLGetBaseInfo(self):
"""
Writes the base information retrieval section to the Julia file.
Returns
-------
None
"""
self.io.write('nlp_solver = JuMP.optimizer_with_attributes(Ipopt.Optimizer, "tol"=>1e-6, "print_level"=>0)\n')
self.io.write('results = Dict{String, Any}()\n')
self.io.write('results["system"] = data\n')
self.io.write('result = PowerModels.solve_ac_pf(data, nlp_solver)\n')
self.io.write('results["base pf"] = data\n')
self.io.write('results["pf"] = Dict{Int, Any}()\n')
self.io.write('results["NOpf"] = Dict{Int, Any}()\n')
def writeJLLoadChangePF(self):
"""
Writes the Power demand change power flow analysis section to the Julia file.
Returns
-------
None
"""
self.io.write(f'samples = {self.samples}\n')
self.io.write('for i = 1:samples\n')
self.io.write('\tdata_ = deepcopy(data)\n')
self.io.write('\tl = length(keys(data_["load"]))\n')
self.io.write('\tn = rand(1:l)\n')
self.io.write('\tm = sample(1:l, n, replace=false)\n')
self.io.write('\tdelta = Dict{Int, Any}()\n')
self.io.write('\tfor (j, k) in enumerate(m)\n')
self.io.write(f'\t\tpct = rand(Uniform({self.LB},{self.UB}))\n')
self.io.write('\t\tpd = (pct) * data_["load"]["$(k)"]["pd"]\n')
self.io.write('\t\tqd = (pct) * data_["load"]["$(k)"]["qd"]\n')
self.io.write('\t\tdata_["load"]["$(k)"]["pd"] = pd\n')
self.io.write('\t\tdata_["load"]["$(k)"]["qd"] = qd\n')
self.io.write('\t\tdelta[k] = pct\n')
self.io.write('\tend\n')
self.io.write('\tresult = PowerModels.solve_ac_pf(data_, nlp_solver)\n')
self.io.write('\tresult["load"] = data_["load"]\n')
self.io.write('\tresult["delta"] = delta\n')
self.io.write('\tif result["termination_status"] == LOCALLY_SOLVED\n')
self.io.write('\t\tresults["pf"][i] = result\n')
self.io.write('\telse\n')
self.io.write('\t\tresults["NOpf"][i] = result\n')
self.io.write('\tend\n')
self.io.write('end\n')
def writeJLJSON(self):
"""
Writes the results to a JSON file at the end of the analysis.
Returns
-------
None
"""
filename = self.jsonName.replace("\\", "/")
self.io.write(f'open("{filename}","w") do f\n')
self.io.write('\tJSON.print(f, results)\n')
self.io.write('end\n')
#------------------------------------------- END: CLASS FOR JULIA TO RUN POWER MODEL ------------------------------------------------------#
#******************************************************************************************************************************************#
#******************************************************************************************************************************************#
#******************************************************************************************************************************************#
#******************************************************************************************************************************************#
#******************************************************************************************************************************************#
#------------------------------------------ COLLECT POWERMODEL.jl DATA FOR ML PIPELINE ----------------------------------------------------#
def collectGridData(dir_path_, base_case):
if __name__ == '__main__':
filename = ""
holder = 1
for file in os.listdir(dir_path_):
if '.json' in file:
filename = os.path.join(dir_path_, file)
f = open(filename)
data_ = json.load(f)
base_system = data_["base pf"]
base_gen = base_system['gen']
base_buses_wt_load = base_system['load']
base_bus_dict = base_system["bus"]
NOpf_data = data_["NOpf"]
pf_data = data_["pf"]
pf_iterations = np.array(list(pf_data.keys()))
feasible_solution_report = f"{len(pf_data.keys())} out of {len(NOpf_data.keys()) + len(pf_data.keys())} events have feaseable solutions"
base_gen_MW = []
base_gen_MVar = []
base_load_MW = []
base_load_MVar = []
buses_ = []
buses_wt_gen_ = []
buses_wt_load_ = []
for the_bus_ in range(1, num_buses + 1):
buses_.append(int(the_bus_))
for the_bus_ in range(1, len(base_gen.keys()) + 1):
buses_wt_gen_.append(int(base_gen[str(the_bus_)]['gen_bus']))
base_gen_MW.append(base_gen[str(the_bus_)]['pg'])
base_gen_MVar.append(base_gen[str(the_bus_)]['qg'])
for the_bus_ in range(1, len(base_buses_wt_load.keys()) + 1):
buses_wt_load_.append(int(base_buses_wt_load[str(the_bus_)]['load_bus']))
base_load_MW.append(base_buses_wt_load[str(the_bus_)]['pd'])
base_load_MVar.append(base_buses_wt_load[str(the_bus_)]['qd'])
buses_ = np.array(buses_)
buses_wt_gen_ = np.array(buses_wt_gen_)
buses_wt_load_ = np.array(buses_wt_load_)
for run_iter in range(len(pf_iterations)):
iter = pf_iterations[run_iter]
data_dict = pf_data[str(iter)]["solution"]
data_dict_genPower = data_dict['gen']
data_dict_busVPU = data_dict['bus']
data_dict_loadedBus = pf_data[str(iter)]["load"]
if holder == 1:
base_gen = base_system['gen']
base_buses_wt_load = base_system['load']
base_gen_MW = []
base_gen_MVar = []
base_load_MW = []
base_load_MVar = []
buses_ = []
buses_wt_gen_ = []
buses_wt_load_ = []
for the_bus_ in range(1, len(data_dict_busVPU.keys()) + 1):
buses_.append(int(the_bus_))
for the_bus_ in range(1, len(base_gen.keys()) + 1):
buses_wt_gen_.append(int(base_gen[str(the_bus_)]['gen_bus']))
base_gen_MW.append(base_gen[str(the_bus_)]['pg'])
base_gen_MVar.append(base_gen[str(the_bus_)]['qg'])
for the_bus_ in range(1, len(data_dict_loadedBus.keys()) + 1):
buses_wt_load_.append(int(data_dict_loadedBus[str(the_bus_)]['load_bus']))
base_load_MW.append(base_buses_wt_load[str(the_bus_)]['pd'])
base_load_MVar.append(base_buses_wt_load[str(the_bus_)]['qd'])
buses_ = np.array(buses_)
buses_wt_gen_ = np.array(buses_wt_gen_)
buses_wt_load_ = np.array(buses_wt_load_)
num_buses_ = len(buses_)
bus_vpu_arr = np.empty([len(pf_iterations), num_buses_])
bus_vangle_arr = np.empty([len(pf_iterations), num_buses_])
load_MW_arr = np.empty([len(pf_iterations),len(buses_wt_load_)])
load_Mvar_arr = np.empty([len(pf_iterations),len(buses_wt_load_)])
gen_MW_arr = np.zeros([len(pf_iterations), num_buses_])
gen_Mvar_arr = np.zeros([len(pf_iterations), num_buses_])
base_gen_MW_arr = np.zeros([len(pf_iterations), num_buses_])
base_gen_Mvar_arr = np.zeros([len(pf_iterations), num_buses_])
sum_generation_MW = np.zeros(len(pf_iterations))
sum_generation_Mvar = np.zeros(len(pf_iterations))
holder += 1
# Get the Power demand data
if True:
MW_data = [data_dict_loadedBus[str(mw)]['pd'] for mw in range(1, len(data_dict_loadedBus.keys()) + 1)]
Mvar_data = [data_dict_loadedBus[str(mw)]['qd'] for mw in range(1, len(data_dict_loadedBus.keys()) + 1)]
load_MW_arr[run_iter] = np.squeeze(MW_data) # nodes with load,
load_Mvar_arr[run_iter] = np.squeeze(Mvar_data)
# Get VPU data
if True:
vpu_data = [data_dict_busVPU[str(mw)]['vm'] for mw in buses_]
vangle_data = [data_dict_busVPU[str(mw)]['va'] for mw in buses_]
bus_vpu_arr[run_iter] = np.squeeze(vpu_data)
bus_vangle_arr[run_iter] = np.squeeze(vangle_data)
# Get generator data
if True:
genMW_data = [data_dict_genPower[str(mw)]['pg'] for mw in range(1, len(data_dict_genPower.keys()) + 1)]
genMvar_data = [data_dict_genPower[str(mw)]['qg'] for mw in range(1, len(data_dict_genPower.keys()) + 1)]
sum_generation_MW[run_iter] = np.sum(genMW_data)