Package pypower :: Module loadcase
[hide private]
[frames] | no frames]

Source Code for Module pypower.loadcase

  1  # Copyright (C) 1996-2011 Power System Engineering Research Center (PSERC) 
  2  # Copyright (C) 2011 Richard Lincoln 
  3  # 
  4  # PYPOWER is free software: you can redistribute it and/or modify 
  5  # it under the terms of the GNU General Public License as published 
  6  # by the Free Software Foundation, either version 3 of the License, 
  7  # or (at your option) any later version. 
  8  # 
  9  # PYPOWER is distributed in the hope that it will be useful, 
 10  # but WITHOUT ANY WARRANTY without even the implied warranty of 
 11  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 12  # GNU General Public License for more details. 
 13  # 
 14  # You should have received a copy of the GNU General Public License 
 15  # along with PYPOWER. If not, see <http://www.gnu.org/licenses/>. 
 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 # read data into case object 71 if isinstance(casefile, basestring): 72 # check for explicit extension 73 if casefile.endswith(('.py', '.mat')): 74 rootname, extension = splitext(casefile) 75 fname = basename(rootname) 76 else: 77 # set extension if not specified explicitly 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 ## attempt to read file 90 if info == 0: 91 if extension == '.mat': ## from MAT file 92 try: 93 d = loadmat(rootname + extension, struct_as_record=True) 94 if 'ppc' in d or 'mpc' in d: ## it's a MAT/PYPOWER dict 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: ## individual data matrices 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] # convert array to float 112 113 except IOError, e: 114 info = 3 115 lasterr = str(e) 116 elif extension == '.py': ## from Python file 117 try: 118 execfile(rootname + extension) 119 120 try: ## assume it returns an object 121 s = eval(fname)() 122 except ValueError, e: 123 info = 4 124 lasterr = str(e) 125 ## if not try individual data matrices 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 # check contents of dict 172 if info == 0: 173 # check for required keys 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 ## missing some expected fields 179 err5 = 'missing data' 180 else: 181 ## remove empty areas if not needed 182 if hasattr(s, 'areas') and (len(s['areas']) == 0) and (not expect_areas): 183 del s['areas'] 184 185 ## all fields present, copy to ppc 186 ppc = deepcopy(s) 187 if not hasattr(ppc, 'version'): ## hmm, struct with no 'version' field 188 if ppc['gen'].shape[1] < 21: ## version 2 has 21 or 25 cols 189 ppc['version'] = '1' 190 else: 191 ppc['version'] = '2' 192 193 if (ppc['version'] == '1'): 194 # convert from version 1 to version 2 195 ppc['gen'], ppc['branch'] = ppc_1to2(ppc['gen'], ppc['branch']); 196 ppc['version'] = '2' 197 198 if info == 0: # no errors 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: # error encountered 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
230 -def ppc_1to2(gen, branch):
231 ##----- gen ----- 232 ## use the version 1 values for column names 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 ## add extra columns to gen 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 ##----- branch ----- 250 ## use the version 1 values for column names 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 ## add extra columns to branch 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