-
Notifications
You must be signed in to change notification settings - Fork 1
/
pypsse.py
1225 lines (1158 loc) · 58.2 KB
/
pypsse.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
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 21 10:17:38 2017
Module interfaces with the PSS/E software through the standard PSS/E APIs.
Creates and deletes additional files needed for certain PSS/E features (e.g.
.dfx, .con, .mon, .sub). Redirects PSS/E output to a string variable. Transfers
the text of the results into a dataframe.
@author: Jesse Boyd
"""
import Tkinter as tk
import tkFileDialog
import StringIO
import os, sys
import pandas as pd
import numpy as np
# import PSSE APIs
PSSE_LOCATION = 'C:\\Program Files (x86)\\PTI\\PSSE34\\PSSPY27\\'
sys.path.append(PSSE_LOCATION)
os.environ['PATH'] = (PSSE_LOCATION + os.environ['PATH'])
try:
import psse34
except ImportError:
inputfilepath = ''
if not inputfilepath:
root = tk.Tk()
PSSE_LOCATION = tkFileDialog.askdirectory(
title='Select PSSE Python library directory (usually PSSE34//PSSPY27)',
filetypes=[('application', '*.exe')])
root.destroy()
sys.path.append(PSSE_LOCATION)
os.environ['PATH'] = (PSSE_LOCATION + os.environ['PATH'])
try:
import psse34
except ImportError as e:
raise ImportError(
'An issue was encountered importing the PSSE library: /n{}'.format(
str(e)))
import psspy
import pssarrays
import pssexcel
import redirect
# create constants that PSS/E requires as default inputs
_i = 100000000
_f = 1.00000002004e+20
_s = 'ÿ'
stdout = sys.stdout
class pypsse(object):
"""Creates an wrapper for PSS/E APIs. Note: although PSS/E supports
multiple instances of its program, if another object of the pypsse class
is created, it will change all pypsse object reference cases to the most
recently opened case. This is unfortunate. Note: reserve sid number 11 for
use in the class methods (it will overwrite other subsystems with sid 11)."""
def __init__(self):
"""Initialization prepares the error message and redirects the PSSE
output from sys.out to a StringIO for processing."""
self.psse_version = 0
self.error_message = ''
self.__internally_created_files__ = []
self.out = StringIO.StringIO()
sys.stdout = self.out
self.support_file_path = ''
self.support_files = list()
self.psspy = psspy
self.pssarrays = pssarrays
self.pssexcel = pssexcel
self.data = None
self.BUS_FIELDS = {}
self.BUS_FIELDS['Real'] = ['BASE', 'PU', 'KV', 'ANGLE', 'ANGLED',
'NVLMHI', 'NVLMLO', 'EVLMHI', 'EVLMLO',
'MISMATCH', 'O_MISMATCH']
self.BUS_FIELDS['Integer'] = ['STATION', 'NUMBER', 'TYPE', 'AREA',
'ZONE', 'OWNER', 'DUMMY']
self.BUS_FIELDS['Complex'] = ['MVA', 'IL', 'YL', 'TOTAL', 'LDDGN',
'SC_MVA', 'SC_IL', 'SC_YL', 'SC_TOTAL',
'FX_MVA', 'FX_IL', 'FX_YL', 'FX_TOTAL',
'YS', 'YSZERO', 'YSZ', 'YSW', 'YSWZ',
'SHUNTN', 'SHUNTZ']
self.A_BUS_FIELDS = {}
self.A_BUS_FIELDS['Real'] = ['BASE', 'PU', 'KV', 'ANGLE', 'ANGLED',
'NVLMHI', 'NVLMLO', 'EVLMHI', 'EVLMLO',
'MISMATCH', 'O_MISMATCH']
self.A_BUS_FIELDS['Integer'] = ['NUMBER', 'TYPE', 'AREA', 'ZONE',
'OWNER', 'DUMMY']
self.A_BUS_FIELDS['Complex'] = ['VOLTAGE', 'SHUNTACT', 'O_SHUNTACT',
'SHUNTNOM', 'O_SHUNTNOM', 'SHUNTN',
'SHUNTZ', 'MISMATCH', 'O_MISMATCH']
self.A_BUS_FIELDS['Character'] = ['NAME', 'EXNAME']
self.BRN_FIELDS = {}
self.BRN_FIELDS['Real'] = ['RATEA', 'RATEB', 'RATEC', 'RATE', 'LENGTH',
'CHARG', 'CHARGZ', 'MOVIPR', 'FRACT1',
'FRACT2', 'FRACT3', 'FRACT4']
self.BRN_FIELDS['Integer'] = ['STATUS', 'METER', 'NMETR', 'OWNERS',
'OWN1', 'OWN2', 'OWN3', 'OWN4', 'SCTYP']
self.BRN_FIELDS['Complex'] = ['RX', 'ISHNT', 'JSHNT', 'RXZ', 'ISHNTZ',
'JSHNTZ', 'LOSSES', 'O_LOSSES']
self.BRN_FIELDS['Miscellaneous'] = ['MVA', 'O_MVA', 'AMPS', 'PUCUR',
'CURANG', 'PCTRTA', 'PCTRTB',
'PCTRTC', 'PCTMVA', 'PCTMVB',
'PCTMVC', 'PCTCPA', 'PCTCPB',
'PCTCPC', 'P', 'O_P', 'Q', 'O_Q',
'PLOS', 'O_PLOS', 'QLOS', 'O_QLOS']
self.A_BRN_FIELDS = {}
self.A_BRN_FIELDS['Real'] = ['AMPS', 'PUCUR', 'PCTRATE', 'PCTRATEA',
'PCTRATEB', 'PCTRATEC', 'PCTMVARATE',
'PCTMVARATEA', 'PCTMVARATEB',
'PCTMVARATEC', 'PCTCORPRATE',
'PCTCORPRATEA', 'PCTCORPRATEB',
'PCTCORPRATEC', 'MAXPCTRATE',
'MAXPCTRATEA', 'MAXPCTRATEB',
'MAXPCTRATEC', 'MAXPCTCRPRATE',
'MAXPCTCRPRATEA', 'MAXPCTCRPRATEB',
'MAXPCTCRPRATEC', 'FRACT1', 'FRACT2',
'FRACT3', 'FRACT4', 'RATE', 'RATEA',
'RATEB', 'RATEC', 'LENGTH', 'CHARGING',
'CHARGINGZERO', 'MOVIRATED', 'P', 'Q',
'MVA', 'MAXMVA', 'PLOSS', 'QLOSS', 'O_P',
'O_Q', 'O_MVA', 'O_MAXMVA', 'O_PLOSS',
'O_QLOSS']
self.A_BRN_FIELDS['Integer'] = ['FROMNUMBER', 'TONUMBER', 'STATUS',
'METERNUMBER', 'NMETERNUMBER', 'OWNERS',
'OWN1', 'OWN2', 'OWN3', 'OWN4',
'MOVTYPE']
self.A_BRN_FIELDS['Complex'] = ['RX', 'FROMSHNT', 'TOSHNT', 'RXZERO',
'FRONSHNTZERO', 'TOSHNTZERO', 'PQ',
'PQLOSS', 'O_PQ', 'O_PQLOSS']
self.A_BRN_FIELDS['Character'] = ['ID', 'FROMNAME', 'FROMEXNAME',
'TONAME', 'TOEXNAME', 'METERNAME',
'METEREXNAME', 'NMETERNAME',
'NMETEREXNAME']
self.A_TR3_FIELDS = {}
self.A_TR3_FIELDS['Real'] = ['FRACT1', 'FRACT2', 'FRACT3', 'FRACT4',
'VMSTAR', 'ANSTAR', 'PLOSS', 'QLOSS',
'O_PLOSS', 'O_QLOSS']
self.A_TR3_FIELDS['Integer'] = ['WIND1NUMBER', 'WIND2NUMBER',
'WIND3NUMBER', 'STATUS', 'NMETERNUMBER',
'OWNERS', 'OWN1', 'OWN2', 'OWN3',
'OWN4', 'CW', 'CZ', 'CM', 'CZ0', 'CZG',
'CNXCOD', 'ZADCOD']
self.A_TR3_FIELDS['Complex'] = ['RX1-2ACT', 'RX1-2ACTCZ', 'RX1-2NOM',
'RX1-2NOMCZ', 'RX2-3ACT', 'RX2-3ACTCZ',
'RX2-3NOM', 'RX2-3NOMCZ', 'RX3-1ACT',
'RX3-1ACTCZ', 'RX3-1NOM', 'RX3-1NOMCZ',
'YMAG', 'YMAGCM', 'ZG1', 'ZGRND',
'ZG1CZG', 'ZG2', 'ZGRND2', 'ZG2CZG',
'ZG3', 'ZGRND3', 'ZG3CZG', 'Z01', 'Z02',
'Z03', 'Z01CZ0', 'Z02CZ0', 'Z03CZ0',
'ZNUTRL', 'ZNUTRLCZG', 'PQLOSS',
'O_PQLOSS']
self.A_TR3_FIELDS['Character'] = ['ID', 'WIND1NAME', 'WIND1EXNAME',
'WIND2NAME', 'WIND2EXNAME',
'WIND3NAME', 'WIND3EXNAME',
'NMETERNAME', 'NMETEREXNAME',
'XFRNAME', 'VECTORGROUP']
self.A_TRN_FIELDS = {}
self.A_TRN_FIELDS['Real'] = ['AMPS', 'PUCUR', 'PCTRATE', 'PCTRATEA',
'PCTRATEB', 'PCTRATEC', 'PCTMVARATE',
'PCTMVARATEA', 'PCTMVARATEB',
'PCTMVARATEC', 'PCTCORPRATE',
'PCTCORPRATEA', 'PCTCORPRATEB',
'PCTCORPRATEC', 'MAXPCTRATE',
'MAXPCTRATEA', 'MAXPCTRATEB',
'MAXPCTRATEC', 'MAXPCTCRPRATE',
'MAXPCTCRPRATEA', 'MAXPCTCRPRATEB',
'MAXPCTCRPRATEC', 'MXPCTMVARAT',
'MXPCTMVARATA', 'MXPCTMVARATB',
'MXPCTMVARATC', 'MXPCTCRPRAT',
'MXPCTCRPRATA', 'MXPCTCRPRATB',
'MXPCTCRPRATC', 'FRACT1', 'FRACT2',
'FRACT3', 'FRACT4', 'RATE', 'RATEA',
'RATEB', 'RATEC', 'RATIO', 'RATIOCW',
'RATIO2', 'RATIO2CW', 'ANGLE', 'RMAX',
'RMAXCW', 'RMIN', 'RMINCW', 'VMAX',
'VMAXKV', 'VMIN', 'VMINKV', 'STEP',
'STEPCW', 'CNXANG', 'NOMV1', 'NOMV2',
'SBASE1', 'P', 'Q', 'MVA', 'MAXMVA',
'PLOSS', 'QLOSS', 'O_P', 'O_Q', 'O_MVA',
'O_MAXMVA', 'O_PLOSS', 'O_QLOSS']
self.A_TRN_FIELDS['Integer'] = ['FROMNUMBER', 'TONUMBER', 'STATUS',
'METERNUMBER', 'NMETERNUMBER', 'OWNERS',
'OWN1', 'OWN2', 'OWN3', 'OWN4',
'ICONTNUMBER', 'SIDCOD', 'WIND1NUMBER',
'WIND2NUMBER', 'TABLE', 'CODE',
'NTPOSN', 'CW', 'CZ', 'CM', 'CZ0',
'CZG', 'CNXCOD', 'TPSTT', 'ANSTT']
self.A_TRN_FIELDS['Complex'] = ['RXACT', 'RXACTCZ', 'RXNOM', 'RXNOMCZ',
'YMAG', 'YMAGCM', 'COMPRX', 'RXZERO',
'ZG1', 'ZGRND', 'ZG1CZG', 'ZG2',
'ZGRND2', 'ZG2CZG', 'Z01', 'Z02',
'Z01CZ0', 'Z02CZ0', 'ZNUTRL',
'ZNUTRLCZG', 'PQ', 'PQLOSS', 'O_PQ',
'O_PQLOSS']
self.A_TRN_FIELDS['Character'] = ['ID', 'FROMNAME', 'FROMEXNAME',
'TONAME', 'TOEXNAME', 'METERNAME',
'METEREXNAME', 'NMETERNAME',
'NMETEREXNAME', 'ICONTNAME',
'ICONTEXNAME', 'WIND1NAME',
'WIND1EXNAME', 'WIND2NAME',
'WIND2EXNAME', 'XFRNAME',
'VECTORGROUP']
self.A_MACH_FIELDS = {}
self.A_MACH_FIELDS['Integer'] = ['NUMBER', 'STATUS', 'WMOD', 'OWNERS',
'OWN1', 'OWN2', 'OWN3', 'OWN4', 'CZG']
self.A_MACH_FIELDS['Real'] = ['FRACT1', 'FRACT2', 'FRACT3', 'FRACT4',
'PERCENT', 'MBASE', 'GENTAP', 'WPF',
'RPOS', 'XSUBTR', 'XTRANS', 'XSYNCH',
'PGEN', 'QGEN', 'MVA', 'PMAX', 'PMIN',
'QMAX', 'QMIN', 'O_PGEN', 'O_QGEN',
'O_MVA', 'O_PMAX', 'O_PMIN', 'O_QMAX',
'O_QMIN']
self.A_MACH_FIELDS['Complex'] = ['ZSORCE', 'XTRAN', 'ZPOS', 'ZNEG',
'ZZERO', 'ZGRND', 'ZGRNDPU', 'PQGEN',
'O_PQGEN']
self.A_MACH_FIELDS['Character'] = ['ID', 'NAME', 'EXNAME']
self.A_LOAD_FIELDS = {}
self.A_LOAD_FIELDS['Integer'] = ['NUMBER', 'TYPE', 'AREA', 'ZONE',
'OWNER', 'DUMMY', 'STATUS']
self.A_LOAD_FIELDS['Real'] = ['BASE', 'PU', 'KV', 'ANGLE', 'ANGLED',
'MVAACT', 'MVANOM', 'ILACT', 'ILNOM',
'YLACT', 'YLNOM', 'TOTALACT', 'TOTALNOM',
'MISMATCH', 'O_MVAACT', 'O_MVANOM',
'O_ILACT', 'O_ILNOM', 'O_YLACT',
'O_YLNOM', 'O_TOTALACT', 'O_TOTALNOM',
'O_MISMATCH']
self.A_LOAD_FIELDS['Complex'] = ['MVAACT', 'MVANOM', 'ILACT', 'ILNOM',
'YLACT', 'YLNOM', 'TOTALACT',
'TOTALNOM', 'MISMATCH', 'LDGNACT',
'LDGNNOM', 'O_MVAACT', 'O_MVANOM',
'O_ILACT', 'O_ILNOM', 'O_YLACT',
'O_YLNOM', 'O_TOTALACT', 'O_TOTALNOM',
'O_MISMATCH', 'O_LDGNACT', 'O_LDGNNOM']
self.A_LOAD_FIELDS['Character'] = ['NAME', 'EXNAME']
def __del__(self):
"""method automatically called when an instance of pypsse is deleted."""
self.__delete_created_files__()
# sys.stdout = stdout
def __reset__(self, delete_files=True):
"""Resets the class attributes so that the object may be reused without
reinstantiation. This is especially helpful to get new results in the
pypsse.out attribute."""
self.__delete_created_files__()
dic = vars(self)
for i in dic.keys():
dic[i] = None
self.__init__()
def redirectoutput(self):
if isinstance(sys.stdout, StringIO.StringIO):
sys.stdout = stdout
return True
else:
self.out = StringIO.StringIO()
sys.stdout = self.out
return True
def printstring(self, string):
if isinstance(sys.stdout, StringIO.StringIO):
self.redirectoutput()
print(string)
self.redirectoutput()
else:
print(string)
def __delete_created_files__(self, exclude_ext=''):
"""Deletes the files which PSS/E annoyingly requires the user to create"""
def delete_file(path):
try:
os.remove(path)
except OSError:
pass
if self.__internally_created_files__ is not None:
for path in self.__internally_created_files__:
if exclude_ext:
if not os.path.splitext(path)[1] == exclude_ext:
delete_file(path)
else:
delete_file(path)
def record(self, filepath=''):
if filepath == '':
root = tk.Tk()
filepath = tkFileDialog.askopenfilename(title='Select output file',
filetypes=[
('Text', '*.txt')])
root.destroy()
with open(filepath, 'w') as f:
f.write(self.out.getvalue())
return True
def opencase(self, casepath=''):
"""Opens PSS/E case"""
if casepath == '':
root = tk.Tk()
casepath = tkFileDialog.askopenfilename(title='Select PSS/E case',
filetypes=[('PSS/E', (
'*.sav', '*.raw'))])
root.destroy()
self.support_file_path = os.path.splitext(casepath)[0]
psspy.psseinit(80000)
if os.path.splitext(casepath)[1].lower() == '.raw':
# version = input('PSS/E version (number 15-34) > ')
with open(casepath, "r") as file:
lines = file.readlines()[:2]
if lines[0][:2] == '@!':
metadata_index = 1
else:
metadata_index = 0
metadata_line = lines[metadata_index].split(',')
version = int(metadata_line[2])
self.root = tk.Tk()
tk.Label(self.root, text="PSS/E version: ").grid(
row=0, column=0)
v = tk.StringVar()
version_confirm = tk.Entry(self.root, width=5, textvariable=v)
version_confirm.grid(row=0, column=1)
v.set("{}".format(version))
tk.Button(self.root, text='Confirm', command=lambda:
self.confirm_v(v)).grid(row=1, column=0, columnspan=2, sticky='nsew')
self.root.mainloop()
if self.psse_version not in range(15, 35):
raise ValueError(
'Incorrect number entered for PSS/E version: {}'.format(
self.psse_version))
ierr = psspy.readrawversion(0, str(self.psse_version), casepath)
if ierr:
self.error_message += (
'Error opening case. API \'readrawversion\' error code %d/n' % ierr)
return False
else:
ierr = psspy.case(casepath)
if ierr:
self.error_message += (
'Error opening case. API \'case\' error code %d/n' % ierr)
return False
return True
def confirm_v(self, textVar):
self.psse_version = int(textVar.get())
self.root.destroy()
def solvecase(self, method='FNSL', options=[0, 0, 0, 0, 0, 0, 0, 0]):
"""Solves the case with the specified method and options. Returns
False if the case does not solve, True if the case solves."""
methods = ['FNSL', 'FDNS']
if method not in methods:
raise ValueError(
'Invalid method \'{}\'. Expected one of: {}/n'.format(method,
methods))
return False
if method == 'FNSL':
app = psspy.fnsl
elif method == 'FDNS':
app = psspy.fdns
app(options)
ierr = psspy.solved()
if ierr:
self.error_message += (
'Error solving case. API \'{}\' code {}/n'.format(
method.lower(), ierr))
return False
return True
def savecaseas(self, path):
ierr = psspy.save(path)
if ierr:
raise Warning(
'Case not saved. API \'save\' error code {}/n'.format(ierr))
else:
return True
###############################################################################
#### create, append, and complete file methods create external files which ####
#### are required by PSS/E to perform certain functions (e.g. dfax, tltg). ####
## The files are tracked in self.__internally_created_files__ and deleted on ##
############################## instance deletion ##############################
###############################################################################
def create_sid(self, sid=0, buslist=[], arealist=[], filepath=''):
"""Creates a subsystem from buses and/or areas. From what I can tell,
this subsystem definition cannot be used like a *.sub file (e.g. to
create a DFAX), but can be used as an input to other APIs."""
if sid not in xrange(11):
raise ValueError(
'{} is not a valid subsystem ID. SIDs must be an integer in the range 0-10 (leaving 11 for internal method use).')
ierr = psspy.bsys(sid=sid, numbus=len(buslist), buses=buslist,
numarea=len(arealist), areas=arealist)
if ierr:
self.error_message += 'Error defining subsystem {}. API \'bsys\' error code {}.'.format(
sid, ierr)
return False
if filepath:
ierr = psspy.bsysmem(sid=sid, sfile=filepath)
if ierr:
self.error_message += 'Error recording subsystem {}. API \'bsysmem\' error code {}'.format(
sid, ierr)
return False
self.__internally_created_files__ += filepath
return True
def create_subfile(self, filepath):
"""Creates a subsystem file from buses and/or areas."""
text = 'COM\nCOM Subystem file created through pypsse \nCOM\n'
with open(filepath, 'w') as f:
f.write(text)
self.__internally_created_files__ += filepath
return True
def append_subfile(self, filepath, subname, buslist=[], arealist=[],
partlist=[]):
"""Appends a subsystem to an existing subsystem file from buses and/or areas."""
text = 'SUBSYSTEM \'{}\'\n'.format(subname)
for b in buslist:
text += '\tBUS {}\n'.format(b)
if partlist:
if len(partlist) == len(buslist):
text += '\tPARTICIPATE\n'
for n in xrange(len(partlist)):
text += '\t\tBUS {} {}\n'.format(buslist[n], partlist[n])
text += '\tEND\n'
else:
raise ValueError(
'Participation factor list is length {} and bus list is length {}. These must be the same length.'.format(
len(partlist), len(buslist)))
for a in arealist:
text += '\tAREA {}\n'.format(a)
text += 'END\n'
with open(filepath, 'a') as f:
f.write(text)
return True
def create_confile(self, filepath):
text = 'COM\nCOM Contingency file created through pypsse \nCOM\n'
with open(filepath, 'w') as f:
f.write(text)
self.__internally_created_files__ += filepath
return True
def append_confile(self, filepath, subname, desc='SINGLE',
element='BRANCH'):
text = desc + ' ' + element + ' IN SUBSYSTEM ' + subname + '\n'
with open(filepath, 'a') as f:
f.write(text)
return True
def create_monfile(self, filepath):
text = 'COM\nCOM Monitored element file created through pypsse \nCOM\n'
with open(filepath, 'w') as f:
f.write(text)
self.__internally_created_files__ += filepath
return True
def append_monfile(self, filepath, sublist, midtext='BRANCHES IN',
fintext=''):
text = '\n'
for s in sublist:
text += 'MONITOR {} SUBSYSTEM \'{}\' {}\n'.format(midtext, s,
fintext)
with open(filepath, 'a') as f:
f.write(text)
return True
def complete_file(self, filepath):
"""Completes the file by adding END"""
text = '\nEND\n'
with open(filepath, 'a') as f:
f.write(text)
return True
def create_dfax(self, filepath, subfilepath, monfilepath, confilepath,
options=[_i, _i]):
ierr = psspy.dfax(options, subfilepath, monfilepath, confilepath,
filepath)
if ierr:
self.error_message += 'Error creating Distribution Factor file. API \'dfax\' error code {}\n'.format(
ierr)
return False
self.__internally_created_files__ += filepath
return True
###############################################################################
#### exists methods return boolean True if specified member exists in that ####
################################### data family ###############################
###############################################################################
def bus_exists(self, ibus):
"""Returns boolean value."""
return psspy.busexs(ibus) == 0
def area_exists(self, areanum):
return False
def owner_exists(self, ownernum):
return False
def branch_exists(self, ibus=0, jbus=0):
"""Returns boolean value."""
if self.bus_exists(ibus) and self.bus_exists(jbus):
ierr = psspy.bsys(sid=11, numbus=2, buses=[ibus, jbus])
if not ierr:
df = self.get_multiple_branch_data(sid=11,
datafields=['STATUS'])
if not df.dropna().empty:
return True
else:
return False
else:
self.error_message += 'Error creating subsystem for buses {} and {}. API \'bsys\' code {}/n'.format(
ibus, jbus, ierr)
return None
def load_exists(self, loadbusnum):
"""Returns boolean value."""
fields = ['NUMBER', 'STATUS']
ierr, arr = psspy.alodbusint(sid=-1, flag=4, string=fields)
if not ierr:
return loadbusnum in arr[0]
else:
self.error_message += 'Error retrieving load bus data. API \'alodbusint\' code {}/n'.format(
ierr)
return None
def machine_exists(self, machbusnum):
"""Returns boolean value."""
ierr, arr = psspy.amachint(sid=-1, flag=4, string=['NUMBER', 'STATUS'])
if not ierr:
return machbusnum in arr[0]
else:
self.error_message += 'Error retrieving machine buses. API \'amachint\' code {}/n'.format(
ierr)
return None
###############################################################################
###### get_single methods pull data for a single element for the bus or #######
############################ branch data family ###############################
###############################################################################
def get_single_bus_data(self, ibus=0, datafields=[], other=None):
"""Returns a series of bus data with field names as indices. If the
field is invalid, returns NaN for that index."""
if not datafields:
for k in self.BUS_FIELDS.keys():
datafields += self.BUS_FIELDS[k]
s = pd.Series(np.empty(len(datafields)).fill(np.nan), datafields)
if not ibus:
return s
for fld in datafields:
dtype = None
app = None
if fld in self.BUS_FIELDS['Real']:
app = psspy.busdat
dtype = float
elif fld in self.BUS_FIELDS['Integer']:
app = psspy.busint
dtype = int
elif fld in self.BUS_FIELDS['Complex']:
app = psspy.busdt1
dtype = float
if not other:
other = 'NOM'
else:
continue
if not other:
ierr, val = app(ibus, fld)
else:
ierr, val = app(ibus, fld, other)
if not ierr:
try:
s[fld] = dtype(val)
except Exception as e:
self.error_message += 'Error adding bus {} {} data series to dataframe: {}'.format(
ibus, fld, str(e))
else:
self.error_message += 'Error retrieving bus {} {} data. API \'{}\' code {}/n'.format(
ibus, fld, str(app).split(' ')[1], ierr)
return s
def get_single_branch_data(self, ibus=0, jbus=0, ckt='1', datafields=[]):
"""Returns branch data as a series with field names as indexes. If the
field is invalid, returns NaN for that index."""
if not datafields:
for k in self.BRN_FIELDS.keys():
datafields += self.BRN_FIELDS[k]
s = pd.Series(np.nan, datafields)
for fld in datafields:
dtype = None
app = None
if fld in self.BRN_FIELDS['Real']:
app = psspy.brndat
dtype = float
elif fld in self.BRN_FIELDS['Complex']:
app = psspy.brndt2
dtype = float
elif fld in self.BRN_FIELDS['Integer']:
app = psspy.brnint
dtype = int
elif fld in self.BRN_FIELDS['Miscellaneous']:
app = psspy.brnmsc
dtype = str
else:
continue
ierr, val = app(ibus, jbus, ckt, fld)
if not ierr:
try:
s[fld] = dtype(val)
except Exception as e:
self.error_message += 'Error adding branch {}-{} {} data series to dataframe: {}'.format(
ibus, jbus, fld, str(e))
else:
self.error_message += 'Error retrieving data for branch {}-{} {}. API \'{}\' code {}/n'.format(
ibus, jbus, fld.lower(), str(app).split(' ')[1], ierr)
return s
###############################################################################
##### get_multiple methods are the prefered methods for pulling case data #####
###############################################################################
def __dtype_map__(self, psse_dtype='C'):
"""Internal function maps between PSSE indicators of datatypes and
Python data types"""
if psse_dtype == 'I':
return int
elif psse_dtype == 'R':
return float
elif psse_dtype == 'X':
return str
elif psse_dtype == 'C':
return str
else:
return None
def __add_arr__(self, df, arrapp, colname, dtype=str, *args, **kwargs):
"""Internal function combines psse array API (arrapp) results with existing dataframe.
The kwargs are for the arrapp."""
ierr, arr = arrapp(*args, **kwargs)
data = arr[0]
if dtype == str and data is not None:
data = [str(x).strip() for x in data]
if ierr:
self.error_message += 'Error retrieving {} data: \nAPI \'{}\' error code {}.\n'.format(
colname, str(arrapp), ierr)
return df.copy()
if len(df.index) != len(data):
raise ValueError(
'Dataframe must be the same length as the array results. Dataframe length: {}. Array length: {}.'.format(
len(df.index), len(arr[0])))
try:
df[colname] = pd.Series(index=df.index, data=data, dtype=dtype)
except Exception as e:
self.error_message += 'Error adding {} data series to dataframe: {}'.format(
colname, str(e))
print(data)
return df.copy()
def get_multiple_bus_data(self, sid=None, ibuslist=[], datafields=[],
flag=2):
"""Returns a dataframe of bus data for buses in the specified SID or bus list. If the field is invalid, returns NaN for that column."""
if not datafields:
for k in self.A_BUS_FIELDS.keys():
datafields += self.A_BUS_FIELDS[k]
if sid and ibuslist:
print('Both sid and busnumlist were provided. Only using sid.')
if not sid:
sid = 11
ierr = psspy.bsys(sid=sid, numbus=len(ibuslist), buses=ibuslist)
if ierr:
self.error_message += 'Bus system not created for {}. API \'bsys\' error code {}.'.format(
ibuslist, ierr)
return pd.DataFrame()
df_sid = self.get_multiple_bus_data(sid=sid, datafields=datafields,
flag=flag)
df = pd.DataFrame(index=ibuslist).join(df_sid, how='left')
elif sid:
ierr, ibuslist = psspy.abusint(sid=sid, flag=flag, string='NUMBER')
ibuslist = ibuslist[0]
df = pd.DataFrame(index=ibuslist, data=np.empty(
(len(ibuslist), len(datafields))).fill(np.nan),
columns=datafields)
dtypes = psspy.abustypes(datafields)[1]
for n in xrange(len(datafields)):
if dtypes[n] == 'I':
app = psspy.abusint
elif dtypes[n] == 'R':
app = psspy.abusreal
elif dtypes[n] == 'X':
app = psspy.abuscplx
elif dtypes[n] == 'C':
app = psspy.abuschar
else:
continue
d = self.__dtype_map__(dtypes[n])
fld = datafields[n]
df = self.__add_arr__(df, app, fld, d, sid=sid, flag=flag,
string=fld)
else:
df = pd.DataFrame(columns=datafields)
df.index.name = 'NUMBER'
return df
def get_multiple_branch_data(self, sid=None, ibuslist=[], jbuslist=[],
cktlist=[], datafields=[], flag=4):
"""Returns a dataframe of branch data for branches in the specified SID or bus lists. If the field is invalid, returns NaN for that column."""
# data check
if len(ibuslist) != len(jbuslist) or len(jbuslist) != len(cktlist):
raise ValueError(
'Dimensions of ibuslist, jbuslist, and cktlist must be the same')
if not datafields:
for k in self.A_BRN_FIELDS.keys():
datafields += self.A_BRN_FIELDS[k]
for c in ['FROMNUMBER', 'TONUMBER', 'ID']:
if c not in datafields:
datafields.append(c)
if sid and ibuslist:
print('Both sid and busnumlist were provided. Only using sid.')
# results for specified branches
if not sid and ibuslist:
sid = 11
sysbuslist = ibuslist
sysbuslist = sysbuslist + [x for x in jbuslist if
x not in sysbuslist]
ierr = psspy.bsys(sid=sid, numbus=len(sysbuslist), buses=sysbuslist)
if ierr:
self.error_message += 'Bus system not created. API \'bsys\' error code {}.'.format(
ierr)
return pd.DataFrame()
# get entire sid branch info and include to as from and from as to
df_sid = self.get_multiple_branch_data(sid=sid,
datafields=datafields,
flag=flag)
df_sid_2 = df_sid.copy()
df_sid_2['FROMNUMBER'] = df_sid['TONUMBER']
df_sid_2['TONUMBER'] = df_sid['FROMNUMBER']
df_sid = df_sid.append(df_sid_2)
df = pd.DataFrame(index=xrange(len(ibuslist)))
df['FROMNUMBER'] = pd.Series(index=df.index, data=ibuslist,
dtype=int)
df['TONUMBER'] = pd.Series(index=df.index, data=jbuslist, dtype=int)
df['ID'] = pd.Series(index=df.index, data=cktlist, dtype=str)
df = df.merge(df_sid, how='left',
on=['FROMNUMBER', 'TONUMBER', 'ID'])
# results for specified sid
elif sid:
ierr, ibuslist = psspy.abrnint(sid=sid, flag=flag,
string='FROMNUMBER')
ibuslist = ibuslist[0]
if ibuslist:
df = pd.DataFrame(index=xrange(len(ibuslist)), data=np.empty(
(len(ibuslist), len(datafields))).fill(np.nan),
columns=datafields)
dtypes = psspy.abrntypes(datafields)[1]
for n in xrange(len(datafields)):
if dtypes[n] == 'I':
app = psspy.abrnint
elif dtypes[n] == 'R':
app = psspy.abrnreal
elif dtypes[n] == 'X':
app = psspy.abrncplx
elif dtypes[n] == 'C':
app = psspy.abrnchar
else:
continue
d = self.__dtype_map__(dtypes[n])
fld = datafields[n]
df = self.__add_arr__(df, app, fld, d, sid=sid, flag=flag,
string=fld)
else:
df = pd.DataFrame(columns=datafields)
else:
df = pd.DataFrame(columns=datafields)
return df
def get_multiple_trn_data(self, sid=None, ibuslist=[], jbuslist=[],
cktlist=[], datafields=[], flag=4):
"""Returns a dataframe of branch data for branches in the specified SID or bus lists. If the field is invalid, returns NaN for that column."""
# data check
if len(ibuslist) != len(jbuslist) or len(jbuslist) != len(cktlist):
raise ValueError(
'Dimensions of ibuslist, jbuslist, and cktlist must be the same')
if not datafields:
for k in self.A_BRN_FIELDS.keys():
datafields += self.A_BRN_FIELDS[k]
for c in ['FROMNUMBER', 'TONUMBER', 'ID']:
if c not in datafields:
datafields.append(c)
if sid and ibuslist:
print('Both sid and busnumlist were provided. Only using sid.')
# results for specified branches
if not sid and ibuslist:
sid = 11
sysbuslist = ibuslist
sysbuslist = sysbuslist + [x for x in jbuslist if
x not in sysbuslist]
ierr = psspy.bsys(sid=sid, numbus=len(sysbuslist), buses=sysbuslist)
if ierr:
self.error_message += 'Bus system not created. API \'bsys\' error code {}.'.format(
ierr)
return pd.DataFrame()
# get entire sid branch info and include to as from and from as to
df_sid = self.get_multiple_trn_data(sid=sid, datafields=datafields,
flag=flag)
df_sid_2 = df_sid.copy()
df_sid_2['FROMNUMBER'] = df_sid['TONUMBER']
df_sid_2['TONUMBER'] = df_sid['FROMNUMBER']
df_sid = df_sid.append(df_sid_2)
df = pd.DataFrame(index=xrange(len(ibuslist)))
df['FROMNUMBER'] = pd.Series(index=df.index, data=ibuslist,
dtype=int)
df['TONUMBER'] = pd.Series(index=df.index, data=jbuslist, dtype=int)
df['ID'] = pd.Series(index=df.index, data=cktlist, dtype=str)
df = df.merge(df_sid, how='left',
on=['FROMNUMBER', 'TONUMBER', 'ID'])
# results for specified sid
elif sid:
ibuslist = psspy.atrnint(sid=sid, flag=flag, string='FROMNUMBER')[1]
ibuslist = ibuslist[0]
if ibuslist:
df = pd.DataFrame(index=xrange(len(ibuslist)), data=np.empty(
(len(ibuslist), len(datafields))).fill(np.nan),
columns=datafields)
dtypes = psspy.atrntypes(datafields)
for n in xrange(len(datafields)):
if dtypes[n] == 'I':
app = psspy.atrnint
elif dtypes[n] == 'R':
app = psspy.atrnreal
elif dtypes[n] == 'X':
app = psspy.atrncplx
elif dtypes[n] == 'C':
app = psspy.atrnchar
else:
continue
d = self.__dtype_map__(dtypes[n])
fld = datafields[n]
df = self.__add_arr__(df, app, fld, d, sid=sid, flag=flag,
string=fld)
else:
df = pd.DataFrame(columns=datafields)
else:
df = pd.DataFrame(columns=datafields)
return df
def get_multiple_tr3_data(self, sid=None, ibuslist=[], jbuslist=[],
kbuslist=[], datafields=[], flag=2):
"""Returns a dataframe of three winding transformers as specified in the buslist or in the SID"""
# data check
if len(ibuslist) != len(jbuslist) or len(jbuslist) != len(kbuslist):
raise ValueError(
'Dimensions of ibuslist, jbuslist, and cktlist must be the same')
if not datafields:
for k in self.A_TR3_FIELDS.keys():
datafields += self.A_TR3_FIELDS[k]
for c in ['WIND1NUMBER', 'WIND2NUMBER', 'WIND3NUMBER', 'ID']:
if c not in datafields:
datafields.append(c)
if sid and ibuslist:
print('Both sid and busnumlist were provided. Only using sid.')
# results for specified branches
if not sid and (ibuslist and jbuslist and kbuslist):
sid = 11
sysbuslist = ibuslist
sysbuslist = sysbuslist + [x for x in jbuslist if
x not in sysbuslist]
sysbuslist = sysbuslist + [x for x in kbuslist if
x not in sysbuslist]
ierr = psspy.bsys(sid=sid, numbus=len(sysbuslist), buses=sysbuslist)
if ierr:
self.error_message += 'Bus system not created. API \'bsys\' error code {}.'.format(
ierr)
return pd.DataFrame()
# get entire sid branch info and include to as from and from as to
df = self.get_multiple_tr3_data(sid=sid, datafields=datafields)
# results for specified sid
elif sid:
ierr, ibuslist = psspy.atr3int(sid=sid, flag=flag,
string='WIND1NUMBER')
ibuslist = ibuslist[0]
if ibuslist:
df = pd.DataFrame(index=xrange(len(ibuslist)), data=np.empty(
(len(ibuslist), len(datafields))).fill(np.nan),
columns=datafields)
dtypes = psspy.atr3types(datafields)[1]
for n in xrange(len(datafields)):
if dtypes[n] == 'I':
app = psspy.atr3int
elif dtypes[n] == 'R':
app = psspy.atr3real
elif dtypes[n] == 'X':
app = psspy.atr3cplx
elif dtypes[n] == 'C':
app = psspy.atr3char
else:
continue
d = self.__dtype_map__(dtypes[n])
fld = datafields[n]
df = self.__add_arr__(df, app, fld, d, sid=sid, flag=flag,
string=fld)
else:
df = pd.DataFrame(columns=datafields)
else:
df = pd.DataFrame(columns=datafields)
return df
def get_multiple_machine_data(self, sid=None, buslist=[], datafields=[],
flag=4):
"""Returns a dataframe of machine data for machines in the specified SID or bus list. If the field is invalid, returns NaN for that column."""
if not datafields:
for k in self.A_MACH_FIELDS.keys():
datafields += self.A_MACH_FIELDS[k]
if sid and buslist:
print('Both sid and buslist were provided. Only using sid.')
if buslist and not sid:
sid = 11
ierr = psspy.bsys(sid=sid, numbus=len(buslist), buses=buslist)
if ierr:
self.error_message += 'Bus system not created for {}. API \'bsys\' error code {}.'.format(
buslist, ierr)
return pd.DataFrame()
df_sid = self.get_multiple_machine_data(sid=sid,
datafields=datafields)
df = pd.DataFrame(index=buslist).join(df_sid, how='left')
elif sid:
ierr, buslist = psspy.amachint(sid=sid, flag=flag, string='NUMBER')
buslist = buslist[0]
df = pd.DataFrame(index=buslist, data=np.empty(
(len(buslist), len(datafields))).fill(np.nan),
columns=datafields)
ierr, dtypes = psspy.amachtypes(datafields)
while ierr in range(1, len(datafields) + 1):
self.error_message += 'Error determining data types: API \'amachtypes\' does not recognize datafield {}. Proceeding without this field.'.format(
datafields[ierr - 1])
datafields.remove(datafields[ierr - 1])
ierr, dtypes = psspy.amachtypes(datafields)
for n in xrange(len(datafields)):
if dtypes[n] == 'I':
app = psspy.amachint
elif dtypes[n] == 'R':
app = psspy.amachreal
elif dtypes[n] == 'X':
app = psspy.amachcplx
elif dtypes[n] == 'C':
app = psspy.amachchar
else:
continue
d = self.__dtype_map__(dtypes[n])
fld = datafields[n]
df = self.__add_arr__(df, app, fld, d, sid=sid, flag=flag,
string=fld)
else:
df = pd.DataFrame(columns=datafields)
df.index.name = 'NUMBER'
return df
def get_multiple_load_data(self, sid=None, buslist=[], datafields=[],
flag=4):
"""Returns a dataframe of load data for loads in the specified SID or bus list. If the field is invalid, returns NaN for that column."""
if not datafields:
for k in self.A_LOAD_FIELDS.keys():
datafields += self.A_LOAD_FIELDS[k]
if sid and buslist:
print('Both sid and buslist were provided. Only using sid.')
if not sid and buslist:
sid = 11
ierr = psspy.bsys(sid=sid, numbus=len(buslist), buses=buslist)
if ierr:
self.error_message += 'Bus system not created for {}. API \'bsys\' error code {}.'.format(
buslist, ierr)
return pd.DataFrame()
df_sid = self.get_multiple_load_data(sid=sid, datafields=datafields)
df = pd.DataFrame(index=buslist).join(df_sid, how='left')
elif sid:
ierr, buslist = psspy.amachint(sid=sid, flag=flag, string='NUMBER')
buslist = buslist[0]
df = pd.DataFrame(index=buslist, data=np.empty(
(len(buslist), len(datafields))).fill(np.nan),
columns=datafields)
dtypes = psspy.aloadtypes(datafields)[1]
for n in xrange(len(datafields)):
if dtypes[n] == 'I':
app = psspy.aloadint
elif dtypes[n] == 'R':
app = psspy.aloadreal
elif dtypes[n] == 'X':
app = psspy.aloadcplx
elif dtypes[n] == 'C':
app = psspy.aloadchar
else:
continue
d = self.__dtype_map__(dtypes[n])