1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 """Loads a PYPOWER case dictionary.
18 """
19
20 import sys
21
22 from os.path import basename, splitext, exists
23
24 from copy import deepcopy
25
26 from numpy import array, zeros, ones, c_
27
28 from scipy.io import loadmat
29
30 from pypower.idx_gen import PMIN, MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, APF
31 from pypower.idx_brch import PF, QF, PT, QT, MU_SF, MU_ST, BR_STATUS
32
33
34 -def loadcase(casefile,
35 return_as_obj=True, expect_gencost=True, expect_areas=True):
36 """Returns the individual data matrices or an dict containing them
37 as values.
38
39 Here C{casefile} is either a dict containing the keys C{baseMVA}, C{bus},
40 C{gen}, C{branch}, C{areas}, C{gencost}, or a string containing the name
41 of the file. If C{casefile} contains the extension '.mat' or '.py', then
42 the explicit file is searched. If C{casefile} containts no extension, then
43 L{loadcase} looks for a '.mat' file first, then for a '.py' file. If the
44 file does not exist or doesn't define all matrices, the function returns
45 an exit code as follows:
46
47 0. all variables successfully defined
48 1. input argument is not a string or dict
49 2. specified extension-less file name does not exist
50 3. specified .mat file does not exist
51 4. specified .py file does not exist
52 5. specified file fails to define all matrices or contains syntax
53 error
54
55 If the input data is not a dict containing a 'version' key, it is
56 assumed to be a PYPOWER case file in version 1 format, and will be
57 converted to version 2 format.
58
59 @author: Carlos E. Murillo-Sanchez (PSERC Cornell & Universidad
60 Autonoma de Manizales)
61 @author: Ray Zimmerman (PSERC Cornell)
62 @author: Richard Lincoln
63 """
64 if return_as_obj == True:
65 expect_gencost = False
66 expect_areas = False
67
68 info = 0
69
70
71 if isinstance(casefile, basestring):
72
73 if casefile.endswith(('.py', '.mat')):
74 rootname, extension = splitext(casefile)
75 fname = basename(rootname)
76 else:
77
78 rootname = casefile
79 if exists(casefile + '.mat'):
80 extension = '.mat'
81 elif exists(casefile + '.py'):
82 extension = '.py'
83 else:
84 info = 2
85 fname = basename(rootname)
86
87 lasterr = ''
88
89
90 if info == 0:
91 if extension == '.mat':
92 try:
93 d = loadmat(rootname + extension, struct_as_record=True)
94 if 'ppc' in d or 'mpc' in d:
95 if 'ppc' in d:
96 struct = d['ppc']
97 else:
98 struct = d['mpc']
99 val = struct[0, 0]
100
101 s = {}
102 for a in val.dtype.names:
103 s[a] = val[a]
104 else:
105 d['version'] = '1'
106
107 s = {}
108 for k, v in d.iteritems():
109 s[k] = v
110
111 s['baseMVA'] = s['baseMVA'][0]
112
113 except IOError, e:
114 info = 3
115 lasterr = str(e)
116 elif extension == '.py':
117 try:
118 execfile(rootname + extension)
119
120 try:
121 s = eval(fname)()
122 except ValueError, e:
123 info = 4
124 lasterr = str(e)
125
126 if info == 0 and not isinstance(s, dict):
127 s = {}
128 s['version'] = '1'
129 if expect_gencost:
130 try:
131 s['baseMVA'], s['bus'], s['gen'], s['branch'], \
132 s['areas'], s['gencost'] = eval(fname)()
133 except IOError, e:
134 info = 4
135 lasterr = str(e)
136 else:
137 if return_as_obj:
138 try:
139 s['baseMVA'], s['bus'], s['gen'], \
140 s['branch'], s['areas'], \
141 s['gencost'] = eval(fname)()
142 except ValueError, e:
143 try:
144 s['baseMVA'], s['bus'], s['gen'], \
145 s['branch'] = eval(fname)()
146 except ValueError, e:
147 info = 4
148 lasterr = str(e)
149 else:
150 try:
151 s['baseMVA'], s['bus'], s['gen'], \
152 s['branch'] = eval(fname)()
153 except ValueError, e:
154 info = 4
155 lasterr = str(e)
156
157 except IOError, e:
158 info = 4
159 lasterr = str(e)
160
161
162 if info == 4 and exists(rootname + '.py'):
163 info = 5
164 err5 = lasterr
165
166 elif isinstance(casefile, dict):
167 s = deepcopy(casefile)
168 else:
169 info = 1
170
171
172 if info == 0:
173
174 if (s['baseMVA'] == None or s['bus'] == None \
175 or s['gen'] == None or s['branch'] == None) or \
176 (expect_gencost and s['gencost'] == None) or \
177 (expect_areas and s['areas'] == None):
178 info = 5
179 err5 = 'missing data'
180 else:
181
182 if hasattr(s, 'areas') and (len(s['areas']) == 0) and (not expect_areas):
183 del s['areas']
184
185
186 ppc = deepcopy(s)
187 if not hasattr(ppc, 'version'):
188 if ppc['gen'].shape[1] < 21:
189 ppc['version'] = '1'
190 else:
191 ppc['version'] = '2'
192
193 if (ppc['version'] == '1'):
194
195 ppc['gen'], ppc['branch'] = ppc_1to2(ppc['gen'], ppc['branch']);
196 ppc['version'] = '2'
197
198 if info == 0:
199 if return_as_obj:
200 return ppc
201 else:
202 result = [ppc['baseMVA'], ppc['bus'], ppc['gen'], ppc['branch']]
203 if expect_gencost:
204 if expect_areas:
205 result.extend([ppc['areas'], ppc['gencost']])
206 else:
207 result.extend([ppc['gencost']])
208 return result
209 else:
210 if info == 1:
211 sys.stderr.write('Input arg should be a case or a string '
212 'containing a filename\n')
213 elif info == 2:
214 sys.stderr.write('Specified case not a valid file\n')
215 elif info == 3:
216 sys.stderr.write('Specified MAT file does not exist\n')
217 elif info == 4:
218 sys.stderr.write('Specified Python file does not exist\n')
219 elif info == 5:
220 sys.stderr.write('Syntax error or undefined data '
221 'matrix(ices) in the file\n')
222 else:
223 sys.stderr.write('Unknown error encountered loading case.\n')
224
225 sys.stderr.write(lasterr + '\n')
226
227 return info
228
229
231
232
233 if gen.shape[1] >= APF:
234 sys.stderr.write('ppc_1to2: gen matrix appears to already be in '
235 'version 2 format\n')
236 return gen, branch
237
238 shift = MU_PMAX - PMIN - 1
239 tmp = array([MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN]) - shift
240 mu_Pmax, mu_Pmin, mu_Qmax, mu_Qmin = tmp
241
242
243 tmp = zeros((gen.shape[0], shift))
244 if gen.shape[1] >= mu_Qmin:
245 gen = c_[ gen[:, 0:PMIN + 1], tmp, gen[:, mu_Pmax:mu_Qmin] ]
246 else:
247 gen = c_[ gen[:, 0:PMIN + 1], tmp ]
248
249
250
251 shift = PF - BR_STATUS - 1
252 tmp = array([PF, QF, PT, QT, MU_SF, MU_ST]) - shift
253 Pf, Qf, Pt, Qt, mu_Sf, mu_St = tmp
254
255
256 tmp = ones((branch.shape[0], 1)) * array([-360, 360])
257 tmp2 = zeros((branch.shape[0], 2))
258 if branch.shape[1] >= mu_St - 1:
259 branch = c_[ branch[:, 0:BR_STATUS + 1], tmp, branch[:, PF - 1:MU_ST + 1], tmp2 ]
260 elif branch.shape[1] >= QT - 1:
261 branch = c_[ branch[:, 0:BR_STATUS + 1], tmp, branch[:, PF - 1:QT + 1] ]
262 else:
263 branch = c_[ branch[:, 0:BR_STATUS + 1], tmp ]
264
265 return gen, branch
266