Repository navigation
Expand file tree
/
Copy pathaugmented_simulator.py
More file actions
1576 lines (1206 loc) · 73 KB
/
Copy pathaugmented_simulator.py
File metadata and controls
1576 lines (1206 loc) · 73 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
"""
Copyright (c) 2025,
Dr. Amarsagar Matavalam, Arizona State University (amar.sagar@asu.edu)
Shaban Ghias Satti, Arizona State University (ishabansatti@gmail.com)
This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International License. To view a copy of this license, visit:
https://creativecommons.org/licenses/by-nc-nd/4.0/
You are free to share this work (copy and redistribute it in any medium or format)
under the following terms:
- Attribution: You must give appropriate credit, provide a link to the license,
and indicate if changes were made.
- NonCommercial: You may not use the material for commercial purposes.
- NoDerivatives: If you remix, transform, or build upon the material,
you may not distribute the modified material.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR
OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
import numpy as np
import torch
from torch import optim
from lips.benchmark.powergridBenchmark import get_env
from lips.dataset.utils.powergrid_utils import get_kwargs_simulator_scenario
import torch.nn.functional as F
from lips.augmented_simulators import AugmentedSimulator
from scipy.sparse import csr_matrix
import scipy.sparse as sp
import torch_geometric as pytg
import torch.nn.functional as F
from scipy.sparse.sparsetools import csr_minus_csr
from torch import nn
from functools import *
import numba as nb
##################################################################################################################
class TorchSimulator(AugmentedSimulator):
"""Simulator class that allows to train and evalute your custom model
Parameters
----------
benchmark : PowerGridBenchmark
A benchmark object passed inside the ingestion program
config : ConfigManager
A lips ConfigManager object allowing the access to all the parameters in `config.ini`
scaler : StandardScaler
A scaler class already implemented in LIPS and selected in parameters.json file
device : torch.device
the device on which the execution should be executed, controlled by ingestion program
**kwargs
The set of supplementary parameters passed through the parameters.json file and `simulator_extra_parameters` key
"""
def __init__(self,
benchmark = None,
config = None,
scaler = None,
device = None,
**kwargs):
self.benchmark = benchmark
self.params = config.get_options_dict() # Load parameters from config.ini file
self.params.update(kwargs) # update parameters with user defined `simulator_extra_parameters` parameters
self.scaler = scaler
self.device = device
env = get_env(get_kwargs_simulator_scenario(benchmark.config))
z_base = torch.tensor(np.power(env.backend.lines_or_pu_to_kv, 2) / env.backend._grid.get_sn_mva()).to(self.device)
grid_model = env.backend._grid
self.base_volt = torch.tensor(self.params["base_volt"]).to(self.device)
bus_enable_flag = self.params["bus_enable_flag"]
self.bus_enable_flag = np.array(bus_enable_flag[0:236])!=0
self.bus_renumber = np.array(self.params["bus_renumber"])
Ybus_sparse_const = self.params["Ybus_sparse_const"]
self.topo_vect_unique = torch.tensor(self.params["topo_vect_unique"], dtype=torch.float32).to(self.device)
self.PQ_unique = torch.tensor(self.params["PQ_unique"], dtype=torch.bool).to(self.device)
self.PV_unique = torch.tensor(self.params["PV_unique"], dtype=torch.bool).to(self.device)
layers = self.params["layers"]
self.Ybus_sprase_const = []
for i in range(0, len(Ybus_sparse_const["indptr"])):
data = np.array(Ybus_sparse_const["data_real"][i]) + 1j * np.array(Ybus_sparse_const["data_imag"][i])
indices = np.array(Ybus_sparse_const["indices"][i])
indptr = np.array(Ybus_sparse_const["indptr"][i])
shape = Ybus_sparse_const["shape"][i]
self.Ybus_sprase_const.append(csr_matrix((data, indices, indptr), shape=shape))
self.line_params = get_line_params(grid_model, z_base[:173], self.device)
self.traf_params= get_traf_params(grid_model, z_base[173:], self.device)
self.line_topo_data = (torch.tensor(env.line_or_pos_topo_vect).to(self.device),\
torch.tensor(env.line_ex_pos_topo_vect).to(self.device),\
torch.tensor(env.line_or_to_subid).to(self.device),\
torch.tensor(env.line_ex_to_subid).to(self.device))
self.P_mis_max = torch.tensor([3000.0], device = self.device) # 3000.0 is a random number
self.Q_mis_max = torch.tensor([3000.0], device = self.device)
self.P_mis_mae = torch.tensor([3000.0], device = self.device) # 3000.0 is a random number
self.Q_mis_mae = torch.tensor([3000.0], device = self.device)
temp = 1.0 / np.sqrt(3.)
self.inv_sqrt_3 = torch.tensor(temp).to(device)
self.one = torch.tensor(1.0).to(device)
self.YBus_Base_flat_csr, self.YBus_Base_torch, self.YBus_imag_Base_torch,\
self.Ybus_imag_base_diag_torch, self.row_sum_Ybus_imag_base_torch = YBus_base_variables(self.Ybus_sprase_const, self.device)
model_PF = TorchPF(name = "TorchPF_Model",
n_RNN_iter = 25, # TODO change to 2, 10 and check, change to 40 , note the time
n_P_iter = 4,
n_Q_iter = 2
)
input_size, output_size = infer_input_output_size(benchmark.train_dataset)
model_theta = Model(input_size,
layers,
output_size)
## It is not used in this simple implementation
if scaler is not None:
self.scaler = scaler()
else:
self.scaler = None
self._model = None
super().__init__(model_PF)
self.model_PF = model_PF
self.model_theta = model_theta
self.build_model()
self.model_PF.to(self.device)
self.model_theta.to(self.device)
self.torch_get_line_vals_vmap = torch.vmap(torch_get_line_vals_sample, in_dims= (0,) * 6 + (None,) * 17, out_dims=(0,) * 6)
def build_model(self):
self.model_PF.build_model()
def train(self, train_dataset, val_dataset = None, **kwargs):
params = kwargs
in_data, target, train_loader = process_dataset(dataset = train_dataset,\
batch_size=params["train_batch_size"], training=True, shuffle=False)
train_losses = []
optimizer = optim.Adam(self.model_theta.parameters(), lr=params["lr"], weight_decay=5e-4)
loss_function = nn.MSELoss()
for epoch in range(params["epochs"]):
self.model_theta.train()
total_loss = 0
for batch in train_loader:
input_batch = in_data[batch, :].to(self.device)
target_batch = target[batch, :].to(self.device)
# reset the gradient
optimizer.zero_grad()
# predict using your model on the current batch of data
prediction = self.model_theta(input_batch)
# compute the loss between prediction and real target
loss = loss_function(prediction, target_batch)
# compute the gradient (backward pass of back propagation algorithm)
loss.backward()
# update the parameters of your model
optimizer.step()
total_loss += loss.item() * len(input_batch)
mean_loss = total_loss / sum(map(np.size, train_loader))
print(f"Train Epoch: {epoch} Avg_Loss: {mean_loss:.5f}")
train_losses.append(mean_loss)
self.predict(val_dataset, eval_batch_size=params["eval_batch_size"])
print("warm_up, done")
return train_losses
def validate(self, val_loader):
pass
#@line_profiler.profile
def predict(self, dataset, eval_batch_size=128, shuffle=False, **kwargs):
self.dataset = dataset
self.model_PF.eval()
self.model_theta.eval()
predictions_list = []
data, YBus_flat, Islanded_buses, data_loader =\
process_dataset(dataset, bus_enable_flag = self.bus_enable_flag, topo_vect_unique = self.topo_vect_unique,\
PQ_unique = self.PQ_unique, PV_unique = self.PV_unique, device = self.device, \
batch_size = eval_batch_size, training = False, shuffle = shuffle)
prod_p, prod_v, load_p, load_q, topo_vect,\
line_status, PQ_nodes, PV_nodes, SBus_124 = data
self.init_volt = torch.zeros([prod_p.shape[0], 237], dtype=torch.float32)
self.volt_236 = torch.zeros([prod_p.shape[0], 236], dtype=torch.complex64)
with torch.no_grad():
for batch in data_loader:
prod_p_batch = prod_p[batch, :].to(self.device)
prod_v_batch = prod_v[batch, :].to(self.device)
load_p_batch = load_p[batch, :].to(self.device)
load_q_batch = load_q[batch, :].to(self.device)
P_mis_max = self.P_mis_max
Q_mis_max = self.Q_mis_max
P_mis_mae = self.P_mis_mae
Q_mis_mae = self.Q_mis_mae
temp = prod_p_batch.shape[0] * 124
X0 = torch.zeros((temp,1), device = self.device)
W_k = torch.zeros((temp,1), device = self.device)
A_times_Wk = torch.zeros((temp,1), device = self.device)
Vtheta = torch.zeros((temp,1), device = self.device)
Vmag = torch.ones((temp,1), device = self.device) * 1.03
topo_vect_batch = topo_vect[batch, :]
line_status_batch = line_status[batch, :].to(self.device)
PQ_nodes_batch = PQ_nodes[batch, :].reshape(-1,1)
PV_nodes_batch = PV_nodes[batch, :].reshape(-1,1)
Islanded_buses_batch = Islanded_buses[batch, :].to(self.device).reshape(-1,1)
Vmag[Islanded_buses_batch] *= 0.0
SBus_batch = SBus_124[batch, :].to(self.device).reshape(-1,1) / 100
init_volt_batch = self.init_volt[batch, :].to(self.device)
volt_236_batch = self.volt_236[batch, :].to(self.device)
model_theta_input = torch.cat((prod_p_batch/100, prod_v_batch/100, load_p_batch/100, load_q_batch/100, topo_vect_batch, line_status_batch), 1)
model_theta_output = self.model_theta(model_theta_input)
Y_blk_diag, Y_imag_blk_diag, row_sum_Ybus_delta_imag, Ybus_imag_delta_diag = \
get_fast_Ybus_Ydelta_spdiag_imag(self.YBus_Base_flat_csr, YBus_flat[batch, :])
Y_blk_diag = Y_blk_diag.to(self.device)
Y_imag_blk_diag = Y_imag_blk_diag.to(self.device)
row_sum_Ybus_delta_imag = row_sum_Ybus_delta_imag.to(self.device)
Ybus_imag_delta_diag = Ybus_imag_delta_diag.to(self.device)
prediction, P_mis_norm, Q_mis_norm, P_mis_mae, Q_mis_mae, P_mis_max_scenario, Q_mis_max_scenario\
= self.model_PF(Y_blk_diag, Y_imag_blk_diag, row_sum_Ybus_delta_imag, SBus_batch, PQ_nodes_batch, PV_nodes_batch,\
Islanded_buses_batch, topo_vect_batch, line_status_batch, Ybus_imag_delta_diag, init_volt_batch,\
model_theta_output,\
self.YBus_Base_torch, self.YBus_imag_Base_torch, self.Ybus_imag_base_diag_torch,\
self.row_sum_Ybus_imag_base_torch, self.bus_renumber, self.line_topo_data,\
P_mis_max, Q_mis_max, P_mis_mae, Q_mis_mae, X0, W_k, A_times_Wk, Vmag, Vtheta)
volt_236_batch[:,np.where(self.bus_renumber>-1)[0]] = prediction.reshape(-1,124)
predictions = self.torch_get_line_vals_vmap(prod_p_batch, load_p_batch, torch.abs(volt_236_batch),torch.angle(volt_236_batch),topo_vect_batch,\
line_status_batch.long(), self.inv_sqrt_3, self.one, self.base_volt,\
*self.line_topo_data, *self.line_params, *self.traf_params)
predictions = torch.cat(predictions, dim=1)
predictions_list.append(predictions)
predictions = torch.cat(predictions_list, dim=0)
predictions = predictions.detach().cpu().numpy()
predictions = {"v_or": predictions[:, 0: 186], "v_ex":predictions[:, 186:372] ,"p_or": predictions[:, 372: 558], "p_ex": predictions[:, 558: 744],\
"a_or": predictions[:, 744: 930], "a_ex": predictions[:, 930: 1116]}
adjust_GC_CPU(prod_p.numpy(), load_p.numpy(), predictions["p_ex"], predictions["p_or"])
return predictions
#@line_profiler.profile
def process_dataset(dataset, bus_enable_flag = None, topo_vect_unique = None, PQ_unique = None, PV_unique = None, device = None,
batch_size: int=512, training: bool=False, shuffle: bool=False, normalize = None, dtype=torch.float32):
if training:
print("train")
train_dataset = LIPSDataset(dataset, device)
in_data, out_data = train_dataset.get_training_data()
samples = np.arange(dataset.size)
if batch_size > dataset.size:
batch_size = dataset.size
train_loader = np.array_split(samples, dataset.size // batch_size)
return in_data, out_data, train_loader
else:
inf_dataset = LIPSDataset(dataset, bus_enable_flag, topo_vect_unique, PQ_unique, PV_unique, None, device)
data = inf_dataset.data_variables()
YBus = inf_dataset.get_reduced_Ybus_flattened_BATCH_enabled_124_buses()
Islanded_buses = inf_dataset.get_bus_islanded_flag_BATCH_124()
if batch_size > dataset.size:
batch_size = dataset.size
samples = np.arange(dataset.size)
inf_loader = np.array_split(samples, dataset.size // batch_size)
return data, YBus, Islanded_buses, inf_loader
def infer_input_output_size(dataset):
input_size = dataset.env_data["_size_x"] + dataset.env_data["_size_tau"]
output_size = dataset.env_data["n_line"] * 2
return input_size, output_size
##########################################################################################################################
####################### Defining Initialization model
class LIPSDataset():
def __init__(self, dataset = None, bus_enable_flag = None, topo_vect_unique = None,\
PQ_unique = None, PV_unique = None, normalize = None, device = None):
self.dataset = dataset
self.device = device
self.bus_enable_flag = bus_enable_flag
self.topo_vect_unique = topo_vect_unique
self.PQ_unique = PQ_unique
self.PV_unique = PV_unique
self.normalize = normalize
def __len__(self):
return self.prod_p.shape[0]
#@line_profiler.profile
def get_training_data(self):
prod_p = self.dataset.data['prod_p'] / 100
prod_v = self.dataset.data['prod_v'] / 100
load_p = self.dataset.data['load_p'] / 100
load_q = self.dataset.data['load_q'] / 100
theta_ex = self.dataset.data['theta_ex']
theta_or = self.dataset.data['theta_or']
topo_vect = self.dataset.data['topo_vect']
line_status = self.dataset.data['line_status']
input_data = np.concatenate((prod_p, prod_v, load_p, load_q, topo_vect, line_status), axis=1)
output_data = np.concatenate((theta_or, theta_ex), axis=1)
return torch.from_numpy(input_data.astype(np.float32)), torch.from_numpy(output_data.astype(np.float32))
def data_variables(self):
self.prod_p = torch.tensor(self.dataset.data['prod_p'], dtype = torch.float32)
self.prod_v = torch.tensor(self.dataset.data['prod_v'] )
self.load_p = torch.tensor(self.dataset.data['load_p'])
self.load_q = torch.tensor(self.dataset.data['load_q'], dtype = torch.float32)
self.line_status = torch.tensor(self.dataset.data['line_status']).to(torch.long)
self.SBus_124 = torch.tensor(self.dataset.data['SBus'][:, self.bus_enable_flag].astype(np.complex64))
self.topo_vect = torch.tensor(self.dataset.data['topo_vect'], dtype=torch.float32).to(self.device)
def distance(x, y):
return torch.norm(x - y, p=1)
def distances_from_a_to_all_b(a):
return torch.vmap(lambda b: distance(a, b))(self.topo_vect_unique)
topo_vect_differences_from_uniq = torch.vmap(distances_from_a_to_all_b)(self.topo_vect)
closest_uniq_topo = torch.argmin(topo_vect_differences_from_uniq, dim=1)
self.PQ_nodes = self.PQ_unique[closest_uniq_topo][:, self.bus_enable_flag]
self.PV_nodes = self.PV_unique[closest_uniq_topo][:, self.bus_enable_flag]
return self.prod_p, self.prod_v, self.load_p, self.load_q, self.topo_vect,\
self.line_status, self.PQ_nodes, self.PV_nodes, self.SBus_124,
#@line_profiler.profile
def get_reduced_Ybus_flattened_BATCH_enabled_124_buses(self):
self.Ybus_flat = self.dataset.data['YBus'] / 100
bus_enable_flag_matrix_flattened = np.einsum('i,j->ij', self.bus_enable_flag, self.bus_enable_flag).flatten()
Ybus_Batch_reduced_124 = self.Ybus_flat[:,bus_enable_flag_matrix_flattened] # assume each row is a scenario in Ybus_batch
self.Ybus_Batch_reduced_124 = Ybus_Batch_reduced_124.tocsr()
return Ybus_Batch_reduced_124
#@line_profiler.profile
def get_bus_islanded_flag_BATCH_124(self):
Ybus_Batch_diag = get_diag_Ybus_flattened_BATCH_124_buses(self.Ybus_Batch_reduced_124)
bus_islanded_flag_batch_124 = (np.abs(Ybus_Batch_diag.toarray())==0)
return torch.tensor(bus_islanded_flag_batch_124)
class TorchFC(torch.nn.Module):
def __init__(self, in_size, fc_hc, out_size):
super().__init__()
self.fc1 = nn.Linear(in_size, fc_hc[0])
self.fc2 = nn.Linear(fc_hc[0], fc_hc[1])
self.fc3 = nn.Linear(fc_hc[1], fc_hc[2])
self.fc4 = nn.Linear(fc_hc[2], out_size)
def forward(self, x):
x = self.fc1(x)
x = F.relu(x)
x = self.fc2(x)
x = F.relu(x)
x = self.fc3(x)
x = self.fc4(x)
return x
class Model(torch.nn.Module):
def __init__(self, in_size, fc_hc, out_size):
super().__init__()
self.encoder = TorchFC(in_size, fc_hc, out_size)
def forward(self, x_dict):
return self.encoder(x_dict)
def YBus_base_variables(Ybus_sparse_list, device):
YBus_Base_flat = Ybus_sparse_list[0].reshape(1, -1)
YBus_Base_flat_csr = YBus_Base_flat.tocsr()
Y_pytg = pytg.utils.from_scipy_sparse_matrix(
YBus_Base_flat.reshape(124, 124).astype(np.complex64))
YBus_Base_torch = pytg.utils.to_torch_sparse_tensor(edge_index=Y_pytg[0], edge_attr=Y_pytg[1],
size=(124, 124), is_coalesced=True)
Y_imag_pytg = pytg.utils.from_scipy_sparse_matrix(
YBus_Base_flat.reshape(124, 124).imag.astype(np.float32))
YBus_imag_Base_torch = pytg.utils.to_torch_sparse_tensor(edge_index=Y_imag_pytg[0], edge_attr=Y_imag_pytg[1],
size=(124, 124), is_coalesced=True)
row_sum_Ybus_imag_base = np.array(
YBus_Base_flat.reshape(124, 124).sum(1).imag, dtype=np.float32)
row_sum_Ybus_imag_base_torch = torch.tensor(row_sum_Ybus_imag_base)
Ybus_imag_base_diag = YBus_Base_flat.reshape(
124, 124).diagonal(0).reshape(-1, 1).imag.astype(np.float32)
Ybus_imag_base_diag_torch = torch.tensor(Ybus_imag_base_diag)
YBus_Base_torch = YBus_Base_torch.to(device).to_dense()
YBus_imag_Base_torch = YBus_imag_Base_torch.to(device).to_dense()
Ybus_imag_base_diag_torch = Ybus_imag_base_diag_torch.to(device)
row_sum_Ybus_imag_base_torch = row_sum_Ybus_imag_base_torch.to(device)
return YBus_Base_flat_csr, YBus_Base_torch, YBus_imag_Base_torch, Ybus_imag_base_diag_torch, row_sum_Ybus_imag_base_torch
# @line_profiler.profile
def get_J11_J22_diags(Ybus_imag_base_diag, Ybus_imag_delta_diag, row_sum_Ybus_imag_base, row_sum_Ybus_delta_imag,
J11_enable_flag, J22_enable_flag):
V = 1.03
batch_size = len(Ybus_imag_delta_diag)//124
J11_diag = Ybus_imag_delta_diag - row_sum_Ybus_delta_imag + \
(Ybus_imag_base_diag-row_sum_Ybus_imag_base).repeat(batch_size, 1)
J11_diag *= -V*V
# J11_diag = J11_diag*J11_enable_flag + (1-J11_enable_flag) = (J11_diag-1)*J11_enable_flag + 1
J11_diag -= 1
J11_diag *= J11_enable_flag
J11_diag += 1
J22_diag = Ybus_imag_delta_diag + row_sum_Ybus_delta_imag + \
(Ybus_imag_base_diag+row_sum_Ybus_imag_base).repeat(batch_size, 1)
J22_diag *= -V
# J22_diag = J22_diag*J22_enable_flag + (1-J22_enable_flag) = (J22_diag-1)*J22_enable_flag + 1
J22_diag -= 1
J22_diag *= J22_enable_flag
J22_diag += 1
return J11_diag, J22_diag
# @line_profiler.profile
def get_fast_Ybus_Ydelta_spdiag_imag(YBus_base_flat_csr, batch_sparse_flat):
batch_size, num_cols = batch_sparse_flat.shape
YBus_base_flat_repeat_indptr = np.arange(batch_size+1)*476
YBus_base_flat_repeat_indices = np.repeat(
[YBus_base_flat_csr.indices], batch_size, axis=0).ravel()
YBus_base_flat_repeat_data = np.repeat(
[YBus_base_flat_csr.data], batch_size, axis=0).ravel()
# ------------------- MOVE code until above to neural network model intiialization ? if batch_size is known.. --------------
minus_res_max_nnz = 100*batch_size # 100 is based on analysis
idx_dtype = batch_sparse_flat._get_index_dtype((batch_sparse_flat.indptr, batch_sparse_flat.indices,
YBus_base_flat_repeat_indptr, YBus_base_flat_repeat_indices),
maxval=minus_res_max_nnz)
minus_res_indptr = np.empty(
batch_sparse_flat.indptr.shape, dtype=idx_dtype)
minus_res_indices = np.empty(minus_res_max_nnz, dtype=idx_dtype)
minus_res_data = np.empty(
minus_res_max_nnz, dtype=batch_sparse_flat.data.dtype)
# https://github.com/scipy/scipy/blob/afeab37e1a02a0cf09d9507fddab05795eea14fa/scipy/sparse/_compressed.py#L1367
csr_minus_csr(batch_size, num_cols,
batch_sparse_flat.indptr,
batch_sparse_flat.indices,
batch_sparse_flat.data,
YBus_base_flat_repeat_indptr,
YBus_base_flat_repeat_indices,
YBus_base_flat_repeat_data,
minus_res_indptr, minus_res_indices, minus_res_data)
minus_res_indices = minus_res_indices[:minus_res_indptr[-1]]
minus_res_data = minus_res_data[:minus_res_indptr[-1]]
n_matrix = np.sqrt(batch_sparse_flat.shape[1]).astype(np.int32)
# nnz = batch_sparse_flat.data.size
minus_res_data = minus_res_data.astype(np.complex64)
# get_3D_indices_from_batch_sparse_flat(batch_vec, row_vec, col_vec, batch_sparse_flat, n=n_matrix)
row_vec, col_vec = np.divmod(minus_res_indices, n_matrix)
batch_vec = np.repeat(np.arange(batch_size), np.diff(minus_res_indptr))
Ybus_delta_scipy_batch_sparse_blk_diag = sp.coo_array((minus_res_data, (row_vec + batch_vec * n_matrix, col_vec + batch_vec * n_matrix)),
shape=(batch_size*n_matrix, batch_size*n_matrix))
Ybus_delta_scipy_batch_sparse_blk_diag.eliminate_zeros()
# TODO - GPU will be better
# row_sum_Ybus_delta = np.zeros((batch_size*n_matrix,1), dtype=np.complex128) # not really allocated
# row_sum_Ybus_delta = row_sum_Ybus_delta*0 # will take some time and memory here..
# np.add.at(row_sum_Ybus_delta[:,0],row_vec+batch_vec*n_matrix,minus_res_data) # TODO - GPU - slow becase no multi threading.. use GPUs??
# this is slow.. not sure why
row_sum_Ybus_delta_v2 = np.ones((batch_size*n_matrix, 1), dtype=np.float32)
row_sum_Ybus_delta_v2_imag = Ybus_delta_scipy_batch_sparse_blk_diag.imag @ row_sum_Ybus_delta_v2
Ybus_imag_delta_diag = Ybus_delta_scipy_batch_sparse_blk_diag.diagonal(
0).reshape(-1, 1).imag
Y_pytg = pytg.utils.from_scipy_sparse_matrix(
Ybus_delta_scipy_batch_sparse_blk_diag)
Y_torch_batch_sparse_blk_diag = pytg.utils.to_torch_sparse_tensor(edge_index=Y_pytg[0], edge_attr=Y_pytg[1],
size=(
batch_size*n_matrix, batch_size*n_matrix),
is_coalesced=True)
Y_pytg = pytg.utils.from_scipy_sparse_matrix(
Ybus_delta_scipy_batch_sparse_blk_diag.imag)
Y_imag_torch_batch_sparse_blk_diag = pytg.utils.to_torch_sparse_tensor(edge_index=Y_pytg[0], edge_attr=Y_pytg[1],
size=(
batch_size*n_matrix, batch_size*n_matrix),
is_coalesced=True)
# torch_batch_sparse_blk_diag = torch.sparse_coo_tensor(indices=torch.tensor(np.array([row_vec+batch_vec*n_matrix, col_vec+batch_vec*n_matrix])),
# values=data_vec,
# size=(batch_size*n_matrix, batch_size*n_matrix))
return Y_torch_batch_sparse_blk_diag, Y_imag_torch_batch_sparse_blk_diag, torch.tensor(row_sum_Ybus_delta_v2_imag), torch.tensor(Ybus_imag_delta_diag)
def get_diag_Ybus_flattened_BATCH_124_buses(Ybus_Batch_reduced_124):
Ybus_diag_index_flattened_124 = np.where(np.eye(124, 124).flatten())[0]
Ybus_Batch_diag = Ybus_Batch_reduced_124[:, Ybus_diag_index_flattened_124]
return Ybus_Batch_diag
class TorchFC(torch.nn.Module):
def __init__(self, in_size, fc_hc, out_size):
super().__init__()
self.fc1 = nn.Linear(in_size, fc_hc[0])
self.fc2 = nn.Linear(fc_hc[0], fc_hc[1])
self.fc3 = nn.Linear(fc_hc[1], fc_hc[2])
self.fc4 = nn.Linear(fc_hc[2], out_size)
def forward(self, x):
x = self.fc1(x)
x = F.relu(x)
x = self.fc2(x)
x = F.relu(x)
x = self.fc3(x)
x = self.fc4(x)
return x
class Model(torch.nn.Module):
def __init__(self, in_size, hc_size, out_size):
super().__init__()
self.encoder = TorchFC(in_size, hc_size, out_size)
def forward(self, x_dict):
return self.encoder(x_dict)
def is_positive_semidefinite(matrix):
# Check if the matrix is square
if matrix.shape[0] != matrix.shape[1]:
return False
# Compute eigenvalues
eigenvalues = np.linalg.eigvals(matrix)
# Check if all eigenvalues are non-negative
return np.all(eigenvalues >= 0)
def is_positive_symmetric_semidefinite(matrix):
# Check if the matrix is square
if matrix.shape[0] != matrix.shape[1]:
return False
# Check if the matrix is symmetric
if not np.allclose(matrix, matrix.T):
return False
# Compute eigenvalues
eigenvalues = np.linalg.eigvals(matrix)
# Check if all eigenvalues are non-negative
return np.all(eigenvalues >= 0)
def get_3D_indices_from_batch_sparse_flat_test_MiniBATCH_Delta_Y(YBus_base_flat, batch_sparse_flat, Sample_select_flag):
Delta_Y_flat = batch_sparse_flat[Sample_select_flag] - \
sp.coo_array(np.ones((len(Sample_select_flag), 1)))@YBus_base_flat
Delta_Y_flat.eliminate_zeros()
if not (Delta_Y_flat.has_sorted_indices): # VERY IMPORTANT STEP..
Delta_Y_flat.sort_indices()
return Delta_Y_flat
def get_3D_indices_from_batch_sparse_flat_test_MiniBATCH(batch_sparse_flat, Sample_select_flag):
return get_3D_indices_from_batch_sparse_flat_test_v2(batch_sparse_flat[Sample_select_flag])
# @line_profiler.profile
def get_3D_indices_from_batch_sparse_flat_test(batch_sparse_flat, sparse_output_format="torch_blk_diag"):
if not (batch_sparse_flat.has_sorted_indices): # VERY IMPORTANT STEP..
batch_sparse_flat.sort_indices()
batch_size = batch_sparse_flat.shape[0]
n_matrix = np.sqrt(batch_sparse_flat.shape[1]).astype(np.int32)
nnz = batch_sparse_flat.data.size
data_vec = batch_sparse_flat.data.astype(np.complex64)
# get_3D_indices_from_batch_sparse_flat(batch_vec, row_vec, col_vec, batch_sparse_flat, n=n_matrix)
indptr = batch_sparse_flat.indptr
indices = batch_sparse_flat.indices
row_vec, col_vec = np.divmod(indices, n_matrix)
batch_vec = np.repeat(np.arange(batch_size), np.diff(indptr))
if sparse_output_format == "torch_3D":
torch_batch_sparse_3D = torch.sparse_coo_tensor(indices=torch.tensor(np.array([batch_vec, row_vec, col_vec])),
values=data_vec,
size=(batch_size, n_matrix, n_matrix))
return torch_batch_sparse_3D
if sparse_output_format == "torch_blk_diag":
torch_batch_sparse_blk_diag = torch.sparse_coo_tensor(indices=torch.tensor(np.array([row_vec+batch_vec*n_matrix, col_vec+batch_vec*n_matrix])),
values=data_vec,
size=(batch_size*n_matrix, batch_size*n_matrix))
return torch_batch_sparse_blk_diag
if sparse_output_format == "pytg":
scipy_batch_sparse_blk_diag = sp.coo_array((data_vec, (row_vec+batch_vec*n_matrix, col_vec+batch_vec*n_matrix)),
shape=(batch_size*n_matrix, batch_size*n_matrix))
return pytg.utils.from_scipy_sparse_matrix(scipy_batch_sparse_blk_diag)
if sparse_output_format == "scipy":
scipy_batch_sparse_blk_diag = sp.coo_array((data_vec, (row_vec+batch_vec*n_matrix, col_vec+batch_vec*n_matrix)),
shape=(batch_size*n_matrix, batch_size*n_matrix))
return scipy_batch_sparse_blk_diag
# @line_profiler.profile
# @torch.jit.script
def get_3D_indices_from_batch_sparse_flat_test_v2(data_vec, indptr, indices, batch_vector, batch_size, n_matrix):
row_vec = torch.div(indices, n_matrix, rounding_mode='floor')
col_vec = torch.remainder(indices, n_matrix)
B = indptr[1:] - indptr[:-1]
batch_vec = batch_vector.repeat_interleave(B)
indices = torch.vstack(
(row_vec+batch_vec*n_matrix, col_vec+batch_vec*n_matrix))
torch_batch_sparse_blk_diag = torch.sparse_coo_tensor(indices=indices, values=data_vec, size=[batch_size*n_matrix, batch_size*n_matrix], dtype=torch.complex64,
device=torch.device('cuda:0'), is_coalesced=True)
return torch_batch_sparse_blk_diag
def get_Jac_Neighbour_Diag_from_flattened_Ybus_MiniBATCH(batch_sparse_flat_Ybus,
PQ_flags,
PV_flags,
Islanded_bus_flag,
Sample_select_flag):
return get_Jac_Neighbour_Diag_from_flattend_Ybus_BATCH_v2(batch_sparse_flat_Ybus[Sample_select_flag],
PQ_flags,
PV_flags,
Islanded_bus_flag)
@nb.njit()
def zero_out_data_vec_TRUE_buses_SINGLE(row_vec, col_vec, data_vec, row_col_to_zero_flag_vector):
row_flag = row_col_to_zero_flag_vector[row_vec]
col_flag = row_col_to_zero_flag_vector[col_vec]
data_vec[np.logical_or(row_flag, col_flag)] = 0.0
# diag_indx = np.where(row_vec == col_vec)[0]
# data_vec[row_vec == col_vec] += 1.0
# @line_profiler.profile
def get_Ybus_imag_flattened_vectors(batch_sparse_flat):
if not (batch_sparse_flat.has_sorted_indices): # VERY IMPORTANT STEP..
batch_sparse_flat.sort_indices()
batch_size = batch_sparse_flat.shape[0]
n_matrix = np.sqrt(batch_sparse_flat.shape[1]).astype(np.int32)
nnz = batch_sparse_flat.data.size
indptr = batch_sparse_flat.indptr
indices = batch_sparse_flat.indices
batch_vec = np.zeros(nnz, dtype=np.int32)
row_vec = np.zeros(nnz, dtype=np.int32)
col_vec = np.zeros(nnz, dtype=np.int32)
data_vec = batch_sparse_flat.imag.data.astype(np.float32)
row_vec, col_vec = np.divmod(indices, n_matrix)
batch_vec = np.repeat(np.arange(batch_size), np.diff(indptr))
return batch_vec, row_vec, col_vec, data_vec, indptr, n_matrix, batch_size
@nb.njit()
def get_batch_sum_row_sparse_matrices(row_vec, data_vec, indptr, n_matrix, batch_size):
row_sum_batch = np.zeros((batch_size, n_matrix))
for k in nb.prange(batch_size):
row_sum_batch[k, :] = np.bincount(
row_vec[indptr[k]: indptr[k + 1]], weights=data_vec[indptr[k]: indptr[k + 1]], minlength=n_matrix)
return row_sum_batch
@nb.njit()
def zero_out_data_vec_TRUE_buses_BATCH(row_vec, col_vec, data_vec, row_col_to_zero_flag_vector, indptr):
for k in nb.prange(row_col_to_zero_flag_vector.shape[0]):
zero_out_data_vec_TRUE_buses_SINGLE(row_vec[indptr[k]:indptr[k + 1]],
col_vec[indptr[k]:indptr[k + 1]],
data_vec[indptr[k]:indptr[k + 1]],
row_col_to_zero_flag_vector[k])
@nb.njit()
def extract_diag_into_vec_and_zero_diag_SINGLE(row_vec, col_vec, data_vec, diag_vec):
diag_indx = np.where(row_vec == col_vec)[0]
diag_vec[row_vec[diag_indx]] = data_vec[diag_indx].copy()
data_vec[diag_indx] *= 0
@nb.njit()
def extract_diag_into_vec_and_zero_diag_BATCH(row_vec, col_vec, data_vec, diag_vec, indptr):
for k in nb.prange(diag_vec.shape[0]):
extract_diag_into_vec_and_zero_diag_SINGLE(row_vec[indptr[k]:indptr[k + 1]],
col_vec[indptr[k]:indptr[k + 1]],
data_vec[indptr[k]:indptr[k + 1]],
diag_vec[k])
@nb.njit()
# @line_profiler.profile
def custom_extract_diag_into_vec_and_zero_diag_SINGLE(row_vec, col_vec, data_vec, diag_vec, row_sum, n_matrix):
row_sum[:] = np.bincount(row_vec, weights=data_vec, minlength=n_matrix)
diag_indx = np.where(row_vec == col_vec)[0]
diag_vec[row_vec[diag_indx]] = data_vec[diag_indx].copy()
data_vec[diag_indx] *= 0
# @nb.njit()
def custom_extract_diag_into_vec_and_zero_diag_BATCH(row_vec, col_vec, data_vec, diag_vec, row_sum, indptr, batch_size, n_matrix):
for k in nb.prange(batch_size):
custom_extract_diag_into_vec_and_zero_diag_SINGLE(row_vec[indptr[k]:indptr[k + 1]],
col_vec[indptr[k]:indptr[k + 1]],
data_vec[indptr[k]:indptr[k + 1]],
diag_vec[k],
row_sum[k],
n_matrix)
def diag_vec_replace_by_1_TRUE_buses_BATCH_SINGLE(diag_vec, row_col_to_zero_flag_vector):
# THIS IS THE SIMPLE # -1 is there as we are estimating the negative of the
diag_vec[row_col_to_zero_flag_vector] = 1.0
def get_Jac_Neighbour_Diag_from_flattend_Ybus_BATCH(batch_sparse_flat_Ybus,
PQ_flags,
PV_flags,
Islanded_bus_flag, sparse_output_format):
batch_vec, row_vec, col_vec, data_vec, indptr, n_matrix, batch_size = get_Ybus_imag_flattened_vectors(
batch_sparse_flat_Ybus)
J11_D_diag_vec = np.zeros((batch_size, n_matrix))
J22_D_diag_vec = np.zeros((batch_size, n_matrix))
row_sum_batch = get_batch_sum_row_sparse_matrices(
row_vec, data_vec, indptr, n_matrix, batch_size)
extract_diag_into_vec_and_zero_diag_BATCH(
row_vec, col_vec, data_vec, J11_D_diag_vec, indptr)
J22_D_diag_vec = J11_D_diag_vec.copy()
J11_D_diag_vec -= row_sum_batch
J22_D_diag_vec += row_sum_batch
# negative sign is important
J11_N_data_vec = data_vec * -1.03 * 1.03
J22_N_data_vec = data_vec * -1.03
J11_D_diag_vec *= -1.03 * 1.03
J22_D_diag_vec *= -1.03
# Islanded buses
zero_out_data_vec_TRUE_buses_BATCH(
row_vec, col_vec, J11_N_data_vec, Islanded_bus_flag, indptr)
zero_out_data_vec_TRUE_buses_BATCH(
row_vec, col_vec, J22_N_data_vec, Islanded_bus_flag, indptr)
J11_D_diag_vec[Islanded_bus_flag] = 1.0
J22_D_diag_vec[Islanded_bus_flag] = 1.0
# slack bus in J11
zero_out_data_vec_TRUE_buses_BATCH(row_vec, col_vec, J11_N_data_vec,
np.logical_not(np.logical_or(PQ_flags, PV_flags)), indptr)
diag_vec_replace_by_1_TRUE_buses_BATCH_SINGLE(
J11_D_diag_vec, np.logical_not(np.logical_or(PQ_flags, PV_flags)))
# slack and PV buses in J22
zero_out_data_vec_TRUE_buses_BATCH(row_vec, col_vec, J22_N_data_vec,
np.logical_not(PQ_flags), indptr)
diag_vec_replace_by_1_TRUE_buses_BATCH_SINGLE(
J22_D_diag_vec, np.logical_not(PQ_flags))
if sparse_output_format == "torch_3D":
# constuct sparse batched matrices
J11_N_torch_sparse_3D = torch.sparse_coo_tensor(indices=torch.tensor(np.array([batch_vec, row_vec, col_vec])),
values=J11_N_data_vec,
size=(batch_size, n_matrix, n_matrix))
J22_N_torch_sparse_3D = torch.sparse_coo_tensor(indices=torch.tensor(np.array([batch_vec, row_vec, col_vec])),
values=J22_N_data_vec,
size=(batch_size, n_matrix, n_matrix))
return J11_N_torch_sparse_3D, J22_N_torch_sparse_3D, J11_D_diag_vec, J22_D_diag_vec
# construct sparse blk diag
if sparse_output_format == "torch_blk_diag":
J11_N_torch_sparse = torch.sparse_coo_tensor(indices=torch.tensor(np.array([row_vec+batch_vec*n_matrix, col_vec+batch_vec*n_matrix])),
values=J11_N_data_vec,
size=(batch_size*n_matrix, batch_size*n_matrix)).to_sparse_csr()
# J11_N_torch_sparse = J11_N_torch_sparse.coa
J22_N_torch_sparse = torch.sparse_coo_tensor(indices=torch.tensor(np.array([row_vec+batch_vec*n_matrix, col_vec+batch_vec*n_matrix])),
values=J22_N_data_vec,
size=(batch_size*n_matrix, batch_size*n_matrix)).to_sparse_csr()
return J11_N_torch_sparse, J22_N_torch_sparse, J11_D_diag_vec, J22_D_diag_vec
if sparse_output_format == "pytg":
J11_N_scipy_sparse = sp.coo_array((J11_N_data_vec, (row_vec+batch_vec*n_matrix, col_vec+batch_vec*n_matrix)),
shape=(batch_size*n_matrix, batch_size*n_matrix), dtype=np.float32)
J22_N_scipy_sparse = sp.coo_array((J22_N_data_vec, (row_vec+batch_vec*n_matrix, col_vec+batch_vec*n_matrix)),
shape=(batch_size*n_matrix, batch_size*n_matrix), dtype=np.float32)
return pytg.utils.from_scipy_sparse_matrix(J11_N_scipy_sparse), pytg.utils.from_scipy_sparse_matrix(J22_N_scipy_sparse), \
J11_D_diag_vec, J22_D_diag_vec
if sparse_output_format == "scipy":
J11_N_scipy_sparse = sp.coo_array((J11_N_data_vec, (row_vec+batch_vec*n_matrix, col_vec+batch_vec*n_matrix)),
shape=(batch_size*n_matrix, batch_size*n_matrix), dtype=np.float32)
J22_N_scipy_sparse = sp.coo_array((J22_N_data_vec, (row_vec+batch_vec*n_matrix, col_vec+batch_vec*n_matrix)),
shape=(batch_size*n_matrix, batch_size*n_matrix), dtype=np.float32)
return J11_N_scipy_sparse, J22_N_scipy_sparse, J11_D_diag_vec, J22_D_diag_vec
# @line_profiler.profile
def get_Jac_Neighbour_Diag_from_flattend_Ybus_BATCH_v2(batch_sparse_flat_Ybus,
PQ_flags,
PV_flags,
Islanded_bus_flag):
batch_vec, row_vec, col_vec, data_vec, indptr, n_matrix, batch_size = get_Ybus_imag_flattened_vectors(
batch_sparse_flat_Ybus)
J11_D_diag_vec = np.zeros((batch_size, n_matrix))
J22_D_diag_vec = np.zeros((batch_size, n_matrix))
row_sum_batch = get_batch_sum_row_sparse_matrices(
row_vec, data_vec, indptr, n_matrix, batch_size)
extract_diag_into_vec_and_zero_diag_BATCH(
row_vec, col_vec, data_vec, J11_D_diag_vec, indptr)
J22_D_diag_vec = J11_D_diag_vec.copy()
J11_D_diag_vec -= row_sum_batch
J22_D_diag_vec += row_sum_batch
# negative sign is important
J11_N_data_vec = data_vec * -1.03 * 1.03
J22_N_data_vec = data_vec * -1.03
J11_D_diag_vec *= -1.03 * 1.03
J22_D_diag_vec *= -1.03
# Islanded buses
zero_out_data_vec_TRUE_buses_BATCH(
row_vec, col_vec, J11_N_data_vec, Islanded_bus_flag, indptr)
zero_out_data_vec_TRUE_buses_BATCH(
row_vec, col_vec, J22_N_data_vec, Islanded_bus_flag, indptr)
J11_D_diag_vec[Islanded_bus_flag] = 1.0
J22_D_diag_vec[Islanded_bus_flag] = 1.0
# slack bus in J11
zero_out_data_vec_TRUE_buses_BATCH(row_vec, col_vec, J11_N_data_vec,
np.logical_not(np.logical_or(PQ_flags, PV_flags)), indptr)
diag_vec_replace_by_1_TRUE_buses_BATCH_SINGLE(
J11_D_diag_vec, np.logical_not(np.logical_or(PQ_flags, PV_flags)))
# slack and PV buses in J22
zero_out_data_vec_TRUE_buses_BATCH(row_vec, col_vec, J22_N_data_vec,
np.logical_not(PQ_flags), indptr)
diag_vec_replace_by_1_TRUE_buses_BATCH_SINGLE(
J22_D_diag_vec, np.logical_not(PQ_flags))
"""
J11_N_scipy_sparse = sp.coo_array((J11_N_data_vec, (row_vec+batch_vec*n_matrix, col_vec+batch_vec*n_matrix)),
shape=(batch_size*n_matrix, batch_size*n_matrix), dtype=np.float32)
J22_N_scipy_sparse = sp.coo_array((J22_N_data_vec, (row_vec+batch_vec*n_matrix, col_vec+batch_vec*n_matrix)),
shape=(batch_size*n_matrix, batch_size*n_matrix), dtype=np.float32)
J11_N_scipy_sparse.eliminate_zeros()
J22_N_scipy_sparse.eliminate_zeros()
# construct sparse blk diag
J_temp = pytg.utils.from_scipy_sparse_matrix(J11_N_scipy_sparse)
J11_N_torch_sparse = pytg.utils.to_torch_sparse_tensor(edge_index=J_temp[0], edge_attr=J_temp[1],
size=(batch_size*n_matrix, batch_size*n_matrix),
is_coalesced=True)
# TODO - coalesce to increase speed ??
J_temp = pytg.utils.from_scipy_sparse_matrix(J22_N_scipy_sparse)
J22_N_torch_sparse = pytg.utils.to_torch_sparse_tensor(edge_index=J_temp[0], edge_attr=J_temp[1],
size=(batch_size*n_matrix, batch_size*n_matrix),
is_coalesced=True)
"""
J11_N_torch_sparse = 0
J22_N_torch_sparse = 0
return J11_N_torch_sparse, J22_N_torch_sparse, J11_D_diag_vec, J22_D_diag_vec
def solve_jacobi_weighted_for_powerflow(
# device: torch.device,
Off, Diag_inv, b, n=torch.tensor(25)):
device = 'cuda:0'
x = torch.zeros_like(b, device=device)
omega = 0.9
for _ in torch.arange(n):
x = omega * Diag_inv * (b - Off @ x) + (1 - omega) * x
return x
@torch.jit.script
# @line_profiler.profile
def get_PQ_mismatch_Delta_Y_v2(YBus_Base, Delta_YBus_blk_diag, SBus_batch_124, J11_enable_flag, J22_enable_flag,
Vtheta, Vmag):
VBus = torch.complex(torch.cos(Vtheta) * Vmag, torch.sin(Vtheta) * Vmag)
# IBus = Delta_YBus_blk_diag @ VBus + (VBus.view(-1,124)@YBus_Base).view(-1,1)
# IBus = Delta_YBus_blk_diag @ VBus
IBus = F.linear(Delta_YBus_blk_diag, VBus.view(1, -1))
temp1 = VBus.view(-1, 124)@YBus_Base
temp2 = temp1.reshape(-1, 1)
IBus += temp2 # TODO - remove reshape as it could be slow...
# SBus_calc = VBus*torch.conj(IBus)
SBus_mis = VBus * torch.conj(IBus) - SBus_batch_124
# SBus_mis[New_Islanded_buses_124] = 0.0
P_mis = SBus_mis.real
Q_mis = SBus_mis.imag
P_mis *= J11_enable_flag
Q_mis *= J22_enable_flag
return P_mis, Q_mis
# @line_profiler.profile
@torch.jit.script
# in-use
def get_Jac_times_vector(Y_base, Y_delta, J_flag_Y_base_row_sum, J_flag_Y_delta_row_sum, enable_flag, disable_flag, V_scale, en_scale, J11_J22_flag, x):
res_0 = disable_flag * x
res_1 = en_scale * x
res_1_0 = J_flag_Y_delta_row_sum * res_1
# res_1_1 = F.linear(Y_delta, res_1.view(1, -1))
res_1_1 = torch.sparse.mm(Y_delta, res_1)
temp1 = res_1.reshape(-1, 124)
temp2 = torch.matmul(temp1, Y_base)
res_1_2 = temp2.reshape(-1, 1)
res_1_3 = (J_flag_Y_base_row_sum*res_1.reshape(-1, 124)).reshape(-1, 1)