Coverage for ppedit/_psse.py: 87.5%
389 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 17:40 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 17:40 +0000
1"""PSS/E RAW case reader
3`parse_raw(text)` converts a Siemens PTI PSS/E power flow case (`.raw`,
4revisions 23 through 35) into a PYPOWER `ppc` dict of plain lists, plus
5notes about the data that was not converted. `ppedit.Case.load` calls it
6for `.raw` files; PSS/E is an input format only.
8The conversion follows MATPOWER's `psse2mpc` (`psse_parse`,
9`psse_convert`, `psse_convert_xfmr`, `psse_convert_hvdc`; MATPOWER is
10BSD-3-Clause licensed, https://matpower.org), with these additions:
12 - revisions 34 and 35 (system-wide data, 12 branch ratings and names,
13 generator `NREG`, at the end of the record in 34 and after `IREG` in
14 35, switched shunt `ID` in 35);
15 - `@!` field name lines, when a section has one, locate the fields of
16 single-line records (buses, loads, shunts, generators, branches,
17 switching devices) by name, so writers that order fields differently
18 are read correctly; without them the fields are taken by position;
19 - a generator that regulates another bus (`IREG`), which PYPOWER
20 cannot do, gets its own bus voltage in the case as `Vg` instead of
21 `VS`, so a solved case solves to the same voltages (a note says how
22 many); a note also counts generators held at a reactive power limit,
23 since PYPOWER power flow holds `Vg` there instead;
24 - out-of-service switched shunts (revision 32 and later) and fixed
25 shunts and loads are left out;
26 - closed in-service system switching devices (revision 34 and later)
27 become branches with their reactance `X` (default 0.0001 pu);
28 - a winding nominal voltage `NOMV` of 0 means the bus base voltage;
29 - 3-winding transformer star buses get the base voltage of the winding 1
30 bus (MATPOWER uses 1 kV).
32What the PYPOWER format cannot hold is reported in the notes and dropped:
33bus, branch and machine names, owners, transformer magnetizing admittance
34and impedance correction, remote voltage regulation, switched shunt
35blocks (the initial susceptance `BINIT` is kept), VSC and multi-terminal
36DC lines, FACTS devices, multi-section line groupings, zones and owners
37tables, inter-area transfers, GNE devices, induction machines and
38substation data. Constant current and constant admittance loads become
39constant power loads at the bus voltage in the case (as in `psse2mpc`).
40PSS/E has no cost data, so the case has no `gencost` rows.
41"""
43import math
44import re
46_EOS = re.compile(r"^\s*(Q|0)\s*(/.*)?$")
47_LABEL = re.compile(r"END\s+OF\s+(.*?)\s+DATA",re.I)
48_REV = re.compile(r"PSS(?:/|\(tm\))E-(\d+)",re.I)
49_STAR_VMAX,_STAR_VMIN = 1.1,0.9
51class RawError(ValueError):
52 """Raised for an unreadable PSS/E RAW file"""
54def _fields(line):
55 """Split a RAW record into fields (comma or blank separated, quoted text
56 kept as one field, `/` starts a comment); an empty field between two
57 commas is `""` (the default value)"""
58 out = []
59 started = False
60 i,n = 0,len(line)
61 while i < n:
62 c = line[i]
63 if c in " \t\r":
64 i += 1
65 elif c == ",":
66 if not started:
67 out.append("")
68 started = False
69 i += 1
70 elif c == "/":
71 break
72 elif c in "'\"":
73 j = i + 1
74 buf = []
75 while j < n: 75 ↛ 84line 75 didn't jump to line 84 because the condition on line 75 was always true
76 if line[j] == c:
77 if j + 1 < n and line[j+1] == c:
78 buf.append(c)
79 j += 2
80 continue
81 break
82 buf.append(line[j])
83 j += 1
84 out.append("".join(buf))
85 started = True
86 i = j + 1
87 else:
88 j = i
89 while j < n and line[j] not in " \t\r,/'\"":
90 j += 1
91 out.append(line[i:j])
92 started = True
93 i = j
94 return out
96class _Rec(list):
97 """One RAW record: fields addressed by 1-based column number"""
99 def num(self,k,default=0.0):
100 """Column `k` as a float (`default` if missing or empty)"""
101 if k > len(self) or self[k-1].strip() == "":
102 return default
103 text = self[k-1].strip().replace("D","E").replace("d","e")
104 try:
105 return float(text)
106 except ValueError as err:
107 raise RawError(f"'{self[k-1]}' is not a number "
108 f"(column {k} of '{','.join(self)}')") from err
110 def int(self,k,default=0):
111 """Column `k` as an int"""
112 return int(round(self.num(k,default)))
114def _field_names(line):
115 """Field names of an `@!` header line, upper case, without quotes or blanks"""
116 return [re.sub(r"[\s'\"]","",x).upper() for x in line.lstrip()[2:].split(",")]
118def _read(text):
119 """Return the header lines, the sections (lists of records), their
120 labels, and the field names of each section's first `@!` line (`None`
121 if it has none), as `psse_read` splits them"""
122 lines = re.split(r"\r\n|\n|\r",text)
123 header = []
124 while lines and len(header) < 3:
125 line = lines.pop(0)
126 if not line.lstrip().startswith("@!"):
127 header.append(line)
128 if len(header) < 3: 128 ↛ 129line 128 didn't jump to line 129 because the condition on line 128 was never true
129 raise RawError("too few lines for a PSS/E RAW file")
130 sections,labels,fields = [],[],[]
131 current,names = [],None
132 for line in lines:
133 if line.lstrip().startswith("@!"):
134 if not current and names is None:
135 names = _field_names(line)
136 elif _EOS.match(line):
137 sections.append(current)
138 fields.append(names)
139 match = _LABEL.search(line)
140 labels.append(match.group(1).upper() if match else "")
141 current,names = [],None
142 if line.lstrip().startswith("Q"):
143 break
144 elif line.strip():
145 current.append(line)
146 else:
147 if current:
148 sections.append(current)
149 fields.append(names)
150 labels.append("")
151 return header,sections,labels,fields
153def _order(rev,system_wide):
154 """Section names in file order for revision `rev`"""
155 out = []
156 if system_wide:
157 out.append("system-wide")
158 out.append("bus")
159 if rev >= 24: 159 ↛ 161line 159 didn't jump to line 161 because the condition on line 159 was always true
160 out.append("load")
161 if rev > 30: 161 ↛ 163line 161 didn't jump to line 163 because the condition on line 161 was always true
162 out.append("fixed shunt")
163 out += ["generator","branch"]
164 if rev >= 34:
165 out.append("system switching device")
166 out.append("transformer adjustment" if rev <= 27 else "transformer")
167 out += ["area","two-terminal dc"]
168 if rev > 28: 168 ↛ 170line 168 didn't jump to line 170 because the condition on line 168 was always true
169 out.append("voltage source converter")
170 if rev < 31: 170 ↛ 171line 170 didn't jump to line 171 because the condition on line 170 was never true
171 out.append("switched shunt")
172 out += ["impedance correction","multi-terminal dc","multi-section line","zone",
173 "inter-area transfer"]
174 if rev > 24: 174 ↛ 176line 174 didn't jump to line 176 because the condition on line 174 was always true
175 out.append("owner")
176 if rev > 25: 176 ↛ 178line 176 didn't jump to line 178 because the condition on line 176 was always true
177 out.append("facts device")
178 if rev > 30: 178 ↛ 180line 178 didn't jump to line 180 because the condition on line 178 was always true
179 out.append("switched shunt")
180 if rev > 31: 180 ↛ 182line 180 didn't jump to line 182 because the condition on line 180 was always true
181 out.append("gne device")
182 if rev > 32: 182 ↛ 184line 182 didn't jump to line 184 because the condition on line 182 was always true
183 out.append("induction machine")
184 if rev >= 35:
185 out.append("substation")
186 return out
188def parse_raw(text:str) -> tuple[dict,list[str]]:
189 """Convert PSS/E RAW text to a PYPOWER case
191 Arguments
192 ---------
194 - `text`: RAW file contents
196 Returns
197 -------
199 - `dict`: `ppc` dict (`version`, `baseMVA`, `bus`, `gen`, `branch`,
200 `dcline`; lists of rows in PYPOWER column order) and
201 `psse_revision`, the PSS/E revision the file was read as
203 - `list[str]`: notes on what was not converted
205 Exceptions
206 ----------
208 - `RawError`: the text is not a readable RAW case
209 """
210 # pylint: disable=too-many-locals,too-many-branches,too-many-statements
211 header,sections,labels,fields = _read(text)
212 head = _Rec(_fields(header[0]))
213 notes = []
214 sbase = head.num(2,0.0)
215 if sbase <= 0:
216 raise RawError("the first line has no valid system MVA base (SBASE); "
217 "is this a PSS/E RAW file?")
218 rev = head.int(3,0)
219 if not rev: 219 ↛ 220line 219 didn't jump to line 220 because the condition on line 219 was never true
220 match = _REV.search(header[0])
221 rev = int(match.group(1)) if match else 0
222 if not rev: 222 ↛ 223line 222 didn't jump to line 223 because the condition on line 222 was never true
223 rev = 23
224 notes.append(f"PSS/E revision not given; read as revision {rev}")
225 if rev < 23:
226 raise RawError(f"PSS/E revision {rev} is not supported (23 to 35)")
227 if rev > 35: 227 ↛ 228line 227 didn't jump to line 228 because the condition on line 227 was never true
228 notes.append(f"PSS/E revision {rev} is newer than 35; read as revision 35")
229 rev = 35
230 if head.int(1,0) != 0: 230 ↛ 231line 230 didn't jump to line 231 because the condition on line 230 was never true
231 notes.append(f"IC = {head.int(1,0)}: this may be a change case, not a base case")
232 system_wide = rev >= 34 or (bool(labels) and "SYSTEM" in labels[0])
233 names = _order(rev,system_wide)
234 data,heads = {},{}
235 for k,records in enumerate(sections):
236 if k >= len(names):
237 if records: 237 ↛ 238line 237 didn't jump to line 238 because the condition on line 237 was never true
238 notes.append(f"{len(sections)-len(names)} section(s) after the "
239 f"{names[-1]} data were not read")
240 break
241 data.setdefault(names[k],[]).append(records)
242 if fields[k] and names[k] not in heads:
243 heads[names[k]] = fields[k]
244 def columns(name,cols):
245 """1-based columns of the fields `cols` (name: (default column, aliases...))
246 in section `name`, from its `@!` field names when it has them"""
247 head = heads.get(name) if rev >= 31 else None
248 out = {}
249 for key,(col,*aliases) in cols.items():
250 found = [head.index(x)+1 for x in (key,*aliases) if head and x in head]
251 out[key] = found[0] if found else col
252 return out
253 def sect(name):
254 """Records of all sections called `name` (switched shunts may be in two places)"""
255 return [r for block in data.get(name,[]) for r in block]
256 def recs(name):
257 return [_Rec(_fields(x)) for x in sect(name)]
258 kept = {"system-wide","bus","load","fixed shunt","generator","branch",
259 "system switching device","transformer","area","two-terminal dc","switched shunt"}
260 skipped = [f"{len(sect(x))} {x}" for x in names if x not in kept and sect(x)]
261 if skipped:
262 notes.append("PSS/E data not converted (records): " + ", ".join(skipped))
264 # ----- buses -----
265 bus = []
266 nolimits = 0
267 bcols = columns("bus",{"BASKV":(3,),"IDE":(4,),"AREA":(5,),"ZONE":(6,),"VM":(8,),
268 "VA":(9,),"NVHI":(10,),"NVLO":(11,)})
269 for r in recs("bus"):
270 if rev < 24: # I,IDE,PL,QL,GL,BL,IA,VM,VA,'NAME',BASKV,ZONE 270 ↛ 271line 270 didn't jump to line 271 because the condition on line 270 was never true
271 row = [r.int(1),r.int(2,1),r.num(3),r.num(4),r.num(5),r.num(6),r.int(7,1),
272 r.num(8,1.0),r.num(9),r.num(11),r.int(12,1),None,None]
273 elif rev < 31: # I,'NAME',BASKV,IDE,GL,BL,AREA,ZONE,VM,VA,OWNER 273 ↛ 274line 273 didn't jump to line 274 because the condition on line 273 was never true
274 row = [r.int(1),r.int(4,1),0.0,0.0,r.num(5),r.num(6),r.int(7,1),
275 r.num(9,1.0),r.num(10),r.num(3),r.int(8,1),None,None]
276 else: # I,'NAME',BASKV,IDE,AREA,ZONE,OWNER,VM,VA,NVHI,NVLO,EVHI,EVLO
277 c = bcols
278 row = [r.int(1),r.int(c["IDE"],1),0.0,0.0,0.0,0.0,r.int(c["AREA"],1),
279 r.num(c["VM"],1.0),r.num(c["VA"]),r.num(c["BASKV"]),r.int(c["ZONE"],1),
280 r.num(c["NVHI"]) if len(r) >= c["NVHI"] and r[c["NVHI"]-1].strip() else None,
281 r.num(c["NVLO"]) if len(r) >= c["NVLO"] and r[c["NVLO"]-1].strip() else None]
282 if row[11] is None or row[12] is None:
283 nolimits += 1
284 row[11] = _STAR_VMAX if row[11] is None else row[11]
285 row[12] = _STAR_VMIN if row[12] is None else row[12]
286 if row[1] not in (1,2,3,4): 286 ↛ 287line 286 didn't jump to line 287 because the condition on line 286 was never true
287 row[1] = 4 if row[1] < 0 else 1
288 bus.append(row)
289 if not bus:
290 raise RawError("the file has no bus data")
291 if nolimits:
292 notes.append(f"{nolimits} bus(es) have no voltage limits; "
293 f"using Vmin = {_STAR_VMIN:g} pu, Vmax = {_STAR_VMAX:g} pu")
294 bus.sort(key=lambda x:x[0])
295 index = {}
296 for n,row in enumerate(bus):
297 if row[0] in index: 297 ↛ 298line 297 didn't jump to line 298 because the condition on line 297 was never true
298 raise RawError(f"bus {row[0]} is defined more than once")
299 index[row[0]] = n
300 def at(number,what):
301 if number not in index:
302 raise RawError(f"{what} refers to bus {number}, which is not defined")
303 return bus[index[number]]
305 # ----- loads (I,ID,STATUS,AREA,ZONE,PL,QL,IP,IQ,YP,YQ,...) -----
306 c = columns("load",{"STAT":(3,"STATUS"),"PL":(6,),"QL":(7,),"IP":(8,),"IQ":(9,),
307 "YP":(10,),"YQ":(11,)})
308 for r in recs("load"):
309 if r.int(c["STAT"],1) != 1:
310 continue
311 b = at(r.int(1),"a load")
312 vm = b[7]
313 b[2] += r.num(c["PL"]) + r.num(c["IP"])*vm + r.num(c["YP"])*vm**2
314 b[3] += r.num(c["QL"]) + r.num(c["IQ"])*vm - r.num(c["YQ"])*vm**2
316 # ----- fixed shunts (I,ID,STATUS,GL,BL) -----
317 c = columns("fixed shunt",{"STATUS":(3,"STAT"),"GL":(4,),"BL":(5,)})
318 for r in recs("fixed shunt"):
319 if r.int(c["STATUS"],1) == 1:
320 b = at(r.int(1),"a fixed shunt")
321 b[4] += r.num(c["GL"])
322 b[5] += r.num(c["BL"])
324 # ----- switched shunts (BINIT only) -----
325 if rev <= 27: 325 ↛ 326line 325 didn't jump to line 326 because the condition on line 325 was never true
326 binit,status = 6,None
327 elif rev <= 29: 327 ↛ 328line 327 didn't jump to line 328 because the condition on line 327 was never true
328 binit,status = 7,None
329 elif rev < 32: 329 ↛ 330line 329 didn't jump to line 330 because the condition on line 329 was never true
330 binit,status = 8,None
331 elif rev < 35: # I,MODSW,ADJM,STAT,VSWHI,VSWLO,SWREM,RMPCT,'RMIDNT',BINIT,...
332 binit,status = 10,4
333 else: # I,'ID',MODSW,ADJM,SWSTAT,VSWHI,VSWLO,SWREG,NREG,RMPCT,'RMIDNT',BINIT
334 binit,status = 12,5
335 if status is not None: 335 ↛ 338line 335 didn't jump to line 338 because the condition on line 335 was always true
336 c = columns("switched shunt",{"BINIT":(binit,),"STAT":(status,"ST","SWSTAT")})
337 binit,status = c["BINIT"],c["STAT"]
338 for r in recs("switched shunt"):
339 if status is None or r.int(status,1) == 1:
340 at(r.int(1),"a switched shunt")[5] += r.num(binit)
342 # ----- generators -----
343 gen = []
344 if rev < 35: # I,ID,PG,QG,QT,QB,VS,IREG,MBASE,ZR,ZX,RT,XT,GTAP,STAT,RMPCT,PT,PB
345 cols = (3,4,5,6,7,9,15,17,18) # (revision 34 has NREG at the end)
346 else: # I,ID,PG,QG,QT,QB,VS,IREG,NREG,MBASE,...,STAT(16),RMPCT,PT,PB
347 cols = (3,4,5,6,7,10,16,18,19)
348 c = columns("generator",dict(zip(("PG","QG","QT","QB","VS","MBASE","STAT","PT","PB",
349 "IREG"),((x,) for x in cols+(8,)))))
350 cols,ireg = tuple(c.values())[:9],c["IREG"]
351 remote = 0
352 defaults = (0.0,0.0,9999.0,-9999.0,1.0,sbase,1,9999.0,-9999.0)
353 for r in recs("generator"):
354 at(r.int(1),"a generator")
355 v = [r.num(c,d) for c,d in zip(cols,defaults)]
356 if r.int(ireg,0) not in (0,r.int(1)):
357 v[4] = bus[index[r.int(1)]][7] # PYPOWER regulates only the generator bus
358 remote += 1
359 gen.append([r.int(1),v[0],v[1],v[2],v[3],v[4],v[5],1 if v[6] > 0 else 0,v[7],v[8]]
360 + [0.0]*11)
362 def at_limit(g):
363 """In service at a Q limit, with Vg not the case voltage of its bus"""
364 return g[7] and min(abs(g[2]-g[3]),abs(g[2]-g[4])) < 1e-3 \
365 and abs(g[5]-bus[index[g[0]]][7]) > 1e-4
366 atlimit = sum(1 for g in gen if at_limit(g))
367 if atlimit:
368 notes.append(f"{atlimit} generator(s) are at a reactive power limit in the case; "
369 "PYPOWER power flow holds their Vg instead of the limit, so voltages may differ")
370 if remote:
371 notes.append(f"{remote} generator(s) regulate the voltage of another bus (IREG), "
372 "which PYPOWER cannot do; their Vg is the voltage of their own bus in the case")
374 # ----- branches -----
375 branch = []
376 def shunt(number,g,b,on):
377 if on and number in index:
378 bus[index[number]][4] += g*sbase
379 bus[index[number]][5] += b*sbase
380 if rev >= 34: # I,J,CKT,R,X,B,'NAME',RATE1..RATE12,GI,BI,GJ,BJ,ST
381 c = columns("branch",{"R":(4,),"X":(5,),"B":(6,),"RATE1":(8,"RATEA"),
382 "GI":(20,),"STAT":(24,"ST")})
383 elif rev >= 31: 383 ↛ 387line 383 didn't jump to line 387 because the condition on line 383 was always true
384 c = columns("branch",{"R":(4,),"X":(5,),"B":(6,),"RATE1":(7,"RATEA"),
385 "GI":(10,),"STAT":(14,"ST")})
386 else:
387 c = {"R":4,"X":5,"B":6}
388 for r in recs("branch"):
389 fbus,tbus = r.int(1),abs(r.int(2))
390 at(fbus,"a branch")
391 at(tbus,"a branch")
392 if rev <= 27: # I,J,CKT,R,X,B,RATEA,RATEB,RATEC,RATIO,ANGLE,GI,BI,GJ,BJ,ST 392 ↛ 393line 392 didn't jump to line 393 because the condition on line 392 was never true
393 rates,gi,st = 7,12,16
394 ratio,angle = r.num(10),r.num(11)
395 elif rev < 31: # I,J,CKT,R,X,B,RATEA,RATEB,RATEC,GI,BI,GJ,BJ,ST 395 ↛ 396line 395 didn't jump to line 396 because the condition on line 395 was never true
396 rates,gi,st = 7,10,14
397 ratio,angle = 0.0,0.0
398 else:
399 rates,gi,st = c["RATE1"],c["GI"],c["STAT"]
400 ratio,angle = 0.0,0.0
401 on = 1 if r.int(st,1) else 0
402 branch.append([fbus,tbus,r.num(c["R"]),r.num(c["X"]),r.num(c["B"]),r.num(rates),
403 r.num(rates+1),r.num(rates+2),ratio,angle,on,-360.0,360.0])
404 shunt(fbus,r.num(gi),r.num(gi+1),on)
405 shunt(tbus,r.num(gi+2),r.num(gi+3),on)
407 # ----- system switching devices (I,J,CKT,X,RATE1..RATE12,STAT,NSTAT,...) -----
408 switches = 0
409 c = columns("system switching device",{"X":(4,),"RATE1":(5,),"STAT":(17,)})
410 for r in recs("system switching device"):
411 fbus,tbus = r.int(1),abs(r.int(2))
412 at(fbus,"a switching device")
413 at(tbus,"a switching device")
414 on = 1 if r.int(c["STAT"],1) == 1 else 0
415 rate = c["RATE1"]
416 branch.append([fbus,tbus,0.0,r.num(c["X"],0.0001) or 0.0001,0.0,r.num(rate),
417 r.num(rate+1),r.num(rate+2),0.0,0.0,on,-360.0,360.0])
418 switches += 1
419 if switches:
420 notes.append(f"{switches} system switching device(s) converted to branches "
421 "with their reactance X")
423 # ----- transformers -----
424 if rev > 27: 424 ↛ 428line 424 didn't jump to line 428 because the condition on line 424 was always true
425 _transformers(sect("transformer"),bus,index,branch,sbase,notes)
427 # ----- two-terminal DC lines -----
428 dcline = _dclines(sect("two-terminal dc"),bus,index,notes)
430 data = {"version":"2","baseMVA":sbase,"bus":bus,"gen":gen,"branch":branch,
431 "psse_revision":rev}
432 if dcline:
433 data["dcline"] = dcline
434 return data,notes
436def _transformers(lines,bus,index,branch,sbase,notes):
437 """Convert 2- and 3-winding transformers (`psse_convert_xfmr`), appending
438 branch rows and star buses"""
439 # pylint: disable=too-many-locals,too-many-arguments,too-many-positional-arguments
440 # pylint: disable=too-many-branches,too-many-statements
441 two,three = [],[]
442 i = 0
443 while i < len(lines):
444 first = _Rec(_fields(lines[i]))
445 if first.int(3,0) == 0:
446 two.append([first] + [_Rec(_fields(x)) for x in lines[i+1:i+4]])
447 i += 4
448 else:
449 three.append([first] + [_Rec(_fields(x)) for x in lines[i+1:i+5]])
450 i += 5
451 if any(len(x) < 4 for x in two) or any(len(x) < 5 for x in three): 451 ↛ 452line 451 didn't jump to line 452 because the condition on line 451 was never true
452 raise RawError("transformer data ends in the middle of a transformer record")
453 def basekv(number):
454 return bus[index[number]][9]
455 def zsys(r,x,cz,s,nomv,number): # pylint: disable=too-many-arguments,too-many-positional-arguments
456 """Winding impedance in pu on the system base"""
457 if cz == 3: # R: load loss (W), X: |Z| (pu on the winding base) 457 ↛ 458line 457 didn't jump to line 458 because the condition on line 457 was never true
458 r = 1e-6*r/s
459 x = math.sqrt(max(x*x-r*r,0.0))
460 if cz in (2,3):
461 kv = nomv or basekv(number)
462 zb = kv*kv/s
463 zbs = basekv(number)**2/sbase if basekv(number) else 0.0
464 if zbs: 464 ↛ 467line 464 didn't jump to line 467 because the condition on line 464 was always true
465 r,x = r*zb/zbs,x*zb/zbs
466 else:
467 r,x = r*sbase/s,x*sbase/s
468 return r,x
469 def ratio(windv,nomv,cw,number):
470 """Winding voltage in pu of the bus base voltage"""
471 if cw == 1:
472 return windv
473 kv = basekv(number)
474 if cw == 3: 474 ↛ 475line 474 didn't jump to line 475 because the condition on line 474 was never true
475 windv *= nomv or kv
476 return windv/kv if kv else windv
477 mag = 0
478 for r1,r2,r3,r4 in two:
479 fbus,tbus = r1.int(1),r1.int(2)
480 if fbus not in index or tbus not in index: 480 ↛ 481line 480 didn't jump to line 481 because the condition on line 480 was never true
481 notes.append(f"transformer {fbus}-{tbus} refers to an undefined bus; not converted")
482 continue
483 cw,cz = r1.int(5,1),r1.int(6,1)
484 if r1.num(8) or r1.num(9):
485 mag += 1
486 s = r2.num(3,sbase) or sbase
487 r,x = zsys(r2.num(1),r2.num(2),cz,s,r3.num(2),fbus)
488 tap = ratio(r3.num(1,1.0),r3.num(2),cw,fbus)/(ratio(r4.num(1,1.0),r4.num(2),cw,tbus) or 1.0)
489 branch.append([fbus,tbus,r,x,0.0,r3.num(4),r3.num(5),r3.num(6),tap,r3.num(3),
490 1 if r1.int(12,1) else 0,-360.0,360.0])
491 base = 10**math.ceil(math.log10(max(row[0] for row in bus)+1))
492 for n,(r1,r2,r3,r4,r5) in enumerate(three):
493 ends = [r1.int(1),r1.int(2),r1.int(3)]
494 if any(x not in index for x in ends): 494 ↛ 495line 494 didn't jump to line 495 because the condition on line 494 was never true
495 notes.append(f"3-winding transformer {'-'.join(map(str,ends))} refers to an "
496 "undefined bus; not converted")
497 continue
498 cw,cz = r1.int(5,1),r1.int(6,1)
499 if r1.num(8) or r1.num(9): 499 ↛ 500line 499 didn't jump to line 500 because the condition on line 499 was never true
500 mag += 1
501 stat = r1.int(12,1)
502 star = base + n + 1
503 w1 = bus[index[ends[0]]]
504 bus.append([star,1 if stat else 4,0.0,0.0,0.0,0.0,w1[6],r2.num(10,1.0),
505 r2.num(11),w1[9],w1[10],_STAR_VMAX,_STAR_VMIN])
506 index[star] = len(bus) - 1
507 windings = (r3,r4,r5)
508 sb = [r2.num(3,sbase) or sbase,r2.num(6,sbase) or sbase,r2.num(9,sbase) or sbase]
509 z12 = zsys(r2.num(1),r2.num(2),cz,sb[0],r3.num(2),ends[0])
510 z23 = zsys(r2.num(4),r2.num(5),cz,sb[1],r4.num(2),ends[1])
511 z31 = zsys(r2.num(7),r2.num(8),cz,sb[2],r5.num(2),ends[2])
512 z = [[(a+c-b)/2 for a,b,c in zip(z12,z23,z31)],
513 [(a+b-c)/2 for a,b,c in zip(z12,z23,z31)],
514 [(c+b-a)/2 for a,b,c in zip(z12,z23,z31)]]
515 off = {0:(1,2,3),2:(2,),3:(3,),4:(1,)}.get(stat,())
516 for k,(end,w) in enumerate(zip(ends,windings)):
517 branch.append([end,star,z[k][0],z[k][1],0.0,w.num(4),w.num(5),w.num(6),
518 ratio(w.num(1,1.0),w.num(2),cw,end),w.num(3),0 if k+1 in off else 1,
519 -360.0,360.0])
520 if three:
521 stars = f"{base+1}" if len(three) == 1 else f"{base+1}-{base+len(three)}"
522 notes.append(f"added bus(es) {stars} as star points of 3-winding transformers")
523 if mag:
524 notes.append(f"{mag} transformer(s) have magnetizing admittance, which is not converted")
526def _qlims(p,amax,amin):
527 """Converter reactive power limits for power `p` and firing angle limits (deg)"""
528 qmin = abs(p*math.tan(math.radians(amin)))
529 phi = math.degrees(math.acos(0.5*(math.cos(math.radians(amax))+0.5)))
530 return qmin,abs(p*math.tan(math.radians(phi)))
532def _dclines(lines,bus,index,notes):
533 """Convert two-terminal DC lines (`psse_convert_hvdc`)"""
534 # pylint: disable=too-many-locals
535 out = []
536 if len(lines) % 3: 536 ↛ 537line 536 didn't jump to line 537 because the condition on line 536 was never true
537 raise RawError("two-terminal DC data ends in the middle of a DC line record")
538 for k in range(0,len(lines),3):
539 r1,rr,ri = (_Rec(_fields(x)) for x in lines[k:k+3])
540 mdc,setvl,vschd = r1.int(2,0),abs(r1.num(4)),r1.num(5)
541 fbus,tbus = rr.int(1),ri.int(1)
542 if fbus not in index or tbus not in index: 542 ↛ 543line 542 didn't jump to line 543 because the condition on line 542 was never true
543 notes.append(f"DC line {fbus}-{tbus} refers to an undefined bus; not converted")
544 continue
545 p = setvl if mdc == 1 else setvl*vschd/1000 if mdc == 2 else 0.0
546 qrmin,qrmax = _qlims(p,rr.num(3),rr.num(4))
547 qimin,qimax = _qlims(p,ri.num(3),ri.num(4))
548 out.append([fbus,tbus,0 if mdc == 0 else 1,p,p,0.0,0.0,
549 bus[index[fbus]][7],bus[index[tbus]][7],0.85*p,1.15*p,
550 qrmin,qrmax,qimin,qimax,0.0,0.0])
551 if out:
552 notes.append(f"{len(out)} two-terminal DC line(s) converted with Pmin/Pmax at "
553 "85%/115% of the scheduled power and no losses")
554 return out