-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpower_system_simulator.py
3501 lines (2913 loc) · 141 KB
/
power_system_simulator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import numpy as np
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import pyqtgraph as pg
from scipy import integrate
import pandas as pd
from PyQt5.QtWidgets import QGraphicsScene, QGraphicsView, QToolBar, QAction
from PyQt5.QtCore import Qt, QPointF
from PyQt5.QtGui import QPen, QBrush, QColor, QPainter
import json
from PyQt5.QtWidgets import QDialog, QVBoxLayout, QFormLayout, QDialogButtonBox, QMenu
from PyQt5.QtWidgets import QToolBar, QSpinBox, QLabel
from numpy.linalg import inv
from cmath import rect, polar
import networkx as nx
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from datetime import datetime
from PyQt5.QtWidgets import QShortcut, QInputDialog, QTreeWidget, QTreeWidgetItem
from PyQt5.QtGui import QKeySequence
class GlassmorphicStyle:
@staticmethod
def apply(widget):
widget.setStyleSheet("""
QMainWindow {
background: qlineargradient(
x1: 0, y1: 0, x2: 1, y2: 1,
stop: 0 rgba(20, 20, 40, 0.95),
stop: 1 rgba(40, 40, 80, 0.95)
);
}
QWidget {
background-color: rgba(255, 255, 255, 0.08);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 15px;
color: white;
}
QPushButton {
background: qlineargradient(
x1: 0, y1: 0, x2: 1, y2: 1,
stop: 0 rgba(255, 255, 255, 0.1),
stop: 1 rgba(255, 255, 255, 0.05)
);
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 10px;
padding: 8px 20px;
color: white;
font-weight: bold;
}
QPushButton:hover {
background: qlineargradient(
x1: 0, y1: 0, x2: 1, y2: 1,
stop: 0 rgba(255, 255, 255, 0.2),
stop: 1 rgba(255, 255, 255, 0.1)
);
border: 1px solid rgba(255, 255, 255, 0.3);
}
QPushButton:pressed {
background-color: rgba(255, 255, 255, 0.15);
}
QLineEdit, QSpinBox, QDoubleSpinBox {
background-color: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 8px;
padding: 8px;
color: white;
selection-background-color: rgba(255, 255, 255, 0.2);
}
QComboBox {
background-color: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 8px;
padding: 8px;
color: white;
}
QComboBox::drop-down {
border: none;
width: 20px;
}
QGroupBox {
background: qlineargradient(
x1: 0, y1: 0, x2: 1, y2: 1,
stop: 0 rgba(255, 255, 255, 0.08),
stop: 1 rgba(255, 255, 255, 0.05)
);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 12px;
margin-top: 1em;
padding: 15px;
font-weight: bold;
}
QGroupBox::title {
subcontrol-origin: margin;
subcontrol-position: top center;
padding: 0 10px;
color: rgba(255, 255, 255, 0.8);
background-color: rgba(40, 40, 80, 0.95);
}
QTabWidget::pane {
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 12px;
background-color: rgba(40, 40, 80, 0.95);
}
QTabBar::tab {
background: qlineargradient(
x1: 0, y1: 0, x2: 1, y2: 1,
stop: 0 rgba(255, 255, 255, 0.05),
stop: 1 rgba(255, 255, 255, 0.02)
);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 8px;
padding: 8px 15px;
margin: 2px;
color: rgba(255, 255, 255, 0.7);
}
QTabBar::tab:selected {
background: qlineargradient(
x1: 0, y1: 0, x2: 1, y2: 1,
stop: 0 rgba(255, 255, 255, 0.1),
stop: 1 rgba(255, 255, 255, 0.05)
);
color: white;
font-weight: bold;
}
QGraphicsView {
background: transparent;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 12px;
}
QTreeWidget {
background-color: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 12px;
padding: 5px;
}
QTreeWidget::item {
padding: 5px;
border-radius: 6px;
}
QTreeWidget::item:selected {
background-color: rgba(255, 255, 255, 0.1);
}
QTextEdit {
background-color: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 12px;
padding: 10px;
}
QToolBar {
background: qlineargradient(
x1: 0, y1: 0, x2: 1, y2: 1,
stop: 0 rgba(255, 255, 255, 0.05),
stop: 1 rgba(255, 255, 255, 0.02)
);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 12px;
spacing: 5px;
padding: 5px;
}
QToolButton {
background-color: transparent;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 8px;
padding: 5px;
}
QToolButton:hover {
background-color: rgba(255, 255, 255, 0.1);
}
QScrollBar:vertical {
background: rgba(255, 255, 255, 0.05);
width: 10px;
border-radius: 5px;
}
QScrollBar::handle:vertical {
background: rgba(255, 255, 255, 0.2);
border-radius: 5px;
min-height: 20px;
}
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
height: 0px;
}
QSlider::groove:horizontal {
border: 1px solid rgba(255, 255, 255, 0.1);
height: 4px;
background: rgba(255, 255, 255, 0.1);
border-radius: 2px;
}
QSlider::handle:horizontal {
background: qlineargradient(
x1: 0, y1: 0, x2: 1, y2: 1,
stop: 0 rgba(255, 255, 255, 0.8),
stop: 1 rgba(255, 255, 255, 0.6)
);
border: 1px solid rgba(255, 255, 255, 0.3);
width: 16px;
height: 16px;
border-radius: 8px;
margin: -6px 0;
}
QMenuBar {
background: transparent;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
QMenuBar::item {
background: transparent;
padding: 8px 12px;
border-radius: 6px;
}
QMenuBar::item:selected {
background: rgba(255, 255, 255, 0.1);
}
QStatusBar {
background: qlineargradient(
x1: 0, y1: 0, x2: 1, y2: 1,
stop: 0 rgba(255, 255, 255, 0.05),
stop: 1 rgba(255, 255, 255, 0.02)
);
border-top: 1px solid rgba(255, 255, 255, 0.1);
color: rgba(255, 255, 255, 0.7);
}
""")
class PowerComponent:
BUS = "bus"
GENERATOR = "generator"
LOAD = "load"
TRANSFORMER = "transformer"
LINE = "line"
CAPACITOR = "capacitor"
REACTOR = "reactor"
SWITCH = "switch"
BREAKER = "breaker"
MEASUREMENT = "measurement"
MOTOR = "motor"
SOLAR = "solar"
WIND = "wind"
BATTERY = "battery"
HVDC = "hvdc"
class NodeNumbering:
def __init__(self):
self.current_number = 1
self.node_map = {} # Maps components to node numbers
def get_next_number(self):
num = self.current_number
self.current_number += 1
return num
def reset(self):
self.current_number = 1
self.node_map.clear()
class ComponentPropertiesDialog(QDialog):
def __init__(self, component_type, parent=None):
super().__init__(parent)
self.setWindowTitle(f"{component_type.title()} Properties")
self.setMinimumWidth(400)
layout = QVBoxLayout(self)
# Create tab widget for different property categories
tab_widget = QTabWidget()
# Basic properties tab
basic_tab = QWidget()
form = QFormLayout(basic_tab)
self.properties = {}
if component_type == PowerComponent.BUS:
# Basic Properties
self.properties['name'] = QLineEdit("Bus 1")
self.properties['voltage'] = QLineEdit("132")
self.properties['type'] = QComboBox()
self.properties['type'].addItems(["Slack", "PV", "PQ"])
form.addRow("Bus Name:", self.properties['name'])
form.addRow("Nominal Voltage (kV):", self.properties['voltage'])
form.addRow("Bus Type:", self.properties['type'])
# Advanced Properties
self.properties['v_min'] = QLineEdit("0.95")
self.properties['v_max'] = QLineEdit("1.05")
self.properties['angle'] = QLineEdit("0.0")
form.addRow("Minimum Voltage (p.u.):", self.properties['v_min'])
form.addRow("Maximum Voltage (p.u.):", self.properties['v_max'])
form.addRow("Initial Angle (degrees):", self.properties['angle'])
elif component_type == PowerComponent.GENERATOR:
# Basic Properties
self.properties['name'] = QLineEdit("Gen 1")
self.properties['power'] = QLineEdit("100")
self.properties['voltage'] = QLineEdit("132")
self.properties['pf'] = QLineEdit("0.85")
form.addRow("Generator Name:", self.properties['name'])
form.addRow("Active Power (MW):", self.properties['power'])
form.addRow("Voltage (kV):", self.properties['voltage'])
form.addRow("Power Factor:", self.properties['pf'])
# Machine Parameters
self.properties['xd'] = QLineEdit("1.5")
self.properties['xq'] = QLineEdit("1.5")
self.properties['xd_prime'] = QLineEdit("0.3")
self.properties['h'] = QLineEdit("5.0")
self.properties['d'] = QLineEdit("2.0")
form.addRow("Direct Axis Reactance (p.u.):", self.properties['xd'])
form.addRow("Quadrature Axis Reactance (p.u.):", self.properties['xq'])
form.addRow("Transient Reactance (p.u.):", self.properties['xd_prime'])
form.addRow("Inertia Constant (s):", self.properties['h'])
form.addRow("Damping Coefficient:", self.properties['d'])
# Operating Limits
self.properties['p_max'] = QLineEdit("150")
self.properties['p_min'] = QLineEdit("0")
self.properties['q_max'] = QLineEdit("100")
self.properties['q_min'] = QLineEdit("-100")
form.addRow("Maximum Active Power (MW):", self.properties['p_max'])
form.addRow("Minimum Active Power (MW):", self.properties['p_min'])
form.addRow("Maximum Reactive Power (MVAR):", self.properties['q_max'])
form.addRow("Minimum Reactive Power (MVAR):", self.properties['q_min'])
elif component_type == PowerComponent.LOAD:
# Basic Properties
self.properties['name'] = QLineEdit("Load 1")
self.properties['power'] = QLineEdit("50")
self.properties['pf'] = QLineEdit("0.9")
form.addRow("Load Name:", self.properties['name'])
form.addRow("Active Power (MW):", self.properties['power'])
form.addRow("Power Factor:", self.properties['pf'])
# Load Model Parameters
self.properties['model_type'] = QComboBox()
self.properties['model_type'].addItems([
"Constant Power", "Constant Current",
"Constant Impedance", "ZIP Model"
])
self.properties['voltage_dependency'] = QLineEdit("1.0")
self.properties['frequency_dependency'] = QLineEdit("0.0")
form.addRow("Load Model:", self.properties['model_type'])
form.addRow("Voltage Dependency:", self.properties['voltage_dependency'])
form.addRow("Frequency Dependency:", self.properties['frequency_dependency'])
# ZIP Model Parameters (if applicable)
self.properties['z_percent'] = QLineEdit("30")
self.properties['i_percent'] = QLineEdit("30")
self.properties['p_percent'] = QLineEdit("40")
form.addRow("Constant Z Component (%):", self.properties['z_percent'])
form.addRow("Constant I Component (%):", self.properties['i_percent'])
form.addRow("Constant P Component (%):", self.properties['p_percent'])
elif component_type == PowerComponent.TRANSFORMER:
# Basic Properties
self.properties['name'] = QLineEdit("Tx 1")
self.properties['rating'] = QLineEdit("100")
self.properties['primary'] = QLineEdit("132")
self.properties['secondary'] = QLineEdit("33")
form.addRow("Transformer Name:", self.properties['name'])
form.addRow("Rating (MVA):", self.properties['rating'])
form.addRow("Primary Voltage (kV):", self.properties['primary'])
form.addRow("Secondary Voltage (kV):", self.properties['secondary'])
# Impedance Parameters
self.properties['r'] = QLineEdit("0.02")
self.properties['x'] = QLineEdit("0.08")
self.properties['b'] = QLineEdit("0.0")
self.properties['g'] = QLineEdit("0.0")
form.addRow("Resistance (p.u.):", self.properties['r'])
form.addRow("Reactance (p.u.):", self.properties['x'])
form.addRow("Charging Susceptance (p.u.):", self.properties['b'])
form.addRow("Conductance (p.u.):", self.properties['g'])
# Tap Changer Properties
self.properties['tap_pos'] = QSpinBox()
self.properties['tap_pos'].setRange(-16, 16)
self.properties['tap_pos'].setValue(0)
self.properties['tap_step'] = QLineEdit("1.25")
self.properties['tap_side'] = QComboBox()
self.properties['tap_side'].addItems(["Primary", "Secondary"])
form.addRow("Tap Position:", self.properties['tap_pos'])
form.addRow("Tap Step Size (%):", self.properties['tap_step'])
form.addRow("Tap Side:", self.properties['tap_side'])
elif component_type == PowerComponent.LINE:
# Basic Properties
self.properties['name'] = QLineEdit("Line 1")
self.properties['length'] = QLineEdit("10")
self.properties['voltage'] = QLineEdit("132")
form.addRow("Line Name:", self.properties['name'])
form.addRow("Length (km):", self.properties['length'])
form.addRow("Nominal Voltage (kV):", self.properties['voltage'])
# Line Parameters
self.properties['r1'] = QLineEdit("0.1")
self.properties['x1'] = QLineEdit("0.4")
self.properties['b1'] = QLineEdit("0.003")
self.properties['r0'] = QLineEdit("0.3")
self.properties['x0'] = QLineEdit("1.2")
self.properties['b0'] = QLineEdit("0.002")
form.addRow("Positive Sequence R (Ω/km):", self.properties['r1'])
form.addRow("Positive Sequence X (Ω/km):", self.properties['x1'])
form.addRow("Positive Sequence B (μS/km):", self.properties['b1'])
form.addRow("Zero Sequence R (Ω/km):", self.properties['r0'])
form.addRow("Zero Sequence X (Ω/km):", self.properties['x0'])
form.addRow("Zero Sequence B (μS/km):", self.properties['b0'])
# Thermal Limits
self.properties['i_max'] = QLineEdit("800")
self.properties['s_max'] = QLineEdit("200")
form.addRow("Maximum Current (A):", self.properties['i_max'])
form.addRow("Maximum Power (MVA):", self.properties['s_max'])
# Add the form to a scroll area
scroll = QScrollArea()
scroll.setWidget(basic_tab)
scroll.setWidgetResizable(True)
layout.addWidget(scroll)
# Add buttons
buttons = QDialogButtonBox(
QDialogButtonBox.Ok | QDialogButtonBox.Cancel,
Qt.Horizontal, self)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
layout.addWidget(buttons)
def get_properties(self):
"""Get properties as dictionary"""
result = {}
for key, widget in self.properties.items():
if isinstance(widget, QComboBox):
result[key] = widget.currentText()
elif isinstance(widget, QSpinBox):
result[key] = str(widget.value())
else:
result[key] = widget.text()
return result
def create_generator_properties(self, form):
"""Create detailed generator properties"""
# Basic Properties Tab
basic_group = QGroupBox("Basic Properties")
basic_layout = QFormLayout()
self.properties['name'] = QLineEdit("Gen 1")
self.properties['power'] = QLineEdit("100")
self.properties['voltage'] = QLineEdit("132")
self.properties['pf'] = QLineEdit("0.85")
self.properties['type'] = QComboBox()
self.properties['type'].addItems(["Synchronous", "Induction", "Inverter-Based"])
basic_layout.addRow("Generator Name:", self.properties['name'])
basic_layout.addRow("Rated Power (MVA):", self.properties['power'])
basic_layout.addRow("Rated Voltage (kV):", self.properties['voltage'])
basic_layout.addRow("Power Factor:", self.properties['pf'])
basic_layout.addRow("Generator Type:", self.properties['type'])
basic_group.setLayout(basic_layout)
form.addWidget(basic_group)
# Machine Parameters Tab
machine_group = QGroupBox("Machine Parameters")
machine_layout = QFormLayout()
self.properties['xd'] = QLineEdit("1.5")
self.properties['xq'] = QLineEdit("1.5")
self.properties['xd_prime'] = QLineEdit("0.3")
self.properties['xq_prime'] = QLineEdit("0.3")
self.properties['xd_dprime'] = QLineEdit("0.2")
self.properties['xq_dprime'] = QLineEdit("0.2")
self.properties['xl'] = QLineEdit("0.15")
self.properties['ra'] = QLineEdit("0.003")
machine_layout.addRow("Direct Axis Reactance (Xd):", self.properties['xd'])
machine_layout.addRow("Quadrature Axis Reactance (Xq):", self.properties['xq'])
machine_layout.addRow("Transient Reactance X'd:", self.properties['xd_prime'])
machine_layout.addRow("Transient Reactance X'q:", self.properties['xq_prime'])
machine_layout.addRow("Subtransient Reactance X''d:", self.properties['xd_dprime'])
machine_layout.addRow("Subtransient Reactance X''q:", self.properties['xq_dprime'])
machine_layout.addRow("Leakage Reactance (Xl):", self.properties['xl'])
machine_layout.addRow("Armature Resistance (Ra):", self.properties['ra'])
machine_group.setLayout(machine_layout)
form.addWidget(machine_group)
# Time Constants Tab
time_group = QGroupBox("Time Constants")
time_layout = QFormLayout()
self.properties['td0_prime'] = QLineEdit("6.0")
self.properties['tq0_prime'] = QLineEdit("0.5")
self.properties['td0_dprime'] = QLineEdit("0.05")
self.properties['tq0_dprime'] = QLineEdit("0.05")
self.properties['ta'] = QLineEdit("0.2")
time_layout.addRow("D-axis Transient T'd0 (s):", self.properties['td0_prime'])
time_layout.addRow("Q-axis Transient T'q0 (s):", self.properties['tq0_prime'])
time_layout.addRow("D-axis Subtransient T''d0 (s):", self.properties['td0_dprime'])
time_layout.addRow("Q-axis Subtransient T''q0 (s):", self.properties['tq0_dprime'])
time_layout.addRow("Armature Time Constant (s):", self.properties['ta'])
time_group.setLayout(time_layout)
form.addWidget(time_group)
# Mechanical Parameters
mech_group = QGroupBox("Mechanical Parameters")
mech_layout = QFormLayout()
self.properties['h'] = QLineEdit("5.0")
self.properties['d'] = QLineEdit("2.0")
self.properties['poles'] = QSpinBox()
self.properties['poles'].setRange(2, 32)
self.properties['poles'].setValue(2)
mech_layout.addRow("Inertia Constant H (s):", self.properties['h'])
mech_layout.addRow("Damping Coefficient D:", self.properties['d'])
mech_layout.addRow("Number of Poles:", self.properties['poles'])
mech_group.setLayout(mech_layout)
form.addWidget(mech_group)
def create_transformer_properties(self, form):
"""Create detailed transformer properties"""
# Basic Properties Tab
basic_group = QGroupBox("Basic Properties")
basic_layout = QFormLayout()
self.properties['name'] = QLineEdit("Tx 1")
self.properties['rating'] = QLineEdit("100")
self.properties['primary'] = QLineEdit("132")
self.properties['secondary'] = QLineEdit("33")
self.properties['type'] = QComboBox()
self.properties['type'].addItems([
"Two-Winding", "Three-Winding",
"Auto-Transformer", "Phase Shifting"
])
self.properties['connection'] = QComboBox()
self.properties['connection'].addItems([
"Wye-Wye", "Delta-Delta",
"Wye-Delta", "Delta-Wye"
])
basic_layout.addRow("Transformer Name:", self.properties['name'])
basic_layout.addRow("Rating (MVA):", self.properties['rating'])
basic_layout.addRow("Primary Voltage (kV):", self.properties['primary'])
basic_layout.addRow("Secondary Voltage (kV):", self.properties['secondary'])
basic_layout.addRow("Transformer Type:", self.properties['type'])
basic_layout.addRow("Connection Type:", self.properties['connection'])
basic_group.setLayout(basic_layout)
form.addWidget(basic_group)
# Impedance Parameters
imp_group = QGroupBox("Impedance Parameters")
imp_layout = QFormLayout()
self.properties['r'] = QLineEdit("0.02")
self.properties['x'] = QLineEdit("0.08")
self.properties['r0'] = QLineEdit("0.02")
self.properties['x0'] = QLineEdit("0.08")
self.properties['b'] = QLineEdit("0.0")
self.properties['g'] = QLineEdit("0.0")
imp_layout.addRow("Positive Sequence R (p.u.):", self.properties['r'])
imp_layout.addRow("Positive Sequence X (p.u.):", self.properties['x'])
imp_layout.addRow("Zero Sequence R (p.u.):", self.properties['r0'])
imp_layout.addRow("Zero Sequence X (p.u.):", self.properties['x0'])
imp_layout.addRow("Magnetizing B (p.u.):", self.properties['b'])
imp_layout.addRow("Core Loss G (p.u.):", self.properties['g'])
imp_group.setLayout(imp_layout)
form.addWidget(imp_group)
# Tap Changer Properties
tap_group = QGroupBox("Tap Changer")
tap_layout = QFormLayout()
self.properties['tap_side'] = QComboBox()
self.properties['tap_side'].addItems(["Primary", "Secondary"])
self.properties['tap_pos'] = QSpinBox()
self.properties['tap_pos'].setRange(-16, 16)
self.properties['tap_pos'].setValue(0)
self.properties['tap_step'] = QLineEdit("1.25")
self.properties['tap_min'] = QLineEdit("0.9")
self.properties['tap_max'] = QLineEdit("1.1")
self.properties['tap_neutral'] = QLineEdit("1.0")
tap_layout.addRow("Tap Side:", self.properties['tap_side'])
tap_layout.addRow("Tap Position:", self.properties['tap_pos'])
tap_layout.addRow("Step Size (%):", self.properties['tap_step'])
tap_layout.addRow("Minimum Tap:", self.properties['tap_min'])
tap_layout.addRow("Maximum Tap:", self.properties['tap_max'])
tap_layout.addRow("Neutral Tap:", self.properties['tap_neutral'])
tap_group.setLayout(tap_layout)
form.addWidget(tap_group)
# Grounding Properties
ground_group = QGroupBox("Grounding")
ground_layout = QFormLayout()
self.properties['ground_primary'] = QComboBox()
self.properties['ground_primary'].addItems([
"Solid", "Resistance", "Reactance", "Ungrounded"
])
self.properties['ground_secondary'] = QComboBox()
self.properties['ground_secondary'].addItems([
"Solid", "Resistance", "Reactance", "Ungrounded"
])
self.properties['ground_r'] = QLineEdit("0.0")
self.properties['ground_x'] = QLineEdit("0.0")
ground_layout.addRow("Primary Grounding:", self.properties['ground_primary'])
ground_layout.addRow("Secondary Grounding:", self.properties['ground_secondary'])
ground_layout.addRow("Grounding Resistance (Ω):", self.properties['ground_r'])
ground_layout.addRow("Grounding Reactance (Ω):", self.properties['ground_x'])
ground_group.setLayout(ground_layout)
form.addWidget(ground_group)
def create_component_tabs(self, component_type):
"""Create tabbed interface for component properties"""
tab_widget = QTabWidget()
# Basic Properties Tab
basic_tab = QWidget()
basic_layout = QFormLayout(basic_tab)
tab_widget.addTab(basic_tab, "Basic")
# Advanced Properties Tab
advanced_tab = QWidget()
advanced_layout = QFormLayout(advanced_tab)
tab_widget.addTab(advanced_tab, "Advanced")
# Protection Settings Tab
protection_tab = QWidget()
protection_layout = QFormLayout(protection_tab)
tab_widget.addTab(protection_tab, "Protection")
# Cost & Maintenance Tab
maintenance_tab = QWidget()
maintenance_layout = QFormLayout(maintenance_tab)
tab_widget.addTab(maintenance_tab, "Maintenance")
if component_type == PowerComponent.CAPACITOR:
self.setup_capacitor_properties(basic_layout, advanced_layout, protection_layout, maintenance_layout)
elif component_type == PowerComponent.REACTOR:
self.setup_reactor_properties(basic_layout, advanced_layout, protection_layout, maintenance_layout)
elif component_type == PowerComponent.SWITCH:
self.setup_switch_properties(basic_layout, advanced_layout, protection_layout, maintenance_layout)
elif component_type == PowerComponent.BREAKER:
self.setup_breaker_properties(basic_layout, advanced_layout, protection_layout, maintenance_layout)
elif component_type == PowerComponent.MOTOR:
self.setup_motor_properties(basic_layout, advanced_layout, protection_layout, maintenance_layout)
elif component_type == PowerComponent.SOLAR:
self.setup_solar_properties(basic_layout, advanced_layout, protection_layout, maintenance_layout)
elif component_type == PowerComponent.WIND:
self.setup_wind_properties(basic_layout, advanced_layout, protection_layout, maintenance_layout)
elif component_type == PowerComponent.BATTERY:
self.setup_battery_properties(basic_layout, advanced_layout, protection_layout, maintenance_layout)
elif component_type == PowerComponent.HVDC:
self.setup_hvdc_properties(basic_layout, advanced_layout, protection_layout, maintenance_layout)
return tab_widget
def setup_capacitor_properties(self, basic, advanced, protection, maintenance):
# Basic Properties
self.properties['name'] = QLineEdit("Cap 1")
self.properties['rating'] = QLineEdit("10")
self.properties['voltage'] = QLineEdit("132")
self.properties['type'] = QComboBox()
self.properties['type'].addItems(["Fixed", "Switched", "Variable"])
basic.addRow("Name:", self.properties['name'])
basic.addRow("Rating (MVAR):", self.properties['rating'])
basic.addRow("Voltage (kV):", self.properties['voltage'])
basic.addRow("Type:", self.properties['type'])
# Advanced Properties
self.properties['q_max'] = QLineEdit("12")
self.properties['q_min'] = QLineEdit("0")
self.properties['steps'] = QSpinBox()
self.properties['steps'].setRange(1, 12)
advanced.addRow("Max Reactive Power (MVAR):", self.properties['q_max'])
advanced.addRow("Min Reactive Power (MVAR):", self.properties['q_min'])
advanced.addRow("Number of Steps:", self.properties['steps'])
# Protection Settings
self.properties['overvoltage'] = QLineEdit("1.1")
self.properties['overcurrent'] = QLineEdit("1.3")
protection.addRow("Overvoltage Setting (p.u.):", self.properties['overvoltage'])
protection.addRow("Overcurrent Setting (p.u.):", self.properties['overcurrent'])
# Maintenance
self.properties['install_date'] = QDateEdit()
self.properties['last_maintenance'] = QDateEdit()
maintenance.addRow("Installation Date:", self.properties['install_date'])
maintenance.addRow("Last Maintenance:", self.properties['last_maintenance'])
def setup_motor_properties(self, basic, advanced, protection, maintenance):
# Basic Properties
self.properties['name'] = QLineEdit("Motor 1")
self.properties['power'] = QLineEdit("500")
self.properties['voltage'] = QLineEdit("400")
self.properties['speed'] = QLineEdit("1500")
basic.addRow("Name:", self.properties['name'])
basic.addRow("Power Rating (kW):", self.properties['power'])
basic.addRow("Voltage (V):", self.properties['voltage'])
basic.addRow("Rated Speed (RPM):", self.properties['speed'])
# Advanced Properties
self.properties['efficiency'] = QLineEdit("95")
self.properties['power_factor'] = QLineEdit("0.85")
self.properties['inertia'] = QLineEdit("2.5")
self.properties['service_factor'] = QLineEdit("1.15")
advanced.addRow("Efficiency (%):", self.properties['efficiency'])
advanced.addRow("Power Factor:", self.properties['power_factor'])
advanced.addRow("Inertia Constant (H):", self.properties['inertia'])
advanced.addRow("Service Factor:", self.properties['service_factor'])
# Protection Settings
self.properties['overload_setting'] = QLineEdit("115")
self.properties['locked_rotor_time'] = QLineEdit("5")
protection.addRow("Overload Setting (%):", self.properties['overload_setting'])
protection.addRow("Locked Rotor Time (s):", self.properties['locked_rotor_time'])
# Maintenance
self.properties['operating_hours'] = QLineEdit("0")
self.properties['maintenance_interval'] = QLineEdit("8760")
maintenance.addRow("Operating Hours:", self.properties['operating_hours'])
maintenance.addRow("Maintenance Interval (h):", self.properties['maintenance_interval'])
# Add similar setup methods for other components...
class DiagramScene(QGraphicsScene):
def __init__(self, parent=None):
super().__init__(parent)
self.main_window = parent # Store reference to main window
self.setSceneRect(0, 0, 800, 600)
self.current_component = None
self.drawing_line = False
self.line_start = None
self.components = []
self.component_properties = {}
def mousePressEvent(self, event):
if event.button() == Qt.RightButton:
self.handle_right_click(event)
elif self.current_component:
pos = event.scenePos()
item = self.draw_component(self.current_component, pos)
if item:
item.setFlag(QGraphicsItem.ItemIsMovable)
item.setFlag(QGraphicsItem.ItemIsSelectable)
# Record add operation
if hasattr(self.parent(), 'record_operation'):
self.parent().record_operation('add', item)
else:
super().mousePressEvent(event)
def handle_right_click(self, event):
item = self.itemAt(event.scenePos(), QTransform())
if item:
menu = QMenu()
# Add element type and name to menu title
for comp_type, comp_item in self.components:
if comp_item == item:
name = self.component_properties.get(item, {}).get('name', '')
if not name:
if comp_type == PowerComponent.BUS:
name = f"Bus {self.get_node_number(item)}"
else:
name = f"{comp_type.title()}"
menu.addSection(name)
break
edit_action = menu.addAction("Edit Properties")
delete_action = menu.addAction("Delete")
delete_action.setIcon(QIcon.fromTheme("edit-delete"))
# Add separator
menu.addSeparator()
# Add "Delete Connected Lines" option for non-line elements
if any(comp_item == item and comp_type != PowerComponent.LINE
for comp_type, comp_item in self.components):
delete_lines_action = menu.addAction("Delete Connected Lines")
else:
delete_lines_action = None
action = menu.exec_(event.screenPos())
if action == edit_action:
self.edit_component_properties(item)
elif action == delete_action:
if self.main_window: # Check if main window reference exists
self.main_window.delete_element(item)
elif delete_lines_action and action == delete_lines_action:
if self.main_window: # Check if main window reference exists
self.main_window.delete_connected_lines(item)
def edit_component_properties(self, item):
for comp_type, comp_item in self.components:
if comp_item == item:
dialog = ComponentPropertiesDialog(comp_type, None)
if item in self.component_properties:
for key, widget in dialog.properties.items():
if key in self.component_properties[item]:
widget.setText(self.component_properties[item][key])
if dialog.exec_() == QDialog.Accepted:
self.component_properties[item] = dialog.get_properties()
break
def remove_component(self, item):
# Record delete operation before removing
if hasattr(self.parent(), 'record_operation'):
self.parent().record_operation('delete', item)
self.removeItem(item)
self.components = [(t, i) for t, i in self.components if i != item]
if item in self.component_properties:
del self.component_properties[item]
def save_diagram(self, filename):
diagram_data = {
'components': [],
'connections': []
}
for comp_type, item in self.components:
if comp_type != 'line':
pos = item.pos()
component_data = {
'type': comp_type,
'x': pos.x(),
'y': pos.y(),
'properties': self.component_properties.get(item, {})
}
diagram_data['components'].append(component_data)
else:
line = item
diagram_data['connections'].append({
'x1': line.line().x1(),
'y1': line.line().y1(),
'x2': line.line().x2(),
'y2': line.line().y2()
})
with open(filename, 'w') as f:
json.dump(diagram_data, f)
def load_diagram(self, filename):
self.clear()
self.components.clear()
self.component_properties.clear()
with open(filename, 'r') as f:
diagram_data = json.load(f)
for component in diagram_data['components']:
pos = QPointF(component['x'], component['y'])
self.current_component = component['type']
self.draw_component(component['type'], pos)
if self.components:
_, item = self.components[-1]
self.component_properties[item] = component['properties']
for connection in diagram_data['connections']:
line = self.addLine(
connection['x1'], connection['y1'],
connection['x2'], connection['y2'],
QPen(Qt.white, 2)) # Added closing parenthesis here
self.components.append(('line', line))
def draw_component(self, component_type, pos):
item = None
if component_type == PowerComponent.BUS:
item = self.addRect(pos.x()-25, pos.y()-5, 50, 10,
QPen(Qt.white), QBrush(Qt.transparent))
self.add_node_number(item, pos)
self.components.append((component_type, item))
elif component_type == PowerComponent.GENERATOR:
item = self.addEllipse(pos.x()-15, pos.y()-15, 30, 30,
QPen(Qt.white), QBrush(Qt.transparent))
text = self.addText("G", QFont("Arial", 10))
text.setDefaultTextColor(Qt.white)
text.setPos(pos.x()-5, pos.y()-10)
text.setParentItem(item) # Make text move with generator
self.components.append((component_type, item))
elif component_type == PowerComponent.LOAD:
polygon = QPolygonF([
QPointF(pos.x(), pos.y()-20),
QPointF(pos.x()-20, pos.y()+20),
QPointF(pos.x()+20, pos.y()+20)
])
item = self.addPolygon(polygon, QPen(Qt.white), QBrush(Qt.transparent))
self.components.append((component_type, item))
elif component_type == PowerComponent.TRANSFORMER:
# Create a group for transformer components
group = QGraphicsItemGroup()
self.addItem(group)
# Add primary and secondary windings
circle1 = self.addEllipse(pos.x()-20, pos.y()-10, 20, 20,
QPen(Qt.white), QBrush(Qt.transparent))
circle2 = self.addEllipse(pos.x(), pos.y()-10, 20, 20,
QPen(Qt.white), QBrush(Qt.transparent))
# Add to group
group.addToGroup(circle1)
group.addToGroup(circle2)
item = group
self.components.append((component_type, item))
elif component_type == PowerComponent.LINE:
if self.drawing_line:
if self.line_start:
item = self.addLine(
self.line_start.x(), self.line_start.y(),
pos.x(), pos.y(),
QPen(Qt.white, 2)
) # Fixed closing parenthesis
self.components.append(('line', item))
self.line_start = None
self.drawing_line = False
else:
self.line_start = pos
return None
if item:
item.setFlag(QGraphicsItem.ItemIsMovable)
item.setFlag(QGraphicsItem.ItemIsSelectable)
item.setAcceptHoverEvents(True)
return item
def add_node_number(self, item, pos):
if not hasattr(self, 'node_numbering'):
self.node_numbering = NodeNumbering()
number = self.node_numbering.get_next_number()
text = self.addText(str(number))
text.setDefaultTextColor(Qt.white)
text.setPos(pos.x() + 25, pos.y() - 25)
self.node_numbering.node_map[item] = number
return number
def get_node_number(self, item):
if hasattr(self, 'node_numbering'):
return self.node_numbering.node_map.get(item)
return None
def mouseMoveEvent(self, event):
if self.drawing_line and self.line_start:
# Show temporary line while drawing
if hasattr(self, 'temp_line'):
self.removeItem(self.temp_line)
self.temp_line = self.addLine(
self.line_start.x(), self.line_start.y(),
event.scenePos().x(), event.scenePos().y(),
QPen(Qt.white, 2, Qt.DashLine)
)
super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
if hasattr(self, 'temp_line'):
self.removeItem(self.temp_line)
delattr(self, 'temp_line')
super().mouseReleaseEvent(event)
def keyPressEvent(self, event):
"""Handle key press events"""
if event.key() == Qt.Key_Delete:
if self.selectedItems():
self.parent().delete_element()
super().keyPressEvent(event)
class PowerFlowSolver:
def __init__(self, diagram_scene):
self.scene = diagram_scene
self.buses = []