Coverage for ppedit/case.py: 92.0%
1967 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"""PYPOWER case model
3The `Case` class holds one PYPOWER case (`version`, `baseMVA`, `bus`, `gen`,
4`branch`, and optional `gencost`, `dcline`, `dclinecost`, `storage` and `areas`) as plain Python
5lists so it can be edited row by row and sent to a browser as JSON. It reads
6and writes:
8 - PYPOWER case files (`.py`), parsed with `ast` (the file is never run);
9 the case may be built up in a variable (`ppc = {...}`) or returned as a
10 dict literal (`return {...}`);
11 - PYPOWER JSON (`.json`), the same keys as a `ppc` dict with list arrays;
12 - Arras Energy GridLAB-D models (`.glm`) that use `module pypower`
13 (`bus`, `gen`, `branch`, `gencost` and `dcline` objects).
15It also reads, but does not write, Siemens PTI PSS/E power flow cases
16(`.raw`, revisions 23 to 35): buses, loads, fixed and switched shunts,
17generators, branches, 2- and 3-winding transformers (a star bus is added
18for each 3-winding transformer) and two-terminal DC lines are converted as
19MATPOWER's `psse2mpc` does; `Case.notes` lists what was not converted
20(see `ppedit._psse`). Save the case as `.py`, `.json` or `.glm`.
22DC lines (`dcline`, columns as in PYPOWER's `idx_dcline`) connect two buses
23with a controlled real power flow `Pf` and linear losses `loss0 +
24loss1*Pf`; optional `dclinecost` rows (one per DC line, in the `gencost`
25format) price the flow `Pf` for OPF. `Case.solve` models them as in
26PYPOWER's `toggle_dcline`.
28Areas (`areas`, columns as in `pypower8.caseformat`) list the control areas
29named by the bus `area` column, each with a price reference bus
30(`price_ref_bus`) and an optional `name` (free text, e.g. a balancing
31authority code). The area number stays the key that matches the bus `area`
32column; names are kept outside PYPOWER's `areas` array, in
33`ppc["areanames"]` (one string per `areas` row), and are not written to GLM. A case read without an `areas` table (every GLM file,
34and PYPOWER cases such as `case39`) gets one row per bus area, with the
35area's REF bus, else its bus with the most in-service generating capacity,
36else its first bus as price reference bus. They are not passed to the solver; `Case.solve` sums the
37solution by bus area and reports each area's generation, load, losses, net
38export and, for OPF, the price at its price reference bus.
40A case may also carry bus locations (`Case.geodata`): rows of `[BUS_I, LAT,
41LON, ...]` in decimal degrees (WGS84), where any further values are
42auxiliary data named by `Case.geotags`. Geodata is read from the case's
43`geodata` key (and `geotags` for the auxiliary names), from GLM bus
44`latitude`/`longitude` (and `pp_geodata` objects for the auxiliary data), or from a CSV file with at least the columns
45`BUS_I`, `LAT` and `LON` (`Case.load_geodata`); any other CSV columns are
46kept as auxiliary data. The editor draws the network on a map from it.
48A case may carry a time series of case values (`Case.series`, issue #124):
49bus `Pd` and `Qd`, generator and DC line `Pmin` and `Pmax` by time step,
50in columns named `table.column.key` (`bus.Pd.5` for bus 5, `gen.Pmax.2`
51for the second generator; `Case.set_series`). It is read from and written
52to the `series` key of `.py` and `.json` cases (not GLM), and `Case.solve`
53with `multistep=True` solves all steps as one cvxopf OPF. A case holds
54several named series, combined for the solve by `Case.combined_series`.
55`Case.set_series_panel` sets one value from a panel instead: steps in rows
56and one column per table row or geohash cell (located by bus geodata,
57`geohash`), sharing a cell's value among the elements in it.
59Examples
60--------
62 >>> from ppedit import Case
63 >>> case = Case.builtin("case9")
64 >>> case.size()
65 {'bus': 9, 'gen': 3, 'branch': 9, 'gencost': 3, 'dcline': 0, 'dclinecost': 0, 'storage': 0, 'areas': 1}
66 >>> case.set_value("bus", 4, "Pd", 95) # True would mean other cells changed
67 False
68 >>> [issue["message"] for issue in case.validate()]
69 []
70 >>> result = case.solve("pf")
71 >>> result["success"], round(result["bus"][0]["Vm"], 3)
72 (True, 1.0)
73 >>> case.load_geodata("geo.csv", "BUS_I,LAT,LON,NAME\\n1,37.42,-122.17,Plant A\\n")
74 1
75 >>> case.geodata, case.geotags
76 ([[1, 37.42, -122.17, 'Plant A']], ['NAME'])
78Caveats
79-------
81 - Only the solver-layer objects of `module pypower` are edited. Other
82 objects in a GLM file (`load`, `powerplant`, `powerline`, `relay`,
83 `shunt`, `transformer`, `scada`, `weather`, `geodata`, ...) are counted
84 and reported by `Case.load()` but are not kept, so saving to GLM drops
85 them.
87 - GridLAB-D `module pypower` has no areas object, so `areas` is not
88 written to GLM (each bus keeps its `area`); a comment in the output says
89 how many rows were left out when they differ from the default rows.
90 Reading the GLM file back rebuilds the rows from the bus areas, with
91 default price reference buses.
93 - GLM `dcline` objects: `Sfrom` holds `Pf + j Pt` and `Sto` holds
94 `Qf + j Qt`. This is how GridLAB-D passes these properties to PYPOWER
95 (real and imaginary parts in PYPOWER column order, `module/pypower/
96 pypower.cpp`) and how `gridlabd convert -t pypower` writes them, so the
97 matrix GridLAB-D solves matches the case; it differs from the property
98 descriptions in `dcline.cpp` (MVA flow at each end). GridLAB-D replaces `loss1 = 0` with its default loss factor
99 (`pypower::default_dcline_loss1`, 0.05) unless it can infer one from
100 `Sfrom` and `Sto`.
102 - `module pypower` has no DC line cost class, so GLM output declares a
103 runtime class `dclinecost` with the properties of `pypower.gencost`
104 (`model`, `startup`, `shutdown`, `costs`) and writes one object per
105 `dclinecost` row, named `pp_dclinecost_<n>` with its DC line as parent
106 (`pypower.gencost` itself must have a generator parent in GridLAB-D).
107 GridLAB-D loads these objects but does not pass them to its solver.
108 The class is named for a `pypower.dclinecost` class that GridLAB-D is
109 expected to add; GLM input also reads `object pypower.dclinecost`.
111 - `module pypower` has no storage class, so GLM output declares a
112 runtime class `pp_storage` with the `storage` columns after `gen_i` as
113 properties and writes one object per `storage` row, named
114 `pp_storage_<n>` with its generator as parent (`gen_i`); GLM input
115 reads them back. GridLAB-D loads them but does not use them.
117 - GLM output names buses `pp_bus_<bus_i>`, generators `pp_gen_<n>`,
118 branches `pp_branch_<n>` and cost curves `pp_gencost_<n>` (1-based row
119 order) and DC lines `pp_dcline_<n>` (1-based). `gridlabd convert -t
120 pypower` names buses by row order and DC lines from 0 instead; the bus
121 names agree when bus numbers run 1..N in order.
123 - PSS/E `.raw` input keeps no names (buses, branches, machines) and no
124 data that PYPOWER cannot hold (owners, zones, magnetizing admittance,
125 impedance correction tables, VSC and multi-terminal DC lines, FACTS
126 devices, ...); constant current and constant admittance loads become
127 constant power loads at the case bus voltage, and there are no cost
128 rows (`gencost`), so OPF needs costs added first.
130 - PYPOWER result columns (e.g. `PF`, `QF`, `lam_P`) present in an input
131 case are dropped on load; only the input columns are edited.
133 - Geodata is written to `.py` and `.json` cases as the `geodata` list
134 (a plain list in `.py`, not a numpy array, because auxiliary values may
135 be text) and `geotags`. GLM output keeps each bus's `latitude` and
136 `longitude`; when there are auxiliary values, it also declares a runtime
137 class `pp_geodata` with one property per tag (`int64`, `double` or
138 `char256`/`char1024`) and writes one `pp_geodata` object per geodata row
139 with its bus as parent (and its own `latitude`/`longitude` when it is
140 not the bus's first row), named `pp_geodata_<bus_i>`, or
141 `pp_geodata_<bus_i>_<n>` (`n` the 1-based geodata row) when the bus has
142 more than one row. Tags that are not GLM names are changed to
143 ones that are (`KV level` becomes `KV_level`; a name GLM objects already
144 have, such as `name`, gets a trailing `_`) and are read back that way;
145 `"` in text becomes `'`, and empty values are not written. Geodata rows
146 are not passed to the solver.
148References
149----------
151 - PYPOWER case format: `pypower8.caseformat`
152 - Arras Energy `module pypower`: https://github.com/arras-energy/gridlabd/tree/master/module/pypower
153 - PSS/E RAW conversion: MATPOWER `psse2mpc`, https://matpower.org
154"""
156import ast
157import copy
158import csv
159import datetime
160import io
161import json
162import logging
163import math
164import os
165import re
166import contextlib
167import importlib.util
168import warnings
170_logger = logging.getLogger(__file__)
172# ---------------------------------------------------------------------------
173# column specifications
174# ---------------------------------------------------------------------------
176def _col(name,unit="",kind="float",default=0.0,desc="",options=None,glm=None):
177 return {"name":name,"unit":unit,"kind":kind,"default":default,
178 "desc":desc,"options":options,"glm":glm or name}
180BUS_TYPES = {1:"PQ",2:"PV",3:"REF",4:"NONE"}
181"""PYPOWER bus type codes and their `module pypower` keywords"""
183GEN_STATUS = {1:"IN_SERVICE",0:"OUT_OF_SERVICE"}
184"""Generator status codes and their `module pypower` keywords"""
186BRANCH_STATUS = {1:"IN",0:"OUT"}
187"""Branch status codes and their `module pypower` keywords"""
189COST_MODELS = {1:"PIECEWISE",2:"POLYNOMIAL"}
190"""Generator cost model codes and their `module pypower` keywords"""
192DCLINE_STATUS = {1:"IN",0:"OUT"}
193"""DC line status codes and their `module pypower` keywords"""
195STORAGE_STATUS = {1:"IN",0:"OUT"}
196"""Storage status codes"""
198HOURS_PER_MONTH = 730.0
199"""Hours in the month of the storage `self_discharge` rate (as cvxopf's
200`HOURS_PER_MONTH`)"""
202def _cost_columns(what):
203 return [
204 _col("model","","enum",2,"cost model",COST_MODELS),
205 _col("startup","$",desc="startup cost"),
206 _col("shutdown","$",desc="shutdown cost"),
207 _col("ncost","","int",3,"number of cost coefficients or points"),
208 _col("costs","","text","0,0,0",
209 f"comma-separated cost data in {what}: c(n-1),...,c0 for POLYNOMIAL; "
210 "p1,f1,p2,f2,... for PIECEWISE"),
211 ]
213COLUMNS = {
214 "bus": [
215 _col("bus_i","","int",0,"bus number"),
216 _col("type","","enum",1,"bus type",BUS_TYPES),
217 _col("Pd","MW",desc="real power demand"),
218 _col("Qd","MVAr",desc="reactive power demand"),
219 _col("Gs","MW",desc="shunt conductance (MW demanded at V = 1.0 pu)"),
220 _col("Bs","MVAr",desc="shunt susceptance (MVAr injected at V = 1.0 pu)"),
221 _col("area","","int",1,"area number"),
222 _col("Vm","pu",default=1.0,desc="voltage magnitude"),
223 _col("Va","deg",desc="voltage angle"),
224 _col("baseKV","kV",desc="base voltage"),
225 _col("zone","","int",1,"loss zone"),
226 _col("Vmax","pu",default=1.1,desc="maximum voltage magnitude"),
227 _col("Vmin","pu",default=0.9,desc="minimum voltage magnitude"),
228 ],
229 "gen": [
230 _col("bus","","int",0,"bus number"),
231 _col("Pg","MW",desc="real power output"),
232 _col("Qg","MVAr",desc="reactive power output"),
233 _col("Qmax","MVAr",default=300.0,desc="maximum reactive power output"),
234 _col("Qmin","MVAr",default=-300.0,desc="minimum reactive power output"),
235 _col("Vg","pu",default=1.0,desc="voltage magnitude setpoint"),
236 _col("mBase","MVA",default=100.0,desc="machine MVA base"),
237 _col("status","","enum",1,"machine status",GEN_STATUS),
238 _col("Pmax","MW",default=100.0,desc="maximum real power output"),
239 _col("Pmin","MW",desc="minimum real power output"),
240 _col("Pc1","MW",desc="lower real power output of PQ capability curve"),
241 _col("Pc2","MW",desc="upper real power output of PQ capability curve"),
242 _col("Qc1min","MVAr",desc="minimum reactive power output at Pc1"),
243 _col("Qc1max","MVAr",desc="maximum reactive power output at Pc1"),
244 _col("Qc2min","MVAr",desc="minimum reactive power output at Pc2"),
245 _col("Qc2max","MVAr",desc="maximum reactive power output at Pc2"),
246 _col("ramp_agc","MW/min",desc="ramp rate for load following/AGC"),
247 _col("ramp_10","MW",desc="ramp rate for 10 minute reserves"),
248 _col("ramp_30","MW",desc="ramp rate for 30 minute reserves"),
249 _col("ramp_q","MVAr/min",desc="ramp rate for reactive power"),
250 _col("apf","",desc="area participation factor"),
251 ],
252 "branch": [
253 _col("fbus","","int",0,"from bus number"),
254 _col("tbus","","int",0,"to bus number"),
255 _col("r","pu",desc="resistance"),
256 _col("x","pu",default=0.1,desc="reactance"),
257 _col("b","pu",desc="total line charging susceptance"),
258 _col("rateA","MVA",desc="long term rating (0 = unlimited)"),
259 _col("rateB","MVA",desc="short term rating (0 = unlimited)"),
260 _col("rateC","MVA",desc="emergency rating (0 = unlimited)"),
261 _col("ratio","",desc="transformer off-nominal turns ratio (0 = line)"),
262 _col("angle","deg",desc="transformer phase shift angle"),
263 _col("status","","enum",1,"branch status",BRANCH_STATUS),
264 _col("angmin","deg",default=-360.0,desc="minimum angle difference"),
265 _col("angmax","deg",default=360.0,desc="maximum angle difference"),
266 ],
267 "gencost": _cost_columns("MW of generator output"),
268 "dcline": [
269 _col("fbus","","int",0,"from bus number"),
270 _col("tbus","","int",0,"to bus number"),
271 _col("status","","enum",1,"DC line status",DCLINE_STATUS),
272 _col("Pf","MW",desc="real power flow at the from bus (from -> to)"),
273 _col("Pt","MW",desc="real power flow at the to bus (from -> to)"),
274 _col("Qf","MVAr",desc="reactive power injection at the from bus"),
275 _col("Qt","MVAr",desc="reactive power injection at the to bus"),
276 _col("Vf","pu",default=1.0,desc="voltage setpoint at the from bus"),
277 _col("Vt","pu",default=1.0,desc="voltage setpoint at the to bus"),
278 _col("Pmin","MW",desc="minimum Pf (negative allows flow from to -> from)"),
279 _col("Pmax","MW",default=100.0,desc="maximum Pf"),
280 _col("QminF","MVAr",desc="minimum reactive power injection at the from bus"),
281 _col("QmaxF","MVAr",desc="maximum reactive power injection at the from bus"),
282 _col("QminT","MVAr",desc="minimum reactive power injection at the to bus"),
283 _col("QmaxT","MVAr",desc="maximum reactive power injection at the to bus"),
284 _col("loss0","MW",desc="constant term of the loss function (loss = loss0 + loss1*Pf)"),
285 _col("loss1","MW/MW",desc="linear term of the loss function (loss = loss0 + loss1*Pf)"),
286 ],
287 "dclinecost": _cost_columns("MW of DC line flow Pf"),
288 "storage": [
289 _col("gen_i","","int",1,"generator row (counted from 1) that discharges the storage"),
290 _col("bus_i","","int",-1,"bus number where the storage charges (-1: negative output of its generator)"),
291 _col("Es","MWh",desc="energy stored at the start of the horizon"),
292 _col("Emin","MWh",desc="minimum energy stored"),
293 _col("Emax","MWh",default=100.0,desc="maximum energy stored"),
294 _col("Smax","MVA",default=25.0,desc="charge and discharge power rating"),
295 _col("eta_ch","",default=1.0,desc="charge efficiency (fraction of charging power stored)"),
296 _col("eta_dis","",default=1.0,desc="discharge efficiency (fraction of energy withdrawn delivered)"),
297 _col("self_discharge","1/month",desc="fraction of stored energy lost per month (730 h)"),
298 _col("aging","$/MWh",default=0.01,desc="cost of charge and discharge throughput (cycling)"),
299 _col("Eend","MWh",default=-1.0,desc="energy stored at the end of the horizon (-1: free)"),
300 _col("status","","enum",1,"storage status",STORAGE_STATUS),
301 ],
302 "areas": [
303 _col("area","","int",1,"area number (the bus area column)"),
304 _col("price_ref_bus","","int",0,"price reference bus number"),
305 _col("name","","name","","area name (optional label, e.g. a balancing authority code)"),
306 ],
307}
308"""Editable columns of each table (name, unit, kind, default, description)
310Kinds: `float`, `int`, `enum` (one of `options`), `text` (comma-separated
311cost data) and `name` (free text).
312"""
314def _res(name,unit,index,desc,opf=True):
315 return {"name":name,"unit":unit,"kind":"float","index":index,"desc":desc,"opf":opf}
317RESULT_COLUMNS = {
318 "bus": [
319 _res("lam_P","$/MWh",13,"Lagrange multiplier on real power mismatch (nodal price)"),
320 _res("lam_Q","$/MVArh",14,"Lagrange multiplier on reactive power mismatch"),
321 _res("mu_Vmax","$/pu/h",15,"Kuhn-Tucker multiplier on the upper voltage limit"),
322 _res("mu_Vmin","$/pu/h",16,"Kuhn-Tucker multiplier on the lower voltage limit"),
323 ],
324 "gen": [
325 _res("mu_Pmax","$/MWh",21,"Kuhn-Tucker multiplier on Pmax"),
326 _res("mu_Pmin","$/MWh",22,"Kuhn-Tucker multiplier on Pmin"),
327 _res("mu_Qmax","$/MVArh",23,"Kuhn-Tucker multiplier on Qmax"),
328 _res("mu_Qmin","$/MVArh",24,"Kuhn-Tucker multiplier on Qmin"),
329 ],
330 "branch": [
331 _res("PF","MW",13,"real power injected at the from bus",False),
332 _res("QF","MVAr",14,"reactive power injected at the from bus",False),
333 _res("PT","MW",15,"real power injected at the to bus",False),
334 _res("QT","MVAr",16,"reactive power injected at the to bus",False),
335 _res("mu_Sf","$/MVAh",17,"Kuhn-Tucker multiplier on the MVA limit at the from bus"),
336 _res("mu_St","$/MVAh",18,"Kuhn-Tucker multiplier on the MVA limit at the to bus"),
337 _res("mu_angmin","$/deg/h",19,"Kuhn-Tucker multiplier on the lower angle difference limit"),
338 _res("mu_angmax","$/deg/h",20,"Kuhn-Tucker multiplier on the upper angle difference limit"),
339 ],
340 "dcline": [
341 _res("mu_Pmin","$/MWh",17,"Kuhn-Tucker multiplier on Pmin"),
342 _res("mu_Pmax","$/MWh",18,"Kuhn-Tucker multiplier on Pmax"),
343 _res("mu_QminF","$/MVArh",19,"Kuhn-Tucker multiplier on QminF"),
344 _res("mu_QmaxF","$/MVArh",20,"Kuhn-Tucker multiplier on QmaxF"),
345 _res("mu_QminT","$/MVArh",21,"Kuhn-Tucker multiplier on QminT"),
346 _res("mu_QmaxT","$/MVArh",22,"Kuhn-Tucker multiplier on QmaxT"),
347 ],
348}
349"""Extended (result) columns PYPOWER appends to each table when a solver
350finishes (name, unit, `index` in the PYPOWER array, description, and `opf`:
351whether only OPF gives it)
353They are read only and not part of the case: `Case.solve` returns their
354values in `extended`, and the editor shows them after the editable columns
355until the next edit (decision #56).
356"""
358AREAS_PPC = 2
359"""Number of `areas` columns in PYPOWER's `areas` array (`area`,
360`price_ref_bus`); the `name` column is kept in `ppc["areanames"]`"""
362TABLES = list(COLUMNS)
363"""Names of the editable tables, in display order"""
365COST_TABLES = {"gencost":"gen","dclinecost":"dcline"}
366"""Cost tables and the table each one follows row by row"""
368DCLINE_GLM = ["Vfrom","Vto","Pmin","Pmax","Qminf","Qmaxf","Qmint","Qmaxt","loss0","loss1"]
369"""GLM `dcline` properties for the `dcline` columns `Vf` .. `loss1`"""
371GLM_UNITS = {
372 "bus": {"Pd":"MW","Qd":"MVAr","Gs":"MW","Bs":"MVAr","Vm":"pu.kV",
373 "Va":"deg","baseKV":"kV","Vmax":"pu.kV","Vmin":"pu.kV"},
374 "gen": {"Pg":"MW","Qg":"MVAr","Qmax":"MVAr","Qmin":"MVAr","Vg":"pu.kV",
375 "mBase":"MVA","Pmax":"MW","Pmin":"MW","Pc1":"MW","Pc2":"MW",
376 "Qc1min":"MVAr","Qc1max":"MVAr","Qc2min":"MVAr","Qc2max":"MVAr",
377 "ramp_agc":"MW/min","ramp_10":"MW","ramp_30":"MW",
378 "ramp_q":"MVAr/min","apf":"pu"},
379 "branch": {"r":"pu.Ohm","x":"pu.Ohm","b":"pu.S","rateA":"MVA",
380 "rateB":"MVA","rateC":"MVA","ratio":"pu","angle":"deg",
381 "angmin":"deg","angmax":"deg"},
382 "dcline": {"Vf":"pu.V","Vt":"pu.V","Pmin":"MW","Pmax":"MW",
383 "QminF":"MVAr","QmaxF":"MVAr","QminT":"MVAr","QmaxT":"MVAr",
384 "loss0":"MW","loss1":"MW/MW"},
385}
386"""Units written to GLM, matching `gridlabd convert -t pypower`"""
388FORMATS = {".py":"py",".json":"json",".glm":"glm"}
389"""File extensions and the format each is read and written in"""
391INPUT_FORMATS = {**FORMATS,".raw":"raw"}
392"""File extensions `Case.load` reads (`.raw`: PSS/E, read only)"""
394PF_SOLVERS = {
395 "NR":("Newton",1),
396 "NR-SC":("Newton: power balance, cartesian voltage","NR-SC"),
397 "NR-SH":("Newton: power balance, hybrid voltage","NR-SH"),
398 "NR-IP":("Newton: current balance, polar voltage","NR-IP"),
399 "NR-IC":("Newton: current balance, cartesian voltage","NR-IC"),
400 "NR-IH":("Newton: current balance, hybrid voltage","NR-IH"),
401 "FDXB":("Fast-decoupled XB",2),
402 "FDBX":("Fast-decoupled BX",3),
403 "GS":("Gauss-Seidel",4),
404 "ZG":("Implicit Z-bus Gauss","ZG"),
405}
406"""Power flow algorithms: `algorithm: (label, pypower8 PF_ALG)`. `NR` is
407Newton's method with power balance and polar voltages (MATPOWER 8.1
408`NR-SP`); the other `NR-*` formulations and `ZG` are MATPOWER 8.1
409algorithms that PYPOWER 5.1 lacks (decision #68)."""
411OPF_SOLVERS = {
412 "PIPS":("AC: PIPS interior point",False,560,None),
413 "PIPS-SC":("AC: PIPS step-controlled",False,565,None),
414 "IPOPT":("AC: IPOPT",False,580,"pyipopt"),
415 "DC-PIPS":("DC: PIPS interior point",True,200,None),
416 "DC-PIPS-SC":("DC: PIPS step-controlled",True,250,None),
417 "DC-IPOPT":("DC: IPOPT",True,400,"pyipopt"),
418 "DC-CPLEX":("DC: CPLEX",True,500,"cplex"),
419 "DC-MOSEK":("DC: MOSEK",True,600,"pymosek"),
420 "DC-GUROBI":("DC: Gurobi",True,700,"gurobipy"),
421 "CVXOPF-AC":("AC: CVXOPF (IPOPT)",False,"ac","cvxopf"),
422 "CVXOPF-SOCP":("AC: CVXOPF SOCP relaxation",False,"socp","cvxopf"),
423 "CVXOPF-DC":("DC: CVXOPF lossy network flow",True,"lossy_dc","cvxopf"),
424 "CVXOPF-1NODE":("DC: CVXOPF copper plate",True,"singlenode_dc","cvxopf"),
425}
426"""OPF solvers: `algorithm: (label, DC formulation, PYPOWER OPF_ALG or
427OPF_ALG_DC code (int) or cvxopf formulation (str), Python module the
428solver needs or None)`. The `CVXOPF-*` solvers use cvxopf
429(https://github.com/cvxgrp/cvxopf, Python 3.11+, needs the IPOPT library)
430instead of PYPOWER's `runopf`; see `Case.solve`."""
432SOLVER_WARNINGS = 10
433"""Most distinct Python warnings from a solver that `Case.solve` lists in
434`messages` (the rest are counted)"""
436ISOLATED_EXPLAIN = ("A bus with no in-service branch has no electrical connection to the rest "
437 "of the network, so no voltage can be solved for it and its load, shunts and generators "
438 "cannot be served. ppedit solves it as type NONE (left out) without changing the case. "
439 "Put a branch to it in service, or set the bus type to NONE (4) to make this explicit.")
440"""Physical meaning of the isolated-bus solver warning (`detail["explain"]`)"""
442STORAGE_EXPLAIN = ("Storage links the energy a generator delivers to the energy charged "
443 "earlier, so it needs several time steps solved together: only a multistep CVXOPF OPF "
444 "(Run OPF, Multistep, with a time series) models it. Other solves treat its generator as "
445 "an ordinary generator and do not charge it.")
446"""Physical meaning of the storage-not-modeled solver warning (`detail["explain"]`)"""
448DCLINE_CUT_EXPLAIN = ("A DC line with a terminal at an isolated or type NONE bus has nowhere "
449 "to deliver or draw power, so it is left out of the solve with zero flow.")
450"""Physical meaning of the unsolved-DC-line solver warning (`detail["explain"]`)"""
452def _message_detail(explain:str,constraints:list) -> dict:
453 """Return a solver message `detail` (see `Case.solve`), listing at most 20 constraints"""
454 return {"explain":explain,"constraints":constraints[:20],"more":max(0,len(constraints)-20)}
456GEODATA_COLUMNS = ["BUS_I","LAT","LON"]
457"""Required geodata columns (CSV header names are matched ignoring case);
458latitude and longitude are decimal degrees (WGS84)"""
460SERIES_COLUMNS = {"bus":("Pd","Qd"),"gen":("Pmin","Pmax"),"dcline":("Pmin","Pmax")}
461"""Case values a time series (`Case.series`) may give by step: `table: columns`"""
463SERIES_STEPS = 8784
464"""Most time steps in a series (one leap year of hours)"""
466SERIES_SPLITS = ("proportional","equal","copy")
467"""How `Case.set_series_panel` shares a geohash cell's value among the
468elements in it: in proportion to their case values (equal shares when
469those are all zero), in equal shares, or the whole value to each"""
471GEOHASH_BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz"
472"""Geohash digits"""
474def geohash(lat:float,lon:float,precision:int=12) -> str:
475 """Return the geohash of a location (WGS84 degrees) with `precision` digits
477 >>> geohash(36.670897,-108.581419,6)
478 '9wdb95'
479 """
480 bounds = [[-90.0,90.0],[-180.0,180.0]]
481 bits,out,even,n = 0,[],True,0
482 while len(out) < precision:
483 b = bounds[1] if even else bounds[0]
484 x = lon if even else lat
485 mid = (b[0] + b[1])/2
486 bits <<= 1
487 if x >= mid:
488 bits |= 1
489 b[0] = mid
490 else:
491 b[1] = mid
492 even,n = not even,n + 1
493 if n == 5:
494 out.append(GEOHASH_BASE32[bits])
495 bits,n = 0,0
496 return "".join(out)
498_SERIES_NAME = re.compile(r"^\s*(bus|gen|dcline)\.(\w+)\.(\d+)\s*$",re.I)
500class CaseError(ValueError):
501 """Raised for invalid case data or an unreadable case file"""
503def writable_format(path:str) -> str:
504 """Return the output format of `path` from its extension (`FORMATS`);
505 raise `CaseError` for read-only (`.raw`) or unknown extensions"""
506 ext = os.path.splitext(path)[1].lower()
507 if ext in FORMATS:
508 return FORMATS[ext]
509 if ext in INPUT_FORMATS: 509 ↛ 512line 509 didn't jump to line 512 because the condition on line 509 was always true
510 raise CaseError(f"'{path}': {ext} files are read only; save as "
511 f"{', '.join(FORMATS)}")
512 raise CaseError(f"'{path}' has an unsupported extension (use {', '.join(FORMATS)})")
514# ---------------------------------------------------------------------------
515# helpers
516# ---------------------------------------------------------------------------
518def _number(value,kind="float"):
519 """Convert a cell value to the column's kind; raise CaseError if invalid"""
520 if isinstance(value,str):
521 text = value.strip()
522 if text == "": 522 ↛ 523line 522 didn't jump to line 523 because the condition on line 522 was never true
523 raise CaseError("value is empty")
524 if text.lower() in ("inf","+inf","infinity"): 524 ↛ 525line 524 didn't jump to line 525 because the condition on line 524 was never true
525 value = math.inf
526 elif text.lower() in ("-inf","-infinity"): 526 ↛ 527line 526 didn't jump to line 527 because the condition on line 526 was never true
527 value = -math.inf
528 else:
529 try:
530 value = float(text)
531 except ValueError as err:
532 raise CaseError(f"'{value}' is not a number") from err
533 if isinstance(value,bool): 533 ↛ 534line 533 didn't jump to line 534 because the condition on line 533 was never true
534 value = int(value)
535 if not isinstance(value,(int,float)): 535 ↛ 536line 535 didn't jump to line 536 because the condition on line 535 was never true
536 raise CaseError(f"'{value}' is not a number")
537 if kind in ("int","enum"):
538 if not math.isfinite(value) or value != int(value):
539 raise CaseError(f"'{value}' is not an integer")
540 return int(value)
541 return float(value)
543def _name(value):
544 """Convert a cell value to a `name` column value (stripped text)"""
545 if value is None: 545 ↛ 546line 545 didn't jump to line 546 because the condition on line 545 was never true
546 return ""
547 if isinstance(value,float) and value == int(value): 547 ↛ 548line 547 didn't jump to line 548 because the condition on line 547 was never true
548 value = int(value)
549 return str(value).strip()
551def _area_names(names,count):
552 """`count` area names from a case's `areanames` (or `""` each if absent)"""
553 if names is None:
554 return [""]*count
555 if hasattr(names,"tolist"): 555 ↛ 556line 555 didn't jump to line 556 because the condition on line 555 was never true
556 names = names.tolist()
557 if not isinstance(names,(list,tuple)) or len(names) != count:
558 raise CaseError(f"areanames must list {count} name(s), one per areas row")
559 return [_name(x) for x in names]
561def _costs_list(text):
562 """Parse a comma-separated cost string into a list of floats"""
563 if isinstance(text,(list,tuple)): 563 ↛ 564line 563 didn't jump to line 564 because the condition on line 563 was never true
564 return [float(x) for x in text]
565 parts = [x for x in re.split(r"[,\s]+",str(text).strip()) if x]
566 try:
567 return [float(x) for x in parts]
568 except ValueError as err:
569 raise CaseError(f"costs '{text}' must be comma-separated numbers") from err
571def _costs_text(values):
572 """Cost coefficients as comma-separated text that reads back exactly
573 (shortest round-trip form, without a trailing `.0`)"""
574 return ",".join(_exact(x) for x in values)
576def _exact(value):
577 """Shortest text of a number that reads back as the same float"""
578 text = repr(float(value))
579 return text[:-2] if text.endswith(".0") else text
581def _fmt(value):
582 """Format a number compactly for case files"""
583 if isinstance(value,int):
584 return str(value)
585 if math.isinf(value): 585 ↛ 586line 585 didn't jump to line 586 because the condition on line 585 was never true
586 return "Inf" if value > 0 else "-Inf"
587 return f"{value:.10g}"
589# ---------------------------------------------------------------------------
590# case
591# ---------------------------------------------------------------------------
593class Case:
594 """Editable PYPOWER case
596 Arguments
597 ---------
599 - `data`: a PYPOWER `ppc` dict (numpy arrays or lists), or `None` for
600 an empty case
602 - `name`: case name, used as the function name in `.py` output
604 Each table is a list of rows; each row is a list ordered as
605 `COLUMNS[table]`. `gencost` rows are `[model, startup, shutdown, ncost,
606 costs]` where `costs` is a comma-separated string.
607 """
609 def __init__(self,data:dict|None=None,name:str="case"):
610 self.name = name
611 """Case name (a valid Python identifier)"""
612 self.version = "2"
613 """PYPOWER case format version"""
614 self.baseMVA = 100.0
615 """System MVA base"""
616 self.tables = {x:[] for x in TABLES}
617 """Rows of each table, ordered as `COLUMNS[table]`"""
618 self.notes = []
619 """Messages from loading (e.g. GLM objects that were not kept)"""
620 self.geodata = []
621 """Bus locations: rows of `[BUS_I, LAT, LON, aux...]` (decimal degrees)"""
622 self.geotags = []
623 """Names of the auxiliary geodata values (columns after `LON`)"""
624 self.series = []
625 """Time series of case values for multistep OPF (issue #124): a
626 list of named series, each `name`, `index` (one label per step),
627 `timed` (whether `index` came from a time column), `delta` (hours
628 per step), `columns` (names `table.column.key`, see
629 `Case.set_series`) and `values` (one row per step, one value per
630 column). Multistep OPF combines them (`Case.combined_series`)."""
631 self.source = None
632 """How `Case.load` read the case (`None` otherwise): `file` (base
633 name), `format` (`py`, `json`, `glm` or `raw`), `revision` (PSS/E
634 revision, else `None`), `size` (rows per table when read) and
635 `notes` (as read; `Case.notes` is cleared when the case is saved)"""
636 if data is not None:
637 self._from_ppc(data)
639 # ----- construction -----
641 def _from_ppc(self,data):
642 if not isinstance(data,dict): 642 ↛ 643line 642 didn't jump to line 643 because the condition on line 642 was never true
643 raise CaseError("case data must be a dict")
644 for key in ("baseMVA","bus","gen","branch"):
645 if key not in data: 645 ↛ 646line 645 didn't jump to line 646 because the condition on line 645 was never true
646 raise CaseError(f"case data is missing '{key}'")
647 self.version = str(data.get("version","2"))
648 self.baseMVA = _number(data["baseMVA"])
649 for table in ("bus","gen","branch"):
650 spec = COLUMNS[table]
651 rows = []
652 for n,row in enumerate(_tolist(data[table])):
653 if len(row) < len(spec): 653 ↛ 654line 653 didn't jump to line 654 because the condition on line 653 was never true
654 raise CaseError(f"{table} row {n+1} has {len(row)} columns, "
655 f"expected at least {len(spec)}")
656 rows.append([_number(v,c["kind"]) for v,c in zip(row,spec)])
657 self.tables[table] = rows
658 for table in ("dcline","storage","areas"):
659 spec = COLUMNS[table][:AREAS_PPC] if table == "areas" else COLUMNS[table]
660 rows = []
661 for n,row in enumerate(_tolist(data.get(table,[]))):
662 if len(row) < len(spec): 662 ↛ 663line 662 didn't jump to line 663 because the condition on line 662 was never true
663 raise CaseError(f"{table} row {n+1} has {len(row)} columns, "
664 f"expected at least {len(spec)}")
665 rows.append([_number(v,c["kind"]) for v,c in zip(row,spec)])
666 self.tables[table] = rows
667 names = _area_names(data.get("areanames"),len(self.tables["areas"]))
668 for row,name in zip(self.tables["areas"],names):
669 row.append(name)
670 for table in COST_TABLES:
671 self.tables[table] = _cost_rows(table,data.get(table,[]))
672 if not self.tables["areas"]:
673 self.tables["areas"] = self._default_areas()
674 self.geodata,self.geotags = _geo_from_ppc(data)
675 series = data.get("series")
676 if series:
677 for n,ser in enumerate([series] if isinstance(series,dict) else series):
678 if not isinstance(ser,dict): 678 ↛ 679line 678 didn't jump to line 679 because the condition on line 678 was never true
679 raise CaseError("series must be a list of dicts with columns and values")
680 name = ser.get("name") or ("series" if n == 0 else f"series{n+1}")
681 try:
682 self.set_series(ser.get("columns"),ser.get("values"),ser.get("index"),
683 ser.get("delta",1.0),name=name,timed=ser.get("timed"))
684 except CaseError as err:
685 raise CaseError(f"series '{name}': {err}") from err
687 def _default_areas(self):
688 """Areas rows rebuilt from the bus areas (see `_price_ref`)"""
689 return [[a,self._price_ref(a),""] for a in sorted({r[6] for r in self.tables["bus"]})]
691 def _price_ref(self,area):
692 """Default price reference bus of an area: its REF bus, else the bus with
693 the most in-service generating capacity, else its first bus (0 if none)"""
694 inside = [r for r in self.tables["bus"] if r[6] == area]
695 ref = [r[0] for r in inside if r[1] == 3]
696 if ref:
697 return ref[0]
698 cap = {}
699 for g in self.tables["gen"]:
700 if g[7] == 1:
701 cap[g[0]] = cap.get(g[0],0.0) + g[8]
702 best = max(inside,key=lambda r:cap.get(r[0],-1.0),default=None)
703 return best[0] if best is not None else (self.tables["bus"][0][0] if self.tables["bus"] else 0)
705 @classmethod
706 def builtin(cls,name:str) -> "Case":
707 """Load a case shipped with the `pypower8` package (e.g. `case14`)"""
708 if name not in builtin_cases(): 708 ↛ 709line 708 didn't jump to line 709 because the condition on line 708 was never true
709 raise CaseError(f"'{name}' is not a pypower8 built-in case")
710 import pypower8 # pylint: disable=import-outside-toplevel
711 path = os.path.join(os.path.dirname(pypower8.__file__),f"{name}.py")
712 return cls.load(path)
714 @classmethod
715 def load(cls,path:str,text:str|None=None) -> "Case":
716 """Read a case file
718 Arguments
719 ---------
721 - `path`: file name; the extension selects the format
722 (`INPUT_FORMATS`)
724 - `text`: file contents (read from `path` if `None`)
726 Returns
727 -------
729 - `Case`: the case; `Case.notes` lists anything not kept
731 Exceptions
732 ----------
734 - `CaseError`: unknown extension or unreadable content
735 """
736 fmt = INPUT_FORMATS.get(os.path.splitext(path)[1].lower())
737 if fmt is None:
738 raise CaseError(f"'{path}' has an unsupported extension "
739 f"(use {', '.join(INPUT_FORMATS)})")
740 if text is None:
741 errors = "replace" if fmt == "raw" else "strict" # PSS/E names may be Latin-1
742 with open(path,"r",encoding="utf-8",errors=errors) as fh:
743 text = fh.read()
744 name = re.sub(r"\W","_",os.path.splitext(os.path.basename(path))[0]) or "case"
745 if name[0].isdigit(): 745 ↛ 746line 745 didn't jump to line 746 because the condition on line 745 was never true
746 name = "case_" + name
747 revision = None
748 if fmt == "py":
749 case = cls(_parse_py(text,name),name)
750 elif fmt == "json":
751 try:
752 data = json.loads(text)
753 except json.JSONDecodeError as err:
754 raise CaseError(f"invalid JSON: {err}") from err
755 case = cls(data,name)
756 elif fmt == "raw":
757 from ppedit._psse import parse_raw,RawError # pylint: disable=import-outside-toplevel
758 try:
759 data,notes = parse_raw(text)
760 except RawError as err:
761 raise CaseError(f"invalid PSS/E RAW file: {err}") from err
762 revision = data.pop("psse_revision")
763 case = cls(data,name)
764 case.notes = notes
765 else:
766 data,notes = _parse_glm(text)
767 case = cls(data,name)
768 case.notes = notes
769 case.source = {"file":os.path.basename(path),"format":fmt,
770 "revision":revision,
771 "size":case.size(),"notes":list(case.notes)}
772 _logger.info("loaded %s: %s",path,case.size())
773 return case
775 # ----- output -----
777 def to_ppc(self,arrays:bool=False) -> dict:
778 """Return the case as a PYPOWER `ppc` dict
780 Arguments
781 ---------
783 - `arrays`: return numpy arrays (for the solver) instead of lists;
784 geodata and `areas` are left out
786 `gencost`, `dcline`, `dclinecost`, `storage` and `areas` are included
787 only when they have rows (`storage` and `areas` not with `arrays`:
788 PYPOWER has neither). `areas` holds the two PYPOWER columns (`area`,
789 `price_ref_bus`); when any area has a name, `areanames` lists the
790 names, one per `areas` row (`""` for none).
791 """
792 data = {"version":self.version,"baseMVA":self.baseMVA}
793 for table in ("bus","gen","branch","gencost","dcline","dclinecost","storage","areas"):
794 if table in ("areas","storage") and arrays:
795 continue
796 if table in COST_TABLES:
797 if self.tables[table]:
798 costs = []
799 for model,startup,shutdown,ncost,text in self.tables[table]:
800 costs.append([model,startup,shutdown,ncost]+_costs_list(text))
801 width = max(len(x) for x in costs)
802 data[table] = [x+[0.0]*(width-len(x)) for x in costs]
803 elif table == "areas" and self.tables[table]:
804 data[table] = [list(row[:AREAS_PPC]) for row in self.tables[table]]
805 if any(row[AREAS_PPC] for row in self.tables[table]):
806 data["areanames"] = [row[AREAS_PPC] for row in self.tables[table]]
807 elif table in ("bus","gen","branch") or self.tables[table]:
808 data[table] = [list(row) for row in self.tables[table]]
809 if arrays:
810 import numpy as np # pylint: disable=import-outside-toplevel
811 for key in TABLES:
812 if key in data:
813 width = len(data[key][0]) if key in COST_TABLES else len(COLUMNS[key])
814 data[key] = np.array(data[key],dtype=float).reshape(-1,width)
815 else:
816 if self.geodata:
817 data["geodata"] = [list(row) for row in self.geodata]
818 data["geotags"] = list(self.geotags)
819 if self.series:
820 data["series"] = copy.deepcopy(self.series)
821 return data
823 def to_dict(self) -> dict:
824 """Return the case for the browser editor (JSON-safe)"""
825 return {
826 "name": self.name,
827 "version": self.version,
828 "baseMVA": self.baseMVA,
829 "tables": {t:[[_jsonsafe(v) for v in row] for row in rows]
830 for t,rows in self.tables.items()},
831 "notes": self.notes,
832 "geodata": _jsonsafe(self.geodata),
833 "geotags": list(self.geotags),
834 "series": _jsonsafe(self.series),
835 "series_combined": self._combined_info(),
836 }
838 def dumps(self,fmt:str) -> str:
839 """Return the case as text in format `fmt` (`py`, `json`, or `glm`)"""
840 if fmt == "py":
841 return self._dump_py()
842 if fmt == "json":
843 data = self.to_ppc()
844 return json.dumps(_jsonsafe(data),indent=2) + "\n"
845 if fmt == "glm":
846 return self._dump_glm()
847 if fmt == "csv": 847 ↛ 849line 847 didn't jump to line 849 because the condition on line 847 was always true
848 return self.dumps_geodata()
849 raise CaseError(f"unknown format '{fmt}'")
851 def save(self,path:str):
852 """Write the case to `path`; the extension selects the format (`FORMATS`)"""
853 fmt = writable_format(path)
854 text = self.dumps(fmt)
855 with open(path,"w",encoding="utf-8") as fh:
856 fh.write(text)
857 _logger.info("saved %s: %s",path,self.size())
859 def _dump_py(self):
860 out = io.StringIO()
861 name = self.name if self.name.isidentifier() else "case"
862 out.write(f'''"""PYPOWER case {name} (written by ppedit)"""
864from numpy import array
866def {name}():
867 """Power flow data for {len(self.tables["bus"])} bus, {len(self.tables["gen"])} generator case.
869 @return: PYPOWER case dict
870 """
871 ppc = {{"version": '{self.version}'}}
873 ## system MVA base
874 ppc["baseMVA"] = {_fmt(self.baseMVA)}
875''')
876 data = self.to_ppc()
877 for table in ("bus","gen","branch","gencost","dcline","dclinecost","storage","areas"):
878 if table not in data:
879 continue
880 header = " ".join(c["name"] for c in COLUMNS[table][:len(data[table][0])]) \
881 if table not in COST_TABLES \
882 else "model startup shutdown ncost c(n-1) ... c0 (or x1 y1 ... xn yn)"
883 out.write(f"\n ## {table} data\n # {header}\n")
884 out.write(f' ppc["{table}"] = array([\n')
885 rows = [", ".join(_fmt(v) for v in row) for row in data[table]]
886 out.write(",\n".join(f" [{r}]" for r in rows))
887 out.write("\n ])\n")
888 if table == "areas" and "areanames" in data:
889 out.write(f"\n ## area names (one per areas row)\n"
890 f" ppc[\"areanames\"] = {json.dumps(data['areanames'])}\n")
891 if self.geodata:
892 out.write(f"\n ## geodata (bus locations, decimal degrees)\n"
893 f" # {' '.join(GEODATA_COLUMNS+self.geotags)}\n ppc[\"geodata\"] = [\n")
894 rows = [", ".join(_geo_literal(v) for v in row) for row in self.geodata]
895 out.write(",\n".join(f" [{r}]" for r in rows))
896 out.write(f"\n ]\n ppc[\"geotags\"] = {json.dumps(self.geotags)}\n")
897 if self.series:
898 out.write("\n ## time series of case values (multistep OPF; ppedit)\n"
899 " ppc[\"series\"] = [\n")
900 for ser in self.series:
901 out.write(f" {{\n \"name\": {json.dumps(ser['name'])},\n"
902 f" \"delta\": {_fmt(ser['delta'])},\n"
903 f" \"timed\": {'True' if ser['timed'] else 'False'},\n"
904 f" \"index\": {json.dumps(ser['index'])},\n"
905 f" \"columns\": {json.dumps(ser['columns'])},\n \"values\": [\n")
906 out.write(",\n".join(" [" + ", ".join(_fmt(v) for v in row) + "]"
907 for row in ser["values"]))
908 out.write("\n ],\n },\n")
909 out.write(" ]\n")
910 out.write("\n return ppc\n")
911 return out.getvalue()
913 def _dump_glm(self):
914 out = io.StringIO()
915 out.write(f"// {self.name}: written by ppedit\n")
916 out.write(f"module pypower\n{{\n version {self.version};\n"
917 f" baseMVA {_fmt(self.baseMVA)};\n}}\n")
918 out.write("\n//\n// bus\n//\n")
919 where = self.geomap()
920 for row in self.tables["bus"]:
921 out.write(f'object pypower.bus\n{{\n name "pp_bus_{row[0]}";\n')
922 if row[0] in where:
923 lat,lon = where[row[0]][1:3]
924 out.write(f" latitude {_fmt(float(lat))};\n longitude {_fmt(float(lon))};\n")
925 for col,val in zip(COLUMNS["bus"],row):
926 out.write(f" {col['name']} {_glm_value('bus',col,val)};\n")
927 out.write("}\n")
928 out.write("\n//\n// gen\n//\n")
929 for n,row in enumerate(self.tables["gen"]):
930 out.write(f'object pypower.gen\n{{\n name "pp_gen_{n+1}";\n'
931 f' parent "pp_bus_{row[0]}";\n')
932 for col,val in zip(COLUMNS["gen"],row):
933 out.write(f" {col['name']} {_glm_value('gen',col,val)};\n")
934 out.write("}\n")
935 out.write("\n//\n// branch\n//\n")
936 for n,row in enumerate(self.tables["branch"]):
937 out.write(f'object pypower.branch\n{{\n name "pp_branch_{n+1}";\n'
938 f' from "pp_bus_{row[0]}";\n to "pp_bus_{row[1]}";\n')
939 for col,val in zip(COLUMNS["branch"],row):
940 out.write(f" {col['name']} {_glm_value('branch',col,val)};\n")
941 out.write("}\n")
942 if self.tables["gencost"]:
943 out.write("\n//\n// gencost\n//\n")
944 ngen = len(self.tables["gen"])
945 for n,(model,startup,shutdown,_,costs) in enumerate(self.tables["gencost"]):
946 out.write(f'object pypower.gencost\n{{\n name "pp_gencost_{n+1}";\n'
947 f' parent "pp_gen_{n%ngen+1 if ngen else n+1}";\n'
948 f' model {COST_MODELS.get(model,"UNKNOWN")};\n'
949 f' startup {_fmt(startup)} $;\n shutdown {_fmt(shutdown)} $;\n'
950 f' costs "{costs}";\n}}\n')
951 if self.tables["dcline"]:
952 out.write("\n//\n// dcline\n//\n")
953 for n,row in enumerate(self.tables["dcline"]):
954 out.write(f'object pypower.dcline\n{{\n name "pp_dcline_{n+1}";\n'
955 f' from "pp_bus_{row[0]}";\n to "pp_bus_{row[1]}";\n'
956 f' status {DCLINE_STATUS.get(row[2],row[2])};\n'
957 f' Sfrom {_glm_complex(row[3],row[4])} MVA;\n'
958 f' Sto {_glm_complex(row[5],row[6])} MVA;\n')
959 for name,col,val in zip(DCLINE_GLM,COLUMNS["dcline"][7:],row[7:]):
960 out.write(f" {name} {_glm_value('dcline',col,val)};\n")
961 out.write("}\n")
962 if self.tables["dclinecost"]:
963 self._dump_glm_dclinecost(out)
964 if self.tables["storage"]:
965 self._dump_glm_storage(out)
966 if self.geotags:
967 self._dump_glm_geodata(out)
968 if self.tables["areas"] != self._default_areas():
969 named = sum(1 for r in self.tables["areas"] if r[AREAS_PPC])
970 out.write(f"\n// {len(self.tables['areas'])} areas row(s) not written"
971 + (f" ({named} with names)" if named else "") + ": "
972 "module pypower has no area objects (bus area numbers are kept; "
973 "reading this file rebuilds the rows with default price reference buses "
974 "and no names)\n")
975 if self.series:
976 out.write(f"\n// {len(self.series)} time series ("
977 + ", ".join(f"{ser['name']}: {len(ser['values'])} steps, {len(ser['columns'])} columns"
978 for ser in self.series)
979 + ") not written: save as .py or .json to keep them\n")
980 return out.getvalue()
982 def _dump_glm_dclinecost(self,out):
983 """Write `dclinecost` rows as `dclinecost` objects (runtime class
984 with the `pypower.gencost` properties, parent the DC line)"""
985 out.write("\n//\n// dclinecost (module pypower has no DC line cost class;"
986 " same properties as pypower.gencost)\n//\n")
987 keywords = ",".join(f"{v}={k}" for k,v in sorted({0:"UNKNOWN",**COST_MODELS}.items()))
988 out.write(f"class {DCLINECOST_CLASS}\n{{\n enumeration {{{keywords}}} model;\n"
989 " double startup[$];\n double shutdown[$];\n char1024 costs;\n}\n")
990 ndc = len(self.tables["dcline"])
991 for n,(model,startup,shutdown,_,costs) in enumerate(self.tables["dclinecost"]):
992 out.write(f'object {DCLINECOST_CLASS}\n{{\n name "pp_dclinecost_{n+1}";\n'
993 f' parent "pp_dcline_{n%ndc+1 if ndc else n+1}";\n'
994 f' model {COST_MODELS.get(model,"UNKNOWN")};\n'
995 f' startup {_fmt(startup)} $;\n shutdown {_fmt(shutdown)} $;\n'
996 f' costs "{costs}";\n}}\n')
998 def _dump_glm_storage(self,out):
999 """Write `storage` rows as `pp_storage` objects (runtime class, parent the generator)"""
1000 out.write("\n//\n// storage (module pypower has no storage class)\n//\n")
1001 keywords = ",".join(f"{v}={k}" for k,v in sorted(STORAGE_STATUS.items()))
1002 out.write(f"class {STORAGE_CLASS}\n{{\n int32 bus_i;\n"
1003 + "".join(f" double {c['name']}" + (f"[{c['unit']}]" if c["unit"] in ("MWh","MVA") else "")
1004 + ";" + (f" // {c['unit']}" if c["unit"] not in ("","MWh","MVA") else "") + "\n"
1005 for c in COLUMNS["storage"][2:-1])
1006 + f" enumeration {{{keywords}}} status;\n}}\n")
1007 for n,row in enumerate(self.tables["storage"]):
1008 out.write(f'object {STORAGE_CLASS}\n{{\n name "pp_storage_{n+1}";\n'
1009 f' parent "pp_gen_{row[0]}";\n bus_i {row[1]};\n'
1010 + "".join(f" {c['name']} {_fmt(v)};\n"
1011 for c,v in zip(COLUMNS["storage"][2:-1],row[2:-1]))
1012 + f" status {STORAGE_STATUS.get(row[-1],'OUT')};\n}}\n")
1014 def _dump_glm_geodata(self,out):
1015 """Write the auxiliary geodata as `pp_geodata` objects (runtime class)"""
1016 names = _glm_tag_names(self.geotags)
1017 out.write("\n//\n// geodata auxiliary values (a comment gives each tag that is not a GLM name)\n//\n")
1018 out.write(f"class {GEODATA_CLASS}\n{{\n")
1019 for k,(tag,name) in enumerate(zip(self.geotags,names)):
1020 values = [row[3+k] for row in self.geodata if row[3+k] != ""]
1021 out.write(f" {_glm_geo_type(values)} {name};"
1022 + (f" // {tag}" if name != tag else "") + "\n")
1023 out.write("}\n")
1024 count = {}
1025 for row in self.geodata:
1026 count[row[0]] = count.get(row[0],0) + 1
1027 seen = set()
1028 for n,row in enumerate(self.geodata):
1029 name = f"pp_geodata_{row[0]}" + (f"_{n+1}" if count[row[0]] > 1 else "")
1030 out.write(f'object {GEODATA_CLASS}\n{{\n name "{name}";\n'
1031 f' parent "pp_bus_{row[0]}";\n')
1032 if row[0] in seen: # not the bus's first row: its location is not on the bus
1033 out.write(f" latitude {_fmt(float(row[1]))};\n"
1034 f" longitude {_fmt(float(row[2]))};\n")
1035 seen.add(row[0])
1036 for name,val in zip(names,row[3:]):
1037 if val != "":
1038 out.write(f" {name} {_glm_geo_literal(val)};\n")
1039 out.write("}\n")
1041 # ----- editing -----
1043 def size(self) -> dict:
1044 """Return the number of rows in each table"""
1045 return {t:len(r) for t,r in self.tables.items()}
1047 def _check(self,table,row=None):
1048 if table not in COLUMNS: 1048 ↛ 1049line 1048 didn't jump to line 1049 because the condition on line 1048 was never true
1049 raise CaseError(f"unknown table '{table}'")
1050 if row is not None and not 0 <= row < len(self.tables[table]):
1051 raise CaseError(f"{table} row {row} does not exist")
1053 def set_global(self,key:str,value):
1054 """Set `baseMVA`, `version`, or `name`"""
1055 if key == "baseMVA": 1055 ↛ 1060line 1055 didn't jump to line 1060 because the condition on line 1055 was always true
1056 value = _number(value)
1057 if value <= 0: 1057 ↛ 1059line 1057 didn't jump to line 1059 because the condition on line 1057 was always true
1058 raise CaseError("baseMVA must be positive")
1059 self.baseMVA = value
1060 elif key == "version":
1061 self.version = str(value).strip() or "2"
1062 elif key == "name":
1063 value = re.sub(r"\W","_",str(value).strip())
1064 if not value or value[0].isdigit():
1065 raise CaseError("name must be a valid identifier")
1066 self.name = value
1067 else:
1068 raise CaseError(f"unknown case property '{key}'")
1070 def set_value(self,table:str,row:int,column:str,value) -> bool:
1071 """Set one cell
1073 Changing a bus number also renumbers the generators, branches, DC
1074 lines, storage charging buses, area price reference buses and
1075 geodata that refer to it.
1076 Changing an area number (`areas` table) also renumbers the `area` of
1077 the buses in that area. Changing a cost model or cost data
1078 (`gencost` or `dclinecost`) updates `ncost` to match.
1080 Returns
1081 -------
1083 - `bool`: `True` if other cells or tables changed as a result
1084 """
1085 return self._set_value(table,row,column,value)
1087 def _set_value(self,table,row,column,value,renumber=True):
1088 # renumber=False: a new areas row takes its number without moving buses
1089 self._check(table,row)
1090 names = [c["name"] for c in COLUMNS[table]]
1091 if column not in names: 1091 ↛ 1092line 1091 didn't jump to line 1092 because the condition on line 1091 was never true
1092 raise CaseError(f"{table} has no column '{column}'")
1093 k = names.index(column)
1094 spec = COLUMNS[table][k]
1095 record = self.tables[table][row]
1096 if spec["kind"] == "name":
1097 record[k] = _name(value)
1098 return False
1099 if spec["kind"] == "text":
1100 costs = _costs_list(value)
1101 record[k] = _costs_text(costs)
1102 model = record[0]
1103 record[3] = len(costs)//2 if model == 1 else len(costs)
1104 return True
1105 value = _number(value,spec["kind"])
1106 if spec["kind"] == "enum" and value not in spec["options"]:
1107 raise CaseError(f"{column} must be one of "
1108 + ", ".join(f"{a} ({b})" for a,b in spec["options"].items()))
1109 cascade = False
1110 if table == "bus" and column == "bus_i":
1111 if value < 0: 1111 ↛ 1112line 1111 didn't jump to line 1112 because the condition on line 1111 was never true
1112 raise CaseError("bus number must not be negative")
1113 old = record[0]
1114 if value != old and any(r[0] == value for r in self.tables["bus"]):
1115 raise CaseError(f"bus {value} already exists")
1116 for gen in self.tables["gen"]:
1117 if gen[0] == old:
1118 gen[0] = value
1119 cascade = True
1120 for table2 in ("branch","dcline"):
1121 for branch in self.tables[table2]:
1122 for j in (0,1):
1123 if branch[j] == old:
1124 branch[j] = value
1125 cascade = True
1126 for area in self.tables["areas"]:
1127 if area[1] == old and value != old:
1128 area[1] = value
1129 cascade = True
1130 for store in self.tables["storage"]:
1131 if store[1] == old and value != old and old >= 0:
1132 store[1] = value
1133 cascade = True
1134 for geo in self.geodata:
1135 if geo[0] == old and value != old:
1136 geo[0] = value
1137 cascade = True
1138 if value != old and self._series_rekey("bus",lambda key: value if key == old else key):
1139 cascade = True
1140 if table == "areas" and column == "area":
1141 old = record[0]
1142 if value != old and any(r[0] == value for r in self.tables["areas"]):
1143 raise CaseError(f"area {value} already exists")
1144 if renumber and value != old:
1145 for bus in self.tables["bus"]:
1146 if bus[6] == old:
1147 bus[6] = value
1148 cascade = True
1149 if (table in ("gen","branch","dcline") and column in ("bus","fbus","tbus")) \
1150 or (table == "areas" and column == "price_ref_bus"):
1151 if not any(r[0] == value for r in self.tables["bus"]):
1152 raise CaseError(f"bus {value} does not exist")
1153 if table == "storage" and column == "bus_i" and value != -1 \
1154 and not any(r[0] == value for r in self.tables["bus"]):
1155 raise CaseError(f"bus {value} does not exist (use -1 to charge through the generator)")
1156 if table == "storage" and column == "gen_i" and not 1 <= value <= len(self.tables["gen"]):
1157 raise CaseError(f"generator row {value} does not exist (rows are counted from 1)")
1158 if table in COST_TABLES and column == "model" and value != record[0]:
1159 n = len(_costs_list(record[4]))
1160 record[3] = n//2 if value == 1 else n
1161 cascade = True
1162 record[k] = value
1163 return cascade
1165 def default_row(self,table:str) -> list:
1166 """Return a new row with default values for `table`"""
1167 self._check(table)
1168 row = [c["default"] for c in COLUMNS[table]]
1169 buses = self.tables["bus"]
1170 if table == "bus":
1171 row[0] = max((r[0] for r in buses),default=0) + 1
1172 if buses:
1173 row[6],row[9],row[10] = buses[-1][6],buses[-1][9],buses[-1][10]
1174 elif table == "gen":
1175 ref = [r[0] for r in buses if r[1] == 3]
1176 row[0] = ref[0] if ref else (buses[0][0] if buses else 0)
1177 row[6] = self.baseMVA
1178 elif table in ("branch","dcline"):
1179 row[0] = buses[0][0] if buses else 0
1180 row[1] = buses[1][0] if len(buses) > 1 else row[0]
1181 elif table == "storage":
1182 used = {r[0] for r in self.tables["storage"]}
1183 free = [n+1 for n in range(len(self.tables["gen"])) if n+1 not in used]
1184 row[0] = free[0] if free else (1 if self.tables["gen"] else 0)
1185 elif table == "areas": 1185 ↛ 1190line 1185 didn't jump to line 1190 because the condition on line 1185 was always true
1186 listed = {r[0] for r in self.tables["areas"]}
1187 unlisted = sorted({r[6] for r in buses} - listed)
1188 row[0] = unlisted[0] if unlisted else max(listed,default=0) + 1
1189 row[1] = self._price_ref(row[0])
1190 return row
1192 def add_row(self,table:str,values:list|dict|None=None,after:int|None=None) -> int:
1193 """Insert a row and return its index
1195 Arguments
1196 ---------
1198 - `table`: table name
1200 - `values`: a full row, a dict of column values to override the
1201 defaults, or `None` for defaults
1203 - `after`: insert after this row (default: append)
1205 Adding a generator (DC line) also adds a cost row (a copy of the last
1206 one, or zero polynomial costs) when the case has `gencost`
1207 (`dclinecost`) rows, so the cost table stays aligned with its table.
1208 A new area row does not move any buses: by default it lists the
1209 lowest bus area that has no row, with its REF bus (else the bus
1210 with the most in-service generating capacity, else its first bus)
1211 as the price reference bus.
1212 """
1213 self._check(table)
1214 rows = self.tables[table]
1215 row = self.default_row(table)
1216 if isinstance(values,(list,tuple)):
1217 if table == "areas" and len(values) == AREAS_PPC:
1218 values = list(values) + [row[AREAS_PPC]]
1219 if len(values) != len(row): 1219 ↛ 1220line 1219 didn't jump to line 1220 because the condition on line 1219 was never true
1220 raise CaseError(f"{table} rows have {len(row)} columns")
1221 row = list(values)
1222 index = len(rows) if after is None else max(0,min(after+1,len(rows)))
1223 rows.insert(index,row)
1224 try:
1225 if isinstance(values,(list,tuple)):
1226 for col,val in zip(COLUMNS[table],values):
1227 self._set_value(table,index,col["name"],val,renumber=False)
1228 elif isinstance(values,dict):
1229 for key,val in values.items():
1230 self._set_value(table,index,key,val,renumber=False)
1231 if table in ("bus","areas") and sum(1 for r in rows if r[0] == rows[index][0]) > 1:
1232 what = "bus" if table == "bus" else "area"
1233 raise CaseError(f"{what} {rows[index][0]} already exists")
1234 except CaseError:
1235 del rows[index]
1236 raise
1237 if table in ("gen","dcline") and index < len(rows) - 1:
1238 self._series_rekey(table,lambda key: key + 1 if key > index else key)
1239 if table == "gen" and index < len(rows) - 1:
1240 for store in self.tables["storage"]:
1241 if store[0] > index: 1241 ↛ 1240line 1241 didn't jump to line 1240 because the condition on line 1241 was always true
1242 store[0] += 1
1243 cost = {v:k for k,v in COST_TABLES.items()}.get(table)
1244 if cost and self.tables[cost]:
1245 costs = self.tables[cost]
1246 ngen = len(rows) - 1
1247 template = list(costs[ngen-1]) if ngen and len(costs) >= ngen \
1248 else [2,0.0,0.0,3,"0,0,0"]
1249 costs.insert(index,template)
1250 return index
1252 def delete_rows(self,table:str,rows:list[int],cascade:bool=False) -> dict:
1253 """Delete rows
1255 Arguments
1256 ---------
1258 - `table`: table name
1260 - `rows`: row indexes to delete
1262 - `cascade`: when deleting buses, also delete the generators,
1263 branches, DC lines and storage connected to them and the areas
1264 rows that use them as price reference bus; otherwise refuse if
1265 any exist. Geodata rows of deleted buses are always removed.
1267 Deleting generators (DC lines) also deletes their `gencost`
1268 (`dclinecost`) rows; deleting generators also deletes the storage
1269 they discharge and renumbers `gen_i` of the rest.
1271 Returns
1272 -------
1274 - `dict`: number of rows deleted from each table
1275 """
1276 self._check(table)
1277 for row in rows:
1278 self._check(table,row)
1279 removed = {t:0 for t in TABLES}
1280 rows = sorted(set(rows),reverse=True)
1281 if table == "bus":
1282 numbers = {self.tables["bus"][r][0] for r in rows}
1283 gens = [n for n,g in enumerate(self.tables["gen"]) if g[0] in numbers]
1284 branches = [n for n,b in enumerate(self.tables["branch"])
1285 if b[0] in numbers or b[1] in numbers]
1286 dclines = [n for n,b in enumerate(self.tables["dcline"])
1287 if b[0] in numbers or b[1] in numbers]
1288 areas = [n for n,a in enumerate(self.tables["areas"]) if a[1] in numbers]
1289 stores = [n for n,x in enumerate(self.tables["storage"]) if x[1] in numbers]
1290 if (gens or branches or dclines or areas or stores) and not cascade:
1291 raise CaseError(f"bus(es) {sorted(numbers)} have {len(gens)} "
1292 f"generator(s), {len(branches)} branch(es) and {len(dclines)} "
1293 "DC line(s) connected" + (f", {len(stores)} storage row(s) charging there"
1294 if stores else "") + (f", and are the price reference bus "
1295 f"of {len(areas)} area(s)" if areas else ""))
1296 for sub,index in (("storage",stores),("gen",gens),("branch",branches),
1297 ("dcline",dclines),("areas",areas)):
1298 for k,v in self.delete_rows(sub,index).items():
1299 removed[k] += v
1300 self.geodata = [g for g in self.geodata if g[0] not in numbers]
1301 self._series_rekey("bus",lambda key: None if key in numbers else key)
1302 cost = {v:k for k,v in COST_TABLES.items()}.get(table)
1303 if cost and self.tables[cost]:
1304 ngen = len(self.tables[table])
1305 costs = self.tables[cost]
1306 drop = [r for r in rows if r < len(costs)]
1307 drop += [r+ngen for r in rows if r+ngen < len(costs)]
1308 for r in sorted(set(drop),reverse=True):
1309 del costs[r]
1310 removed[cost] += 1
1311 for r in rows:
1312 del self.tables[table][r]
1313 removed[table] += 1
1314 if table in ("gen","dcline"):
1315 gone = {r+1 for r in rows}
1316 self._series_rekey(table,lambda key: None if key in gone
1317 else key - sum(1 for g in gone if g < key))
1318 if table == "gen":
1319 stores = self.tables["storage"]
1320 for n in range(len(stores)-1,-1,-1):
1321 if stores[n][0] in gone:
1322 del stores[n]
1323 removed["storage"] += 1
1324 else:
1325 stores[n][0] -= sum(1 for g in gone if g < stores[n][0])
1326 return removed
1328 def import_rows(self,table:str,columns:list[str],rows:list[list],
1329 replace:list[int]|None=None) -> dict:
1330 """Append imported rows to a table, or replace rows with them
1332 Arguments
1333 ---------
1335 - `table`: table name
1337 - `columns`: column names of the imported data, in `COLUMNS[table]`
1338 (any order); columns named as in `RESULT_COLUMNS[table]` (solution
1339 values written by export) are ignored
1341 - `rows`: imported rows, values in `columns` order (`None` for a
1342 missing value)
1344 - `replace`: row indexes to replace, in case order, with the
1345 imported rows in file order (default: append)
1347 Appending accepts any subset of the columns and uses the defaults of
1348 `default_row` for missing columns and values, as `add_row` does
1349 (adding generators or DC lines adds their cost rows). Replacing
1350 needs every column and value, and as many imported rows as rows to
1351 replace; each changed value is set as by `set_value`, so a changed
1352 bus or area number renumbers what refers to it (numbers may be
1353 exchanged among the replaced rows). In `gencost` and `dclinecost`,
1354 `ncost` follows `model` and `costs`; its imported value is not used.
1356 On an error some rows may already be changed: callers roll back
1357 (the server runs it in one `Editor.edit()`).
1359 Returns
1360 -------
1362 - `dict`: `added` or `replaced` (number of rows), `cascade`
1363 (`True` if other cells or tables changed as a result), and
1364 `ignored` (the `RESULT_COLUMNS` names left out) when there are any
1366 Exceptions
1367 ----------
1369 - `CaseError`: unknown, duplicate or (replacing) missing columns,
1370 a row count that does not match, or an invalid value (the
1371 message gives its data row, counting from 1)
1373 Example
1374 -------
1376 >>> case = Case.builtin("case9")
1377 >>> case.import_rows("bus",["bus_i","type","Pd"],[[10,1,25.0]])
1378 {'added': 1, 'cascade': False}
1379 >>> case.tables["bus"][-1][:3]
1380 [10, 1, 25.0]
1381 """
1382 self._check(table)
1383 names = [c["name"] for c in COLUMNS[table]]
1384 columns = [str(c).strip() for c in columns]
1385 results = {c["name"] for c in RESULT_COLUMNS.get(table,[])} - set(names)
1386 ignored = [c for c in columns if c in results]
1387 if ignored: # solution values written by export: not case data
1388 keep = [k for k,c in enumerate(columns) if c not in results]
1389 rows = [[r[k] for k in keep] if len(r) == len(columns) else r for r in rows]
1390 columns = [columns[k] for k in keep]
1391 unknown = [c for c in columns if c not in names]
1392 if unknown:
1393 raise CaseError(f"{table} has no column(s) " + ", ".join(f"'{c}'" for c in unknown)
1394 + " (columns are " + ", ".join(names) + ")")
1395 if len(set(columns)) != len(columns):
1396 raise CaseError("column(s) " + ", ".join(sorted({c for c in columns
1397 if columns.count(c) > 1})) + " appear more than once")
1398 if not rows:
1399 raise CaseError("the file has no rows")
1400 if any(len(r) != len(columns) for r in rows): 1400 ↛ 1401line 1400 didn't jump to line 1401 because the condition on line 1400 was never true
1401 raise CaseError(f"every row must have {len(columns)} values")
1402 order = [columns.index(n) for n in names if n in columns] # COLUMNS order
1403 text = {c["name"] for c in COLUMNS[table] if c["kind"] == "name"}
1404 def values(n):
1405 # an empty cell is a missing value, except in a free-text column
1406 return {columns[k]:"" if rows[n][k] is None else rows[n][k] for k in order
1407 if rows[n][k] is not None or columns[k] in text}
1408 if replace is None:
1409 for n in range(len(rows)):
1410 try:
1411 self.add_row(table,values(n))
1412 except CaseError as err:
1413 raise CaseError(f"row {n+1}: {err}") from err
1414 cost = {v:k for k,v in COST_TABLES.items()}.get(table)
1415 return {"added":len(rows),"cascade":bool(cost and self.tables[cost])} \
1416 | ({"ignored":ignored} if ignored else {})
1417 for row in replace:
1418 self._check(table,row)
1419 targets = sorted(set(replace))
1420 if len(rows) != len(targets):
1421 raise CaseError(f"{len(rows)} row(s) imported for {len(targets)} selected row(s)")
1422 missing = [n for n in names if n not in columns]
1423 if missing:
1424 raise CaseError("replacing rows needs every column; missing " + ", ".join(missing))
1425 new = [values(n) for n in range(len(rows))]
1426 for n,vals in enumerate(new):
1427 empty = [c for c in names if c not in vals]
1428 if empty:
1429 raise CaseError(f"row {n+1}: no value for " + ", ".join(empty))
1430 cascade = False
1431 if table in ("bus","areas"):
1432 # move changed bus (area) numbers out of the way first, so that
1433 # numbers may be exchanged among the replaced rows
1434 key = names[0]
1435 try:
1436 wanted = [_number(v[key],"int") for v in new]
1437 except CaseError as err:
1438 raise CaseError(f"{key}: {err}") from err
1439 temp = max([r[0] for r in self.tables[table]] + wanted) + 1
1440 for row,number in zip(targets,wanted):
1441 if self.tables[table][row][0] != number:
1442 cascade |= self._set_value(table,row,key,temp)
1443 temp += 1
1444 def same(spec,old,value):
1445 # unchanged values are not set, so they cascade nothing
1446 try:
1447 if spec["kind"] == "name":
1448 return _name(value) == old
1449 if spec["kind"] == "text":
1450 return _costs_text(_costs_list(value)) == old
1451 return _number(value,spec["kind"]) == old
1452 except (CaseError,ValueError,TypeError):
1453 return False # _set_value reports it
1454 for n,(row,vals) in enumerate(zip(targets,new)):
1455 try:
1456 for k,column in enumerate(names):
1457 if table in COST_TABLES and column == "ncost":
1458 continue # follows model and costs
1459 if not same(COLUMNS[table][k],self.tables[table][row][k],vals[column]):
1460 cascade |= self._set_value(table,row,column,vals[column])
1461 except CaseError as err:
1462 raise CaseError(f"row {n+1}: {err}") from err
1463 return {"replaced":len(rows),"cascade":cascade} | ({"ignored":ignored} if ignored else {})
1465 # ----- geodata -----
1467 def set_geodata(self,rows:list,tags:list|None=None):
1468 """Replace the geodata
1470 Arguments
1471 ---------
1473 - `rows`: rows of `[BUS_I, LAT, LON, aux...]` (decimal degrees),
1474 or an empty list to remove the geodata
1476 - `tags`: names of the auxiliary values (default: none); rows are
1477 padded with `""` or truncated to match
1479 Exceptions
1480 ----------
1482 - `CaseError`: a row has fewer than 3 values, a bus number is not
1483 an integer, or a latitude/longitude is not a number in range
1484 """
1485 self.geodata,self.geotags = _geo_rows(rows,tags or [])
1487 def load_geodata(self,path:str,text:str|None=None) -> int:
1488 """Read geodata from a CSV file, replacing any existing geodata
1490 Arguments
1491 ---------
1493 - `path`: CSV file name
1495 - `text`: file contents (read from `path` if `None`)
1497 The header row must name the columns `BUS_I`, `LAT` and `LON` (in any
1498 order, ignoring case); other columns are kept as auxiliary data named
1499 by their headers (`Case.geotags`). Auxiliary values that read as
1500 numbers are stored as numbers, others as text.
1502 Returns
1503 -------
1505 - `int`: number of geodata rows read
1507 Exceptions
1508 ----------
1510 - `CaseError`: missing columns or invalid values
1511 """
1512 if text is None:
1513 with open(path,"r",encoding="utf-8-sig") as fh:
1514 text = fh.read()
1515 rows,tags = _read_geodata_csv(text)
1516 self.set_geodata(rows,tags)
1517 _logger.debug("geodata %s: %d rows, tags %s",path,len(rows),tags)
1518 return len(self.geodata)
1520 def dumps_geodata(self) -> str:
1521 """Return the geodata as CSV text (`BUS_I,LAT,LON` and the tags)"""
1522 out = io.StringIO()
1523 writer = csv.writer(out,lineterminator="\n")
1524 writer.writerow(GEODATA_COLUMNS+self.geotags)
1525 for row in self.geodata:
1526 writer.writerow([_fmt(v) if isinstance(v,(int,float)) else v for v in row])
1527 return out.getvalue()
1529 def geomap(self) -> dict:
1530 """Return `{bus_i: geodata row}` (the first row of each bus)"""
1531 where = {}
1532 for row in self.geodata:
1533 where.setdefault(row[0],row)
1534 return where
1536 # ----- time series (issue #124) -----
1538 def set_series(self,columns:list[str]|None,values:list[list]|None=None,
1539 index:list|None=None,delta:float=1.0,name:str|None=None,
1540 timed:bool|None=None) -> dict|None:
1541 """Add, replace or remove a time series of case values used by
1542 multistep OPF
1544 Arguments
1545 ---------
1547 - `columns`: column names `table.column.key` (`None` or empty
1548 removes the series `name`, or every series when `name` is
1549 `None`): `table` and `column` as in `SERIES_COLUMNS`
1550 (`bus.Pd`, `bus.Qd`, `gen.Pmin`, `gen.Pmax`, `dcline.Pmin`,
1551 `dcline.Pmax`; case is ignored) and `key` the bus number
1552 (`bus_i`) for `bus`, else the row number counted from 1, as in
1553 `gen.Pmax.2` for the second generator
1555 - `values`: one row per time step, one finite number per column
1556 (MW, MVAr)
1558 - `index`: one label per step (e.g. a time stamp; default `1`,
1559 `2`, ...), kept as text
1561 - `delta`: hours per step (positive)
1563 - `name`: the series to add or replace (default `series`); a case
1564 holds several, which multistep OPF combines
1565 (`Case.combined_series`)
1567 - `timed`: whether `index` came from a time column (default: an
1568 `index` was given); series with time labels are lined up by
1569 time when combined
1571 Values not in the series keep their case values at every step. The
1572 series moves with the case: renumbering a bus renames its columns,
1573 deleting a bus, generator or DC line drops its columns, and adding
1574 or deleting generator or DC line rows renumbers the columns of the
1575 rows after them.
1577 Returns
1578 -------
1580 - `dict`: the series as stored (an entry of `Case.series`), or `None`
1582 Exceptions
1583 ----------
1585 - `CaseError`: an unknown or repeated column, a bus or row that
1586 does not exist, a missing or non-finite value, rows of
1587 different lengths, more than `SERIES_STEPS` steps, labels that
1588 do not match the steps, `delta` not positive, or a bad `name`
1589 """
1590 if not columns:
1591 if name is None:
1592 self.series = []
1593 else:
1594 self.series = [x for x in self.series if x["name"] != name]
1595 return None
1596 name = self._series_name("series" if name is None else name)
1597 names = []
1598 for col in columns:
1599 table,column,key = self._series_part(col)
1600 names.append(f"{table}.{column}.{key}")
1601 dup = sorted({x for x in names if names.count(x) > 1})
1602 if dup:
1603 raise CaseError(f"repeated series column(s): {', '.join(dup)}")
1604 if not values:
1605 raise CaseError("the series has no time steps")
1606 if len(values) > SERIES_STEPS: 1606 ↛ 1607line 1606 didn't jump to line 1607 because the condition on line 1606 was never true
1607 raise CaseError(f"the series has {len(values)} steps; at most {SERIES_STEPS} are allowed")
1608 rows = []
1609 for t,row in enumerate(values):
1610 if not isinstance(row,(list,tuple)) or len(row) != len(names):
1611 raise CaseError(f"series step {t+1} has "
1612 f"{len(row) if isinstance(row,(list,tuple)) else 'no'} values, expected {len(names)}")
1613 out = []
1614 for col,v in zip(names,row):
1615 try:
1616 x = float(v)
1617 except (TypeError,ValueError):
1618 x = math.nan
1619 if not math.isfinite(x):
1620 raise CaseError(f"series step {t+1}, {col}: {v!r} is not a finite number")
1621 out.append(x)
1622 rows.append(out)
1623 given = index is not None
1624 if index is None:
1625 index = [str(t+1) for t in range(len(rows))]
1626 if len(index) != len(rows):
1627 raise CaseError(f"the series has {len(index)} step labels for {len(rows)} steps")
1628 ser = {"name":name,"index":[str(x) for x in index],"timed":bool(given if timed is None else timed),
1629 "delta":self._series_delta(delta),"columns":names,"values":rows}
1630 old = [n for n,x in enumerate(self.series) if x["name"] == name]
1631 if old:
1632 self.series[old[0]] = ser
1633 else:
1634 self.series.append(ser)
1635 return ser
1637 @staticmethod
1638 def _series_name(name) -> str:
1639 text = str(name).strip()
1640 if not text or len(text) > 64 or any(ord(c) < 32 for c in text):
1641 raise CaseError(f"series name {name!r} must be 1 to 64 printable characters")
1642 return text
1644 def get_series(self,name:str|None=None) -> dict|None:
1645 """Return the series `name` (the only one when `name` is `None` and
1646 there is one), or `None`"""
1647 if name is None:
1648 return self.series[0] if len(self.series) == 1 else None
1649 return next((x for x in self.series if x["name"] == name),None)
1651 def set_series_panel(self,table:str,column:str,keys:list,values:list[list],
1652 index:list|None=None,delta:float|None=None,keys_are:str="auto",
1653 split:str="proportional",merge:bool=True,name:str|None=None) -> dict:
1654 """Set one case value by step from a panel: steps in rows, one
1655 column per table row or geohash cell
1657 Arguments
1658 ---------
1660 - `table`, `column`: the case value the panel gives, as in
1661 `SERIES_COLUMNS` (e.g. `bus`, `Pd`; case is ignored)
1663 - `keys`: one key per panel column: a row number of `table`
1664 counted from 1 (for `bus` the row, not the bus number), or a
1665 geohash (any length, e.g. `9q8yy`)
1667 - `values`: one row per step, one finite number per key
1669 - `index`, `delta`: step labels and hours per step for a new
1670 series (see `set_series`); a merged panel keeps those of the
1671 current series (`delta` replaces it when given)
1673 - `keys_are`: `row`, `geohash`, or `auto` (all digits: rows,
1674 else geohashes)
1676 - `split`: for geohashes, how a cell's value is shared among the
1677 elements located in it (`SERIES_SPLITS`): `proportional` to
1678 their case values of `column` (equal shares when those are all
1679 zero), `equal`, or `copy` (the whole value to each)
1681 - `merge`: add the panel to the series `name` if it exists (same
1682 number of steps), replacing that value's columns for the
1683 elements the panel covers; `False` replaces that series
1685 - `name`: the series written (default `series`)
1687 Elements are located by their bus's geodata (the first row of the
1688 bus; a generator by its bus, a DC line by its from bus). Geohash
1689 cells with no element in them are ignored and reported; elements
1690 without geodata or outside every cell are left out.
1692 Returns
1693 -------
1695 - `dict`: `columns` (series columns written), `keys` (panel
1696 columns used), `ignored` (geohashes with no element), and
1697 `unlocated` (elements without geodata, for geohashes)
1699 Exceptions
1700 ----------
1702 - `CaseError`: an unknown table or column, keys of the wrong
1703 kind, repeated or nested geohashes that put one element in two
1704 cells, a row that does not exist, no geodata for geohashes, no
1705 element matched, a non-finite value, or a merge with a
1706 different number of steps (and the errors of `set_series`)
1707 """
1708 if table not in SERIES_COLUMNS:
1709 raise CaseError(f"a panel can set {', '.join(SERIES_COLUMNS)} values, not '{table}'")
1710 known = {c.lower():c for c in SERIES_COLUMNS[table]}
1711 if str(column).lower() not in known:
1712 raise CaseError(f"{table} values by step can be {', '.join(SERIES_COLUMNS[table])}, "
1713 f"not '{column}'")
1714 column = known[str(column).lower()]
1715 if split not in SERIES_SPLITS:
1716 raise CaseError(f"split must be one of {', '.join(SERIES_SPLITS)}, not '{split}'")
1717 keys = [re.sub(r"\.0+$","",str(k).strip()) for k in keys]
1718 if not keys: 1718 ↛ 1719line 1718 didn't jump to line 1719 because the condition on line 1718 was never true
1719 raise CaseError("the panel has no columns")
1720 dup = sorted({k for k in keys if keys.count(k) > 1})
1721 if dup:
1722 raise CaseError(f"repeated panel column(s): {', '.join(dup)}")
1723 digits = [k.isdigit() for k in keys]
1724 if keys_are == "auto":
1725 keys_are = "row" if all(digits) else "geohash"
1726 if keys_are == "row":
1727 bad = [k for k,d in zip(keys,digits) if not d]
1728 elif keys_are == "geohash": 1728 ↛ 1732line 1728 didn't jump to line 1732 because the condition on line 1728 was always true
1729 keys = [k.lower() for k in keys]
1730 bad = [k for k in keys if not k or any(c not in GEOHASH_BASE32 for c in k)]
1731 else:
1732 raise CaseError(f"keys_are must be row, geohash or auto, not '{keys_are}'")
1733 if bad:
1734 raise CaseError(f"panel column(s) {', '.join(bad[:5])} are not "
1735 + ("row numbers" if keys_are == "row" else "geohashes"))
1736 rows = []
1737 for t,row in enumerate(values or []):
1738 if not isinstance(row,(list,tuple)) or len(row) != len(keys): 1738 ↛ 1739line 1738 didn't jump to line 1739 because the condition on line 1738 was never true
1739 raise CaseError(f"panel step {t+1} has "
1740 f"{len(row) if isinstance(row,(list,tuple)) else 'no'} values, expected {len(keys)}")
1741 out = []
1742 for k,v in zip(keys,row):
1743 try:
1744 x = float(v)
1745 except (TypeError,ValueError):
1746 x = math.nan
1747 if not math.isfinite(x):
1748 raise CaseError(f"panel step {t+1}, column {k}: {v!r} is not a finite number")
1749 out.append(x)
1750 rows.append(out)
1751 if not rows:
1752 raise CaseError("the panel has no time steps")
1753 names = [c["name"] for c in COLUMNS[table]]
1754 k_col = names.index(column)
1755 ids = lambda n: self.tables["bus"][n][0] if table == "bus" else n + 1
1756 parts,ignored,unlocated = [],[],0 # parts: (panel column, element key, share)
1757 if keys_are == "row":
1758 for j,k in enumerate(keys):
1759 n = int(k)
1760 if not 1 <= n <= len(self.tables[table]):
1761 raise CaseError(f"panel column {k}: {table} row {n} does not exist "
1762 f"({len(self.tables[table])} rows)")
1763 parts.append((j,ids(n-1),1.0))
1764 else:
1765 if not self.geodata:
1766 raise CaseError("geohash panel columns need bus geodata (load it first)")
1767 where = {}
1768 for g in self.geodata:
1769 where.setdefault(g[0],(g[1],g[2]))
1770 bus_of = (lambda n: self.tables["bus"][n][0]) if table == "bus" else \
1771 (lambda n: self.tables[table][n][0])
1772 cells = {}
1773 for n in range(len(self.tables[table])):
1774 loc = where.get(bus_of(n))
1775 if loc is None:
1776 unlocated += 1
1777 continue
1778 code = geohash(loc[0],loc[1],12)
1779 hits = [j for j,k in enumerate(keys) if code.startswith(k)]
1780 if len(hits) > 1:
1781 raise CaseError(f"{table} {ids(n)} is in panel cells "
1782 f"{' and '.join(keys[j] for j in hits)}; keep one")
1783 if hits:
1784 cells.setdefault(hits[0],[]).append(n)
1785 ignored = [k for j,k in enumerate(keys) if j not in cells]
1786 for j,members in sorted(cells.items()):
1787 base = [abs(float(self.tables[table][n][k_col])) for n in members]
1788 for n,b in zip(members,base):
1789 share = 1.0 if split == "copy" else \
1790 b/sum(base) if split == "proportional" and sum(base) > 0 else 1/len(members)
1791 parts.append((j,ids(n),share))
1792 if not parts:
1793 raise CaseError("no panel column matched a "
1794 + ("located " if keys_are == "geohash" else "") + f"{table} element")
1795 new = [f"{table}.{column}.{key}" for _,key,_ in parts]
1796 new_values = [[r[j]*share for j,_,share in parts] for r in rows]
1797 name = self._series_name("series" if name is None else name)
1798 ser = self.get_series(name)
1799 if merge and ser:
1800 if len(ser["values"]) != len(rows):
1801 raise CaseError(f"the panel has {len(rows)} steps but series '{name}' has "
1802 f"{len(ser['values'])}; replace the series instead")
1803 keep = [j for j,c in enumerate(ser["columns"]) if c not in new]
1804 columns = [ser["columns"][j] for j in keep] + new
1805 merged = [[old[j] for j in keep] + add for old,add in zip(ser["values"],new_values)]
1806 self.set_series(columns,merged,ser["index"],ser["delta"] if delta is None else delta,
1807 name=name,timed=ser["timed"])
1808 else:
1809 self.set_series(new,new_values,index,1.0 if delta is None else delta,name=name)
1810 return {"columns":len(new),"keys":len({j for j,_,_ in parts}),"ignored":ignored,
1811 "unlocated":unlocated}
1813 def set_series_delta(self,delta:float,name:str|None=None):
1814 """Set the hours per step of the series `name` (`None`: the only
1815 one); `CaseError` if there is no such series"""
1816 ser = self.get_series(name)
1817 if not ser:
1818 raise CaseError("the case has no time series" if not self.series else
1819 f"no series named '{name}'" if name is not None else "name the series (the case has several)")
1820 ser["delta"] = self._series_delta(delta)
1822 @staticmethod
1823 def _series_delta(delta):
1824 try:
1825 x = float(delta)
1826 except (TypeError,ValueError):
1827 x = math.nan
1828 if not math.isfinite(x) or x <= 0:
1829 raise CaseError(f"series step length must be a positive number of hours, not {delta!r}")
1830 return x
1832 def _series_part(self,name):
1833 """Return `(table, column, key)` of a series column name (see `set_series`)"""
1834 m = _SERIES_NAME.match(str(name))
1835 if not m:
1836 raise CaseError(f"series column '{name}' is not table.column.key "
1837 "(e.g. bus.Pd.5, gen.Pmax.1, dcline.Pmax.1)")
1838 table,column,key = m[1].lower(),m[2],int(m[3])
1839 known = {c.lower():c for c in SERIES_COLUMNS[table]}
1840 if column.lower() not in known:
1841 raise CaseError(f"series column '{name}': {table} values by step can be "
1842 f"{', '.join(SERIES_COLUMNS[table])}")
1843 column = known[column.lower()]
1844 if table == "bus":
1845 if not any(r[0] == key for r in self.tables["bus"]):
1846 raise CaseError(f"series column '{name}': bus {key} does not exist")
1847 elif not 1 <= key <= len(self.tables[table]):
1848 raise CaseError(f"series column '{name}': {table} row {key} does not exist "
1849 f"({len(self.tables[table])} rows)")
1850 return table,column,key
1852 def _series_rekey(self,table,func) -> bool:
1853 """Change the keys of the `table` series columns by `func(key)`
1854 (`None` drops the column); return whether any changed"""
1855 changed = False
1856 for ser in list(self.series):
1857 keep,names,this = [],[],False
1858 for j,name in enumerate(ser["columns"]):
1859 t,column,key = name.split(".")
1860 new = func(int(key)) if t == table else int(key)
1861 if new is None:
1862 this = True
1863 continue
1864 this |= new != int(key)
1865 keep.append(j)
1866 names.append(f"{t}.{column}.{new}")
1867 if this:
1868 changed = True
1869 if not names:
1870 self.series.remove(ser)
1871 else:
1872 ser["columns"] = names
1873 ser["values"] = [[row[j] for j in keep] for row in ser["values"]]
1874 return changed
1876 def combined_series(self) -> dict|None:
1877 """Return the series combined into one horizon for multistep OPF, or
1878 `None` when there is none
1880 When every series has time labels (`timed`), steps are lined up by
1881 time: the labels are read as ISO dates and times when they all are
1882 (else compared as text), and only the times present in every series
1883 are kept, in the order of the first series. When no series has time
1884 labels, steps are lined up by number, and all series must have the
1885 same number of steps. A value given by several series is their sum
1886 (e.g. a base load series and an EV load series for the same bus).
1887 The result has the first series' labels and the `delta` all series
1888 share, `columns` (each once, in order of first appearance) and
1889 `values`, `aligned` (`single`, `time` or `step`), `used` (steps kept
1890 from each series, by name) and `summed` (`{column: [series
1891 names]}` for the columns added up).
1893 Exceptions
1894 ----------
1896 - `CaseError`: some series have time labels and others do not,
1897 different step counts (by number) or step lengths, or no time
1898 common to all series
1899 """
1900 if not self.series:
1901 return None
1902 first = self.series[0]
1903 owner = {} # column -> names of the series giving it
1904 for ser in self.series:
1905 for c in ser["columns"]:
1906 owner.setdefault(c,[]).append(ser["name"])
1907 summed = {c:names for c,names in owner.items() if len(names) > 1}
1908 deltas = {ser["delta"] for ser in self.series}
1909 if len(deltas) > 1:
1910 raise CaseError("the series have different step lengths ("
1911 + ", ".join(f"{ser['name']}: {ser['delta']:g} h" for ser in self.series) + ")")
1912 if len(self.series) == 1:
1913 return {**copy.deepcopy(first),"aligned":"single",
1914 "used":{first["name"]:len(first["values"])},"summed":{}}
1915 timed = [ser["timed"] for ser in self.series]
1916 if any(timed) and not all(timed):
1917 raise CaseError("series " + ", ".join(f"'{ser['name']}'" for ser in self.series if ser["timed"])
1918 + " have time labels but " + ", ".join(f"'{ser['name']}'" for ser in self.series
1919 if not ser["timed"]) + " do not: import all with a time column or none")
1920 columns = list(owner) # each column once, in order of first appearance
1921 slot = {c:j for j,c in enumerate(columns)}
1922 def merge(parts):
1923 """One combined row from (series, row) pairs; shared columns add up"""
1924 row = [0.0]*len(columns)
1925 for ser,values in parts:
1926 for c,v in zip(ser["columns"],values):
1927 row[slot[c]] += v
1928 return row
1929 if not any(timed):
1930 counts = {len(ser["values"]) for ser in self.series}
1931 if len(counts) > 1:
1932 raise CaseError("series without time labels are combined step by step and need the "
1933 "same number of steps (" + ", ".join(f"{ser['name']}: {len(ser['values'])}"
1934 for ser in self.series) + ")")
1935 values = [merge((ser,ser["values"][t]) for ser in self.series) for t in range(len(first["values"]))]
1936 return {"name":first["name"],"index":list(first["index"]),"timed":False,"delta":first["delta"],
1937 "columns":columns,"values":values,"aligned":"step",
1938 "used":{ser["name"]:len(ser["values"]) for ser in self.series},"summed":summed}
1939 def parse(label):
1940 try:
1941 return datetime.datetime.fromisoformat(label.strip())
1942 except ValueError:
1943 return None
1944 parsed = [[parse(x) for x in ser["index"]] for ser in self.series]
1945 dates = all(x is not None for p in parsed for x in p)
1946 if dates and len({x.tzinfo is None for p in parsed for x in p}) > 1: 1946 ↛ 1947line 1946 didn't jump to line 1947 because the condition on line 1946 was never true
1947 dates = False # mixed zone-aware and naive times compare as text
1948 keys = [p if dates else [x.strip() for x in ser["index"]] for p,ser in zip(parsed,self.series)]
1949 where = [{k:t for t,k in enumerate(ks)} for ks in keys]
1950 common = [t for t,k in enumerate(keys[0]) if all(k in w for w in where[1:])]
1951 if not common:
1952 raise CaseError("the series have no time in common (" + ", ".join(
1953 f"{ser['name']}: {ser['index'][0]} to {ser['index'][-1]}" for ser in self.series) + ")")
1954 values = [merge((ser,ser["values"][w[keys[0][t]]]) for ser,w in zip(self.series,where)) for t in common]
1955 return {"name":first["name"],"index":[first["index"][t] for t in common],"timed":True,
1956 "delta":first["delta"],"columns":columns,"values":values,"aligned":"time",
1957 "used":{ser["name"]:len(common) for ser in self.series},"summed":summed}
1959 def _combined_info(self) -> dict|None:
1960 """Summary of `combined_series` for the browser: `steps`, `columns`,
1961 `aligned`, `delta`, `first` and `last` labels, `summed`, `index` (all
1962 step labels) or `error`"""
1963 if not self.series:
1964 return None
1965 try:
1966 ser = self.combined_series()
1967 except CaseError as err:
1968 return {"error":str(err)}
1969 return {"steps":len(ser["values"]),"columns":len(ser["columns"]),"aligned":ser["aligned"],
1970 "delta":ser["delta"],"first":ser["index"][0],"last":ser["index"][-1],
1971 "summed":len(ser["summed"]),"index":list(ser["index"])}
1973 def series_values(self,table:str,column:str) -> list[list[float]]:
1974 """Return the values of `table.column` at every step of the series:
1975 one row per step, one value per row of `table` (case values where
1976 the series has none)"""
1977 names = [c["name"] for c in COLUMNS[table]]
1978 k = names.index(column)
1979 base = [r[k] for r in self.tables[table]]
1980 ser = self.combined_series()
1981 if not ser: 1981 ↛ 1982line 1981 didn't jump to line 1982 because the condition on line 1981 was never true
1982 return [base]
1983 rows = [list(base) for _ in ser["values"]]
1984 where = {r[0]:n for n,r in enumerate(self.tables["bus"])}
1985 for j,name in enumerate(ser["columns"]):
1986 t,c,key = name.split(".")
1987 if t != table or c != column:
1988 continue
1989 n = where[int(key)] if t == "bus" else int(key) - 1
1990 for row,values in zip(rows,ser["values"]):
1991 row[n] = values[j]
1992 return rows
1994 def at_step(self,step:int) -> "Case":
1995 """Return a copy of the case with the series values of `step`
1996 (counted from 0); the copy has no series"""
1997 ser = self.combined_series()
1998 if not ser or not 0 <= step < len(ser["values"]):
1999 raise CaseError(f"the case has no series step {step+1}")
2000 case = Case(name=self.name)
2001 case.version,case.baseMVA = self.version,self.baseMVA
2002 case.tables = copy.deepcopy(self.tables)
2003 case.geodata,case.geotags = copy.deepcopy(self.geodata),list(self.geotags)
2004 where = {r[0]:n for n,r in enumerate(self.tables["bus"])}
2005 for name,value in zip(ser["columns"],ser["values"][step]):
2006 table,column,key = name.split(".")
2007 n = where[int(key)] if table == "bus" else int(key) - 1
2008 k = [c["name"] for c in COLUMNS[table]].index(column)
2009 case.tables[table][n][k] = value
2010 return case
2012 def apply_step(self,step:int) -> int:
2013 """Copy the values of series step `step` (counted from 0) of
2014 `combined_series` into the case tables, through `set_value`; return
2015 the number of values that changed. The series is kept.
2017 >>> case = Case.builtin("case9")
2018 >>> _ = case.set_series(["bus.Pd.5","gen.Pmax.1"],[[80,250],[120,200]],["a","b"])
2019 >>> case.apply_step(1)
2020 2
2021 >>> case.tables["bus"][4][2],case.tables["gen"][0][8]
2022 (120.0, 200.0)
2023 """
2024 ser = self.combined_series()
2025 if not ser or not 0 <= step < len(ser["values"]):
2026 raise CaseError(f"the case has no series step {step+1}")
2027 where = {r[0]:n for n,r in enumerate(self.tables["bus"])}
2028 changed = 0
2029 for name,value in zip(ser["columns"],ser["values"][step]):
2030 table,column,key = name.split(".")
2031 n = where[int(key)] if table == "bus" else int(key) - 1
2032 k = [c["name"] for c in COLUMNS[table]].index(column)
2033 if self.tables[table][n][k] != value:
2034 self.set_value(table,n,column,value)
2035 changed += 1
2036 return changed
2038 def series_window(self,window:list|tuple|None=None) -> tuple[int,int]:
2039 """Return the combined series steps `(first, last)` (counted from 0,
2040 both included) that a multistep OPF solves: `window`, a pair of step
2041 numbers counted from 0, or all steps when `window` is `None`
2042 (issue #157)
2044 >>> case = Case.builtin("case9")
2045 >>> _ = case.set_series(["bus.Pd.5"],[[80],[90],[100],[110]])
2046 >>> case.series_window(), case.series_window([1,2])
2047 ((0, 3), (1, 2))
2049 Exceptions
2050 ----------
2052 - `CaseError`: no series, `window` not two whole numbers, or a
2053 window outside the series or ending before it starts
2054 """
2055 ser = self.combined_series()
2056 if not ser:
2057 raise CaseError("the case has no time series")
2058 steps = len(ser["values"])
2059 if window is None:
2060 return 0,steps - 1
2061 try:
2062 first,last = window
2063 if any(isinstance(x,bool) or float(x) != int(x) for x in (first,last)):
2064 raise ValueError
2065 first,last = int(first),int(last)
2066 except (TypeError,ValueError) as err:
2067 raise CaseError("the multistep window must be two step numbers [first, last]") from err
2068 if not 0 <= first <= last < steps:
2069 raise CaseError(f"the multistep window (steps {first+1} to {last+1}) must lie within "
2070 f"the {steps} series step(s) and not end before it starts")
2071 return first,last
2073 def _series_input(self,window:list|tuple|None=None) -> dict:
2074 """Per-step case values for `ppedit._cvxopf.runopf` (`series` argument)
2075 over the steps of `series_window(window)`; `first` is the first step
2076 of the window in the combined series; `CaseError` when a step has
2077 `Pmin > Pmax`"""
2078 ser = self.combined_series()
2079 first,last = self.series_window(window)
2080 index = list(ser["index"][first:last+1])
2081 out = {"T":len(index),"delta":ser["delta"],"index":index,"first":first,
2082 "steps":len(ser["values"])}
2083 for table,column in (("bus","Pd"),("bus","Qd"),("gen","Pmin"),("gen","Pmax"),
2084 ("dcline","Pmin"),("dcline","Pmax")):
2085 key = column if table == "bus" else f"{table}_{column}"
2086 out[key] = self.series_values(table,column)[first:last+1]
2087 for table in ("gen","dcline"):
2088 for n in range(len(self.tables[table])):
2089 for t,(lo,hi) in enumerate(zip(out[f"{table}_Pmin"],out[f"{table}_Pmax"])):
2090 if lo[n] > hi[n]:
2091 raise CaseError(f"series step {first+t+1} ({index[t]}): "
2092 f"{table} {n+1} has Pmin {lo[n]:g} > Pmax {hi[n]:g}")
2093 out["gen_limited"] = sorted({int(x.split(".")[2]) - 1 for x in ser["columns"]
2094 if x.startswith("gen.")})
2095 names = [c["name"] for c in COLUMNS["storage"]]
2096 out["storage"] = [{"row":n,"gen":int(r[0])-1,"bus":None if r[1] == -1 else int(r[1]),
2097 **{k:float(v) for k,v in zip(names[2:-1],r[2:-1])}}
2098 for n,r in enumerate(self.tables["storage"]) if r[-1] == 1]
2099 out["storage_rows"] = len(self.tables["storage"])
2100 return out
2102 def apply_result(self,result:dict):
2103 """Copy a solution's bus voltages, generator outputs and DC line flows into the case
2105 DC line `Pf`, `Pt`, `Qf` and `Qt` are copied for in-service lines.
2106 """
2107 if not result.get("success"): 2107 ↛ 2108line 2107 didn't jump to line 2108 because the condition on line 2107 was never true
2108 raise CaseError("cannot apply a failed solution")
2109 if len(result["bus"]) != len(self.tables["bus"]) \ 2109 ↛ 2112line 2109 didn't jump to line 2112 because the condition on line 2109 was never true
2110 or len(result["gen"]) != len(self.tables["gen"]) \
2111 or len(result.get("dcline",[])) != len(self.tables["dcline"]):
2112 raise CaseError("solution does not match the case (it was edited)")
2113 for row,res in zip(self.tables["bus"],result["bus"]):
2114 row[7],row[8] = res["Vm"],res["Va"]
2115 for row,res in zip(self.tables["gen"],result["gen"]):
2116 row[1],row[2] = res["Pg"],res["Qg"]
2117 for row,res in zip(self.tables["dcline"],result.get("dcline",[])):
2118 if res["solved"]:
2119 row[3:7] = [res["Pf"],res["Pt"],res["Qf"],res["Qt"]]
2121 # ----- checking and solving -----
2123 def validate(self) -> list[dict]:
2124 """Check the case for errors and likely mistakes
2126 Returns
2127 -------
2129 - `list[dict]`: issues, each with `level` (`error` or `warning`),
2130 `table`, `row` (index or `None`), `column`, and `message`.
2131 An empty list means no issues were found.
2132 """
2133 issues = []
2134 def add(level,table,row,column,message):
2135 issues.append({"level":level,"table":table,"row":row,
2136 "column":column,"message":message})
2137 bus,gen,branch,dcline = (self.tables[t] for t in ("bus","gen","branch","dcline"))
2138 if not bus:
2139 add("error","bus",None,None,"case has no buses")
2140 numbers = {}
2141 for n,row in enumerate(bus):
2142 if row[0] < 0: 2142 ↛ 2143line 2142 didn't jump to line 2143 because the condition on line 2142 was never true
2143 add("error","bus",n,"bus_i","bus number must not be negative")
2144 elif row[0] == 0: 2144 ↛ 2145line 2144 didn't jump to line 2145 because the condition on line 2144 was never true
2145 add("warning","bus",n,"bus_i","bus number 0 is read as 'unset' by GridLAB-D module pypower")
2146 if row[0] in numbers: 2146 ↛ 2147line 2146 didn't jump to line 2147 because the condition on line 2146 was never true
2147 add("error","bus",n,"bus_i",f"bus {row[0]} duplicates row {numbers[row[0]]+1}")
2148 numbers.setdefault(row[0],n)
2149 if row[12] > row[11]: 2149 ↛ 2150line 2149 didn't jump to line 2150 because the condition on line 2149 was never true
2150 add("error","bus",n,"Vmin","Vmin exceeds Vmax")
2151 if row[7] <= 0: 2151 ↛ 2152line 2151 didn't jump to line 2152 because the condition on line 2151 was never true
2152 add("warning","bus",n,"Vm","voltage magnitude is not positive")
2153 refs = [n for n,r in enumerate(bus) if r[1] == 3]
2154 if bus and not refs:
2155 add("error","bus",None,"type","no reference (REF) bus")
2156 for n in refs[1:]: 2156 ↛ 2157line 2156 didn't jump to line 2157 because the loop on line 2156 never started
2157 add("warning","bus",n,"type","more than one REF bus")
2158 online = {}
2159 for n,row in enumerate(gen):
2160 if row[0] not in numbers: 2160 ↛ 2161line 2160 didn't jump to line 2161 because the condition on line 2160 was never true
2161 add("error","gen",n,"bus",f"bus {row[0]} does not exist")
2162 if row[9] > row[8]: 2162 ↛ 2163line 2162 didn't jump to line 2163 because the condition on line 2162 was never true
2163 add("error","gen",n,"Pmin","Pmin exceeds Pmax")
2164 if row[4] > row[3]: 2164 ↛ 2165line 2164 didn't jump to line 2165 because the condition on line 2164 was never true
2165 add("error","gen",n,"Qmin","Qmin exceeds Qmax")
2166 if row[7] == 1:
2167 online.setdefault(row[0],[]).append(n)
2168 for n,row in enumerate(dcline):
2169 for j,col in ((0,"fbus"),(1,"tbus")):
2170 if row[j] not in numbers:
2171 add("error","dcline",n,col,f"bus {row[j]} does not exist")
2172 elif row[2] == 1:
2173 online.setdefault(row[j],[]).append(None) # a DC line terminal is a PV source
2174 if row[0] == row[1]:
2175 add("error","dcline",n,"tbus","DC line connects a bus to itself")
2176 if row[9] > row[10]:
2177 add("error","dcline",n,"Pmin","Pmin exceeds Pmax")
2178 if row[11] > row[12]: 2178 ↛ 2179line 2178 didn't jump to line 2179 because the condition on line 2178 was never true
2179 add("error","dcline",n,"QminF","QminF exceeds QmaxF")
2180 if row[13] > row[14]: 2180 ↛ 2181line 2180 didn't jump to line 2181 because the condition on line 2180 was never true
2181 add("error","dcline",n,"QminT","QminT exceeds QmaxT")
2182 if row[16] >= 1:
2183 add("error","dcline",n,"loss1","loss1 must be less than 1")
2184 elif row[16] < 0: 2184 ↛ 2185line 2184 didn't jump to line 2185 because the condition on line 2184 was never true
2185 add("warning","dcline",n,"loss1","loss1 is negative")
2186 for k,col in ((7,"Vf"),(8,"Vt")):
2187 if row[k] <= 0: 2187 ↛ 2188line 2187 didn't jump to line 2188 because the condition on line 2187 was never true
2188 add("warning","dcline",n,col,"voltage setpoint is not positive")
2189 if row[2] == 1 and not row[9] <= row[3] <= row[10]:
2190 add("warning","dcline",n,"Pf",
2191 "Pf is outside Pmin..Pmax (power flow uses Pf as given)")
2192 for n,row in enumerate(bus):
2193 if row[1] in (2,3) and row[0] not in online:
2194 add("warning","bus",n,"type",
2195 f"{BUS_TYPES[row[1]]} bus {row[0]} has no in-service generator "
2196 "(the solver will treat it as PQ)")
2197 connected = set()
2198 for n,row in enumerate(branch):
2199 for j,col in ((0,"fbus"),(1,"tbus")):
2200 if row[j] not in numbers: 2200 ↛ 2201line 2200 didn't jump to line 2201 because the condition on line 2200 was never true
2201 add("error","branch",n,col,f"bus {row[j]} does not exist")
2202 if row[0] == row[1]: 2202 ↛ 2203line 2202 didn't jump to line 2203 because the condition on line 2202 was never true
2203 add("error","branch",n,"tbus","branch connects a bus to itself")
2204 if row[2] == 0 and row[3] == 0:
2205 add("error","branch",n,"x","branch has zero impedance")
2206 if row[5] < 0: 2206 ↛ 2207line 2206 didn't jump to line 2207 because the condition on line 2206 was never true
2207 add("error","branch",n,"rateA","rating is negative")
2208 if row[11] > row[12]: 2208 ↛ 2209line 2208 didn't jump to line 2209 because the condition on line 2208 was never true
2209 add("error","branch",n,"angmin","angmin exceeds angmax")
2210 if row[10] == 1:
2211 connected.update((row[0],row[1]))
2212 if len(bus) > 1:
2213 for n,row in enumerate(bus):
2214 if row[0] not in connected and row[1] != 4:
2215 add("warning","bus",n,None,f"bus {row[0]} has no in-service branch")
2216 for table,owner in COST_TABLES.items():
2217 costs,count = self.tables[table],len(self.tables[owner])
2218 if not costs:
2219 continue
2220 if table == "gencost" and len(costs) not in (count,2*count): 2220 ↛ 2221line 2220 didn't jump to line 2221 because the condition on line 2220 was never true
2221 add("error",table,None,None,
2222 f"{len(costs)} cost rows for {count} generators "
2223 f"(need {count} or {2*count})")
2224 elif table == "dclinecost" and len(costs) != count:
2225 add("error",table,None,None,
2226 f"{len(costs)} cost rows for {count} DC lines (need {count})")
2227 for n,(model,startup,shutdown,ncost,text) in enumerate(costs):
2228 values = _costs_list(text)
2229 need = 2*ncost if model == 1 else ncost
2230 if len(values) != need:
2231 add("error",table,n,"costs",
2232 f"{COST_MODELS.get(model,'?')} with ncost={ncost} needs "
2233 f"{need} values, found {len(values)}")
2234 if model == 1:
2235 xs = values[0::2]
2236 if any(b < a for a,b in zip(xs,xs[1:])): 2236 ↛ 2237line 2236 didn't jump to line 2237 because the condition on line 2236 was never true
2237 add("error",table,n,"costs","piecewise MW points must increase")
2238 if startup < 0 or shutdown < 0: 2238 ↛ 2239line 2238 didn't jump to line 2239 because the condition on line 2238 was never true
2239 add("error",table,n,"startup","startup/shutdown cost is negative")
2240 owners = {}
2241 for n,row in enumerate(self.tables["storage"]):
2242 gen_i,bus_i,es,emin,emax,smax,eta_ch,eta_dis,loss,aging,eend,status = row
2243 if not 1 <= gen_i <= len(gen): 2243 ↛ 2244line 2243 didn't jump to line 2244 because the condition on line 2243 was never true
2244 add("error","storage",n,"gen_i",f"generator row {gen_i} does not exist")
2245 elif status == 1:
2246 if gen_i in owners:
2247 add("error","storage",n,"gen_i",f"generator {gen_i} already discharges "
2248 f"storage row {owners[gen_i]+1}")
2249 owners.setdefault(gen_i,n)
2250 if gen[gen_i-1][9] > 0:
2251 add("warning","storage",n,"gen_i",f"generator {gen_i} has Pmin "
2252 f"{gen[gen_i-1][9]:g} > 0, so the storage must always discharge")
2253 if gen[gen_i-1][7] != 1:
2254 add("warning","storage",n,"gen_i",f"generator {gen_i} is out of service, "
2255 "so the storage cannot discharge")
2256 if bus_i != -1 and bus_i not in numbers: 2256 ↛ 2257line 2256 didn't jump to line 2257 because the condition on line 2256 was never true
2257 add("error","storage",n,"bus_i",f"bus {bus_i} does not exist")
2258 if emin < 0: 2258 ↛ 2259line 2258 didn't jump to line 2259 because the condition on line 2258 was never true
2259 add("error","storage",n,"Emin","Emin is negative")
2260 if emin > emax: 2260 ↛ 2261line 2260 didn't jump to line 2261 because the condition on line 2260 was never true
2261 add("error","storage",n,"Emin","Emin exceeds Emax")
2262 elif not emin <= es <= emax:
2263 add("error","storage",n,"Es","Es is outside Emin..Emax")
2264 if eend != -1 and not emin <= eend <= emax:
2265 add("error","storage",n,"Eend","Eend is outside Emin..Emax (-1 leaves it free)")
2266 if smax <= 0:
2267 add("error","storage",n,"Smax","Smax must be positive")
2268 for col,val in (("eta_ch",eta_ch),("eta_dis",eta_dis)):
2269 if not 0 < val <= 1:
2270 add("error","storage",n,col,f"{col} must be in (0, 1]")
2271 if not 0 <= loss < 1: 2271 ↛ 2272line 2271 didn't jump to line 2272 because the condition on line 2271 was never true
2272 add("error","storage",n,"self_discharge","self_discharge must be in [0, 1)")
2273 if aging < 0: 2273 ↛ 2274line 2273 didn't jump to line 2274 because the condition on line 2273 was never true
2274 add("error","storage",n,"aging","aging cost is negative")
2275 elif aging == 0 and (eta_ch < 1 or eta_dis < 1): 2275 ↛ 2276line 2275 didn't jump to line 2276 because the condition on line 2275 was never true
2276 add("warning","storage",n,"aging","lossy storage with no aging cost may "
2277 "charge and discharge at once to waste energy")
2278 if self.tables["areas"]:
2279 used = {}
2280 for row in bus:
2281 used[row[6]] = used.get(row[6],0) + 1
2282 listed = {}
2283 for n,(area,ref,_) in enumerate(self.tables["areas"]):
2284 if area in listed:
2285 add("error","areas",n,"area",f"area {area} duplicates row {listed[area]+1}")
2286 listed.setdefault(area,n)
2287 if ref not in numbers:
2288 add("error","areas",n,"price_ref_bus",f"bus {ref} does not exist")
2289 elif bus[numbers[ref]][6] != area:
2290 add("warning","areas",n,"price_ref_bus",
2291 f"price reference bus {ref} is in area {bus[numbers[ref]][6]}, not {area}")
2292 if area not in used:
2293 add("warning","areas",n,"area",f"area {area} has no buses")
2294 for area in sorted(set(used) - set(listed)):
2295 add("warning","areas",None,None,
2296 f"area {area} ({used[area]} bus(es)) has no areas row")
2297 if self.geodata:
2298 seen = {}
2299 for n,row in enumerate(self.geodata):
2300 if row[0] not in numbers:
2301 add("warning","bus",None,None,
2302 f"geodata row {n+1}: bus {row[0]} does not exist")
2303 elif row[0] in seen:
2304 add("warning","bus",numbers[row[0]],None,
2305 f"bus {row[0]} has more than one geodata row (row {seen[row[0]]+1} is used)")
2306 seen.setdefault(row[0],n)
2307 missing = [str(r[0]) for r in bus if r[0] not in seen]
2308 if missing:
2309 add("warning","bus",None,None,f"{len(missing)} bus(es) have no geodata: "
2310 + ", ".join(missing[:10]) + (", ..." if len(missing) > 10 else ""))
2311 return issues
2313 def solve(self,kind:str="pf",algorithm:str|None=None,options:dict|None=None,
2314 multistep:bool=False,job=None,window:list|tuple|None=None) -> dict:
2315 """Run a PYPOWER power flow (`pf`) or optimal power flow (`opf`)
2317 Arguments
2318 ---------
2320 - `kind`: `pf` or `opf` (OPF needs `gencost`)
2322 - `algorithm`: for `pf`, a key of `PF_SOLVERS` (`NR`, the
2323 default, `NR-SC`, `NR-SH`, `NR-IP`, `NR-IC`, `NR-IH`, `FDXB`,
2324 `FDBX`, `GS`, or `ZG`); for `opf`, a key of
2325 `OPF_SOLVERS` (`PIPS`, the default, `PIPS-SC`, `IPOPT`, or a
2326 DC OPF solver `DC-PIPS`, `DC-PIPS-SC`, `DC-IPOPT`, `DC-CPLEX`,
2327 `DC-MOSEK`, `DC-GUROBI`; or a cvxopf formulation `CVXOPF-AC`,
2328 `CVXOPF-SOCP`, `CVXOPF-DC`, `CVXOPF-1NODE`); `solvers()` lists
2329 those installed
2331 - `options`: solve options for the `CVXOPF-*` solvers (ignored by
2332 the others): `preparation` (`default` or `recommended`, the
2333 per-model numerical preparation profile), `solver` (CVXPY
2334 solver for the convex models; default CLARABEL), `verbose`
2335 (solver output in `log`), and `solver_options` (a dict of other
2336 solver keyword arguments, e.g. `{"max_iter": 500}`)
2338 - `multistep`: solve the time series (`Case.series`) as one
2339 multistep OPF (issue #124); needs `opf`, a `CVXOPF-*` solver and
2340 a series (see below)
2342 - `window`: the steps a multistep OPF solves, `[first, last]`
2343 (counted from 0, both included) of `combined_series`; all steps
2344 when `None` (see `series_window`; issue #157). Ignored without
2345 `multistep`. Storage starts the window with its `Es`.
2347 - `job`: `None`, or a `ppedit._solveproc.SolveJob`: a `CVXOPF-*`
2348 solve then runs in a child process that reports its progress
2349 to `job` (phase, IPOPT iteration and infeasibility) and that
2350 `job.stop()` ends; the result is then a failure with `stopped`
2351 true. Other solvers ignore `job` (they run in this process).
2352 The server passes one with every solve (`/api/solve/progress`,
2353 `/api/solve/stop`).
2355 Returns
2356 -------
2358 - `dict`: `success`, `kind`, `algorithm`, `solver` (its label),
2359 `dc` (DC OPF: flat voltages, no reactive power), `iterations` (PF), `objective`
2360 (OPF, $/h), `losses_MW`, `log` (solver text output), and the rows
2361 `bus` (`bus_i`, `Vm`, `Va`, `lam_P`), `gen` (`bus`, `Pg`, `Qg`),
2362 `branch` (`fbus`, `tbus`, `PF`, `QF`, `PT`, `QT`,
2363 `loading_pct` of `rateA`, or `None` when unrated), and `dcline`
2364 (`fbus`, `tbus`, `solved`, `Pf`, `Pt`, `Qf`, `Qt`, `Vf`, `Vt`,
2365 `loss_MW`, and for OPF the multipliers `mu_Pmin`, `mu_Pmax`
2366 in $/MWh). `losses_MW` includes the DC line losses, which are
2367 also given alone as `dcline_losses_MW`. `areas` has a row for
2368 each bus area (see below). `messages` lists the solver's errors
2369 and warnings as `{"level": "error"|"warning", "message"}`,
2370 with `detail` when ppedit can say what a warning means (see
2371 below); `options` gives the cvxopf solve options used
2372 (`None` for other solvers). `extended` maps `bus`, `gen`,
2373 `branch` and `dcline` to one row per case row with the values
2374 of `RESULT_COLUMNS[table]` (PYPOWER's extended columns:
2375 branch flows, and for OPF the prices and Kuhn-Tucker
2376 multipliers); a value is `None` when the solver does not give
2377 it (multipliers for PF and the `CVXOPF-*` solvers, flows for
2378 `CVXOPF-1NODE`).
2380 `messages` has an error when the solver fails or does not
2381 converge, and warnings for buses solved as isolated, DC lines not
2382 solved, data the solver does not model (cvxopf), cvxopf's warnings,
2383 an SOCP relaxation that is not exact, and the distinct Python
2384 warnings the solver raised (at most `SOLVER_WARNINGS`). Each is
2385 also written to `log`. Warnings about isolated buses, unsolved DC
2386 lines and cvxopf's notes and warnings have a `detail` (decision
2387 #53): `explain` (what the warning means physically), `constraints`
2388 (rows of `constraint`, `element`, `table`, `row` and `value`: the
2389 constraints involved and the case rows they belong to, at most 20)
2390 and `more` (constraints not listed). cvxopf's per-element warnings
2391 are grouped (one message for all `rateA` = 0 branches) and refer to
2392 case rows and bus numbers, not cvxopf's internal indexes.
2394 A multistep OPF builds every step of the series in one cvxopf
2395 problem (`build_opf_multistep`, steps `delta` hours long) and
2396 returns the first step in the layout above, plus `multistep`
2397 (`steps`, `delta`, `index`: the step labels, `series`: the series
2398 names, `window`: `[first, last]` of the steps solved in the combined
2399 series, and `total`: its number of steps), `horizon_objective`
2400 (cvxopf's objective over the horizon, $: each step's cost rate
2401 times `delta`) and `steps`: one result per step with `label`,
2402 `success`, `objective` (that step's generator and DC line cost,
2403 $/h), `losses_MW`, `dcline_losses_MW`, `bus`, `gen`, `branch`,
2404 `dcline`, `areas` (computed with that step's loads), `extended`
2405 and `log` (that step's report; the top-level `log` holds the notes
2406 and solver output common to all steps). The steps are coupled only
2407 by the shared problem: there are no ramp limits, storage or other
2408 constraints between steps. `messages` cover the whole horizon.
2409 Other results have `multistep` `None`.
2411 A failure has an error in `messages`, empty rows, and `stopped`
2412 (true when `job.stop()` ended the solve). A solve run with `job`
2413 whose child process dies (e.g. killed by the operating system for
2414 lack of memory) fails with its exit code instead of stopping the
2415 server.
2417 Buses with no in-service branch are solved as isolated (type NONE)
2418 without changing the case; `log` names them. DC lines are modeled
2419 as in PYPOWER's `toggle_dcline`: each in-service line is a pair of
2420 generators at its terminal buses, which become PV buses held at
2421 `Vf` and `Vt`; power flow keeps `Pf` and sets `Pt = Pf - (loss0 +
2422 loss1*Pf)`, and OPF dispatches `Pf` within `Pmin..Pmax` at the
2423 `dclinecost` cost (zero if there is none). DC lines that are out of
2424 service or touch an isolated bus are not solved (`solved` is
2425 false, flows 0).
2427 Each `areas` result row sums the buses with that `area` number:
2428 `area`, `name` (from the `areas` table, `""` if none), `buses` (count), in-service generation `Pg` and `Qg`, load
2429 `Pd` and `Qd`, `shunt_MW` (`Gs*Vm^2`), `losses_MW` (AC and DC lines
2430 with both ends in the area), `export_MW` (net real power leaving the
2431 area over AC and DC ties, measured at its own end of each tie, so
2432 `Pg = Pd + shunt_MW + losses_MW + export_MW`), `price_ref_bus` (from
2433 the `areas` table, or `None`), and for OPF `lam_P`, the price
2434 ($/MWh) at the price reference bus. Losses on ties belong to no
2435 area: they are the sum of all `export_MW`. Buses that are not
2436 solved (type NONE or isolated) count only toward `buses`: their
2437 load, shunts and generators are left out of the sums.
2439 The `CVXOPF-*` solvers pass the case to cvxopf (`ac`: full AC with
2440 IPOPT; `socp`: second-order cone relaxation, with `Vm` = sqrt(w)
2441 and `Va` from cvxopf's voltage recovery; `lossy_dc`: network-flow
2442 approximation, flat voltages, `PT = -PF`; `singlenode_dc`: copper
2443 plate, flat voltages and no `branch` rows). cvxopf gives no
2444 multipliers, so `lam_P`, `mu_Pmin` and `mu_Pmax` are `None`. It
2445 has no reactive power costs (those rows are ignored) and models DC
2446 lines without `loss0`, terminal reactive power or voltage set
2447 points (the copper plate ignores them); `log` lists these notes
2448 and cvxopf's warnings. cvxopf accepts piecewise-linear costs.
2450 Exceptions
2451 ----------
2453 - `CaseError`: the case has validation errors, OPF without costs,
2454 an unknown algorithm, a solver whose module is not installed,
2455 invalid cvxopf `options`, or a multistep OPF with another solver,
2456 without a series, with a `window` outside the series, with a
2457 step where `Pmin > Pmax`, or with
2458 generator limits in the series and the `recommended` preparation
2459 """
2460 errors = [x for x in self.validate() if x["level"] == "error"]
2461 if errors:
2462 raise CaseError(f"case has {len(errors)} error(s); first: "
2463 f"{errors[0]['table']}: {errors[0]['message']}")
2464 from pypower8.runpf import runpf # pylint: disable=import-outside-toplevel
2465 from pypower8.runopf import runopf # pylint: disable=import-outside-toplevel
2466 from pypower8.ppoption import ppoption # pylint: disable=import-outside-toplevel
2467 if kind not in ("pf","opf"): 2467 ↛ 2468line 2467 didn't jump to line 2468 because the condition on line 2467 was never true
2468 raise CaseError("kind must be 'pf' or 'opf'")
2469 algs = PF_SOLVERS if kind == "pf" else OPF_SOLVERS
2470 if algorithm is None:
2471 algorithm = "NR" if kind == "pf" else "PIPS"
2472 if algorithm not in algs:
2473 raise CaseError(f"{kind.upper()} algorithm must be one of {', '.join(algs)}")
2474 if kind == "opf" and not self.tables["gencost"]: 2474 ↛ 2475line 2474 didn't jump to line 2475 because the condition on line 2474 was never true
2475 raise CaseError("OPF needs generator cost data (gencost)")
2476 dc = kind == "opf" and OPF_SOLVERS[algorithm][1]
2477 cvx = kind == "opf" and isinstance(OPF_SOLVERS[algorithm][2],str)
2478 if kind == "opf" and OPF_SOLVERS[algorithm][3] \
2479 and importlib.util.find_spec(OPF_SOLVERS[algorithm][3]) is None:
2480 raise CaseError(f"OPF solver {algorithm} needs the Python module "
2481 f"'{OPF_SOLVERS[algorithm][3]}', which is not installed")
2482 series = None
2483 if multistep:
2484 if not cvx:
2485 raise CaseError("multistep OPF needs a CVXOPF-* solver")
2486 if not self.series:
2487 raise CaseError("multistep OPF needs a time series (import one on the Multistep tab)")
2488 series = self._series_input(window)
2489 cvx_options = None
2490 if cvx:
2491 from ppedit._cvxopf import solve_options # pylint: disable=import-outside-toplevel
2492 try:
2493 cvx_options = solve_options(options,OPF_SOLVERS[algorithm][2])
2494 except ValueError as err:
2495 raise CaseError(str(err)) from err
2496 if series and series["gen_limited"] and cvx_options["preparation"] != "default":
2497 raise CaseError("per-step generator limits (gen Pmin, Pmax series) need the "
2498 "default cvxopf preparation (Settings tab)")
2499 if series and series["storage"] and cvx_options["preparation"] != "default":
2500 raise CaseError("storage needs the default cvxopf preparation (Settings tab)")
2501 ppc = self.to_ppc(arrays=True)
2502 # buses with no in-service branch make the solver fail; solve them as isolated
2503 connected = {r[k] for r in self.tables["branch"] if r[10] == 1 and r[0] != r[1] for k in (0,1)}
2504 isolated = [r[0] for r in self.tables["bus"] if r[1] != 4 and r[0] not in connected] \
2505 if len(self.tables["bus"]) > 1 else []
2506 for n,row in enumerate(self.tables["bus"]):
2507 if row[0] in isolated:
2508 ppc["bus"][n,1] = 4
2509 if kind == "pf":
2510 opt = ppoption(PF_ALG=PF_SOLVERS[algorithm][1],VERBOSE=0,OUT_ALL=0)
2511 elif cvx:
2512 opt = ppoption(VERBOSE=0,OUT_ALL=0)
2513 elif dc:
2514 opt = ppoption(PF_DC=1,OPF_ALG_DC=OPF_SOLVERS[algorithm][2],VERBOSE=0,OUT_ALL=0)
2515 else:
2516 opt = ppoption(OPF_ALG=OPF_SOLVERS[algorithm][2],VERBOSE=0,OUT_ALL=0)
2517 info = {"kind":kind,"algorithm":algorithm,"solver":algs[algorithm][0],"dc":dc,
2518 "options":cvx_options,"multistep":None if series is None else
2519 {"steps":series["T"],"delta":series["delta"],"index":series["index"],
2520 "series":[x["name"] for x in self.series],
2521 "window":[series["first"],series["first"]+series["T"]-1],"total":series["steps"]}}
2522 log = io.StringIO()
2523 messages = []
2524 def message(level,text,detail=None):
2525 messages.append({"level":level,"message":text} | ({"detail":detail} if detail else {}))
2526 log.write(text + "\n")
2527 busrow = {r[0]:n for n,r in enumerate(self.tables["bus"])}
2528 active = [n for n,r in enumerate(self.tables["storage"]) if r[-1] == 1]
2529 if active and series is None:
2530 message("warning",f"Storage row(s) {', '.join(str(n+1) for n in active)} not modeled: "
2531 "storage is solved only by multistep CVXOPF OPF (its generators run as ordinary "
2532 "generators)",_message_detail(STORAGE_EXPLAIN,[{"constraint":"energy balance "
2533 "left out of the solve","element":f"storage {n+1}","table":"storage","row":n,
2534 "value":None} for n in active]))
2535 if isolated:
2536 message("warning",f"Solved bus(es) {', '.join(str(x) for x in isolated)} as isolated "
2537 "(type NONE): no in-service branch",_message_detail(ISOLATED_EXPLAIN,
2538 [{"constraint":"bus left out of the solve (type NONE): no voltage, its load, "
2539 "shunts and generators are not served","element":f"bus {x}","table":"bus",
2540 "row":busrow[x],"value":None} for x in isolated]))
2541 if "dcline" in ppc:
2542 from ppedit._dcline import add_dclines # pylint: disable=import-outside-toplevel
2543 dead = {r[0] for r in self.tables["bus"] if r[1] == 4} | set(isolated)
2544 cut = [n for n,r in enumerate(self.tables["dcline"])
2545 if r[2] == 1 and (r[0] in dead or r[1] in dead)]
2546 for n in cut:
2547 ppc["dcline"][n,2] = 0
2548 if cut:
2549 message("warning",f"DC line(s) {', '.join(str(n+1) for n in cut)} not solved: "
2550 "terminal bus is isolated",_message_detail(DCLINE_CUT_EXPLAIN,
2551 [{"constraint":"Pf = Pt = 0 (line taken out of the solve)",
2552 "element":f"dcline {n+1}","table":"dcline","row":n,"value":None} for n in cut]))
2553 if not cvx:
2554 ppc = add_dclines(ppc)
2555 what = ("multistep " if series else "") + ("DC " if dc else "") + kind.upper() \
2556 + f" ({re.sub(r'^(AC|DC): ','',algs[algorithm][0])})"
2557 failed = None
2558 with contextlib.redirect_stdout(log), warnings.catch_warnings(record=True) as caught:
2559 warnings.simplefilter("always")
2560 try:
2561 if kind == "pf":
2562 res,success = runpf(ppc,opt)
2563 res["success"] = bool(success)
2564 elif cvx:
2565 from ppedit._cvxopf import runopf as cvxopf_runopf # pylint: disable=import-outside-toplevel
2566 if job is None:
2567 res = cvxopf_runopf(ppc,OPF_SOLVERS[algorithm][2],log,cvx_options,series)
2568 else:
2569 from ppedit import _solveproc # pylint: disable=import-outside-toplevel
2570 res = _solveproc.run(job,ppc,OPF_SOLVERS[algorithm][2],log,cvx_options,series)
2571 else:
2572 res = runopf(ppc,opt)
2573 except Exception as err: # pylint: disable=broad-exception-caught
2574 _logger.debug("solver failed: %s",err)
2575 failed = err
2576 self._solver_warnings(caught,message)
2577 if failed is not None:
2578 log.write("\n")
2579 message("error",f"{what} failed: {failed}")
2580 out = {"success":False,**info,"log":log.getvalue(),"messages":messages,
2581 "stopped":type(failed).__name__ == "SolveStopped",
2582 "bus":[],"gen":[],"branch":[],"dcline":[],"areas":[],"extended":{}}
2583 if series is not None: # a failed multistep solve has no steps
2584 out.update(steps=[],horizon_objective=None)
2585 return out
2586 dead = {r[0] for r in self.tables["bus"] if r[1] == 4} | set(isolated)
2587 for w in res.get("warnings",[]): # cvxopf notes and warnings (already in log)
2588 messages.append({"level":"warning","message":w["message"]}
2589 | ({"detail":w["detail"]} if w.get("detail") else {}))
2590 if not res["success"]:
2591 message("error",f"{what} did not converge"
2592 + (f" (solver status {res['status']})" if "status" in res else "")
2593 + "; see the solver log on the Results tab")
2594 if series is None:
2595 result = self._solution(res,kind,cvx,info,opt,log,dead)
2596 result["messages"] = messages
2597 return _jsonsafe(result)
2598 common = log.getvalue()
2599 steps = []
2600 for t,step in enumerate(res["steps"]):
2601 label = series["index"][t]
2602 slog = io.StringIO()
2603 slog.write(f"Step {t+1} of {len(res['steps'])} ({label})\n")
2604 out = self.at_step(series["first"]+t)._solution(step,kind,cvx,info,opt,slog,dead) # pylint: disable=protected-access
2605 out["label"] = label
2606 out["storage"] = step.get("storage",[])
2607 steps.append({k:out[k] for k in ("label","success","objective","losses_MW",
2608 "dcline_losses_MW","bus","gen","branch","dcline","storage","areas","extended","log")})
2609 result = dict(steps[0])
2610 result.update(info,label=None,messages=messages,log=common,steps=steps,
2611 horizon_objective=float(res["f"]) if "f" in res else None)
2612 return _jsonsafe(result)
2614 def _solution(self,res,kind,cvx,info,opt,log,dead) -> dict:
2615 """Result rows of one solver result `res` (see `solve`), with the
2616 solver report written to `log`; `dead`: unsolved bus numbers"""
2617 from pypower8.ppoption import ppoption # pylint: disable=import-outside-toplevel
2618 try:
2619 from pypower8.printpf import printpf # pylint: disable=import-outside-toplevel
2620 with warnings.catch_warnings():
2621 warnings.simplefilter("ignore")
2622 if cvx: # no multipliers: report as a power flow, objective first
2623 if "f" in res:
2624 log.write(f"\nObjective Function Value = {res['f']:.2f} $/hr\n")
2625 printpf({k:v for k,v in res.items() if k != "f"},log,
2626 ppoption(opt,OUT_ALL=-1,OUT_SYS_SUM=1,OUT_BUS=1,OUT_GEN=1,
2627 OUT_BRANCH=int(res["flows"])))
2628 else:
2629 printpf(res,log,ppoption(opt,OUT_ALL=1)) # results form: (results, fd, ppopt)
2630 except Exception as err: # pylint: disable=broad-exception-caught
2631 log.write(f"(report unavailable: {err})\n")
2632 dclines = []
2633 for n,d in enumerate(res["dcline"] if "dcline" in res else []):
2634 solved = bool(d[2]) and bool(res["success"])
2635 dclines.append({"fbus":int(d[0]),"tbus":int(d[1]),"solved":solved,
2636 "Pf":float(d[3]),"Pt":float(d[4]),"Qf":float(d[5]),"Qt":float(d[6]),
2637 "Vf":float(d[7]),"Vt":float(d[8]),"loss_MW":float(d[3]-d[4]) if solved else 0.0,
2638 "mu_Pmin":float(d[17]) if kind == "opf" and not cvx else None,
2639 "mu_Pmax":float(d[18]) if kind == "opf" and not cvx else None})
2640 if dclines:
2641 log.write("\nDC lines\n # from to Pf MW Pt MW loss MW"
2642 " Qf MVAr Qt MVAr\n")
2643 for n,d in enumerate(dclines):
2644 log.write(f"{n+1:4d} {d['fbus']:6d} {d['tbus']:6d} " + (
2645 "".join(f"{d[k]:11.2f}" for k in ("Pf","Pt","loss_MW","Qf","Qt"))
2646 if d["solved"] else " (not solved: out of service or isolated)") + "\n")
2647 bus,gen,branch = res["bus"],res["gen"],res["branch"]
2648 result = {
2649 "success": bool(res["success"]),
2650 **info,
2651 "iterations": int(res["iterations"]) if "iterations" in res else None,
2652 "objective": float(res["f"]) if kind == "opf" and "f" in res else None,
2653 "log": log.getvalue(),
2654 "bus": [{"bus_i":int(b[0]),"Vm":float(b[7]),"Va":float(b[8]),
2655 "lam_P":float(b[13]) if kind == "opf" and not cvx and len(b) > 13 else None}
2656 for b in bus],
2657 "gen": [{"bus":int(g[0]),"Pg":float(g[1]),"Qg":float(g[2])} for g in gen],
2658 "branch": [],
2659 "dcline": dclines,
2660 }
2661 losses = 0.0
2662 for b in branch if res.get("flows",True) else []:
2663 pf,qf,pt,qt = (float(x) for x in b[13:17])
2664 rate = float(b[5])
2665 smax = max(math.hypot(pf,qf),math.hypot(pt,qt))
2666 if b[10] == 1:
2667 losses += pf + pt
2668 result["branch"].append({"fbus":int(b[0]),"tbus":int(b[1]),
2669 "PF":pf,"QF":qf,"PT":pt,"QT":qt,
2670 "loading_pct":100*smax/rate if rate > 0 else None})
2671 result["extended"] = _extended(res,kind == "opf" and not cvx,res.get("flows",True))
2672 result["dcline_losses_MW"] = sum(d["loss_MW"] for d in dclines)
2673 result["losses_MW"] = losses + result["dcline_losses_MW"]
2674 result["areas"] = self._area_summary(result,dead)
2675 if result["success"] and (self.tables["areas"] or len(result["areas"]) > 1):
2676 log = io.StringIO()
2677 log.write("\nAreas\n area buses Pg MW Pd MW"
2678 " shunt MW loss MW export MW" + (" price $/MWh" if kind == "opf" and not cvx else "") + "\n")
2679 for a in result["areas"]:
2680 log.write(f"{a['area']:6d} {a['buses']:6d} " + "".join(f"{a[k]:11.2f}"
2681 for k in ("Pg","Pd","shunt_MW","losses_MW","export_MW"))
2682 + (f"{a['lam_P']:13.2f}" if kind == "opf" and a["lam_P"] is not None else "")
2683 + (f" {a['name']}" if a["name"] else "") + "\n")
2684 result["log"] += log.getvalue()
2685 return result
2687 @staticmethod
2688 def _solver_warnings(caught,message):
2689 """Report the distinct Python warnings in `caught` (at most
2690 `SOLVER_WARNINGS`) through `message`"""
2691 seen = {}
2692 for w in caught:
2693 if issubclass(w.category,(DeprecationWarning,PendingDeprecationWarning,FutureWarning)):
2694 continue # about the code, not the solution
2695 key = f"{w.category.__name__}: {str(w.message).strip()}"
2696 seen[key] = seen.get(key,0) + 1
2697 for n,(key,count) in enumerate(seen.items()):
2698 if n == SOLVER_WARNINGS: 2698 ↛ 2699line 2698 didn't jump to line 2699 because the condition on line 2698 was never true
2699 message("warning",f"{len(seen)-n} more distinct solver warning(s) not listed")
2700 break
2701 message("warning",f"Solver warning: {key}" + (f" ({count} times)" if count > 1 else ""))
2703 def _area_summary(self,result,dead):
2704 """Per-area sums of a solution (see `solve`); `dead`: unsolved bus numbers"""
2705 if not result["success"]:
2706 return []
2707 buses = self.tables["bus"]
2708 area = {row[0]:row[6] for row in buses}
2709 refs,names = {},{}
2710 for a,ref,name in self.tables["areas"]:
2711 refs.setdefault(a,ref)
2712 names.setdefault(a,name)
2713 out = {}
2714 for a in sorted(set(area.values())):
2715 out[a] = {"area":a,"name":names.get(a,""),"buses":0,"Pg":0.0,"Qg":0.0,"Pd":0.0,"Qd":0.0,
2716 "shunt_MW":0.0,"losses_MW":0.0,"export_MW":0.0,
2717 "price_ref_bus":refs.get(a),"lam_P":None}
2718 lam = {}
2719 for row,res in zip(buses,result["bus"]):
2720 x = out[row[6]]
2721 x["buses"] += 1
2722 lam[row[0]] = res["lam_P"]
2723 if row[0] in dead:
2724 continue
2725 x["Pd"] += row[2]
2726 x["Qd"] += row[3]
2727 x["shunt_MW"] += row[4]*res["Vm"]**2
2728 for row,res in zip(self.tables["gen"],result["gen"]):
2729 if row[7] == 1 and row[0] in area and row[0] not in dead:
2730 out[area[row[0]]]["Pg"] += res["Pg"]
2731 out[area[row[0]]]["Qg"] += res["Qg"]
2732 ties = [(b[0],b[1],r["PF"],r["PT"]) for b,r in zip(self.tables["branch"],result["branch"])
2733 if b[10] == 1]
2734 ties += [(d["fbus"],d["tbus"],d["Pf"],-d["Pt"]) for d in result["dcline"] if d["solved"]]
2735 for f,t,pf,pt in ties:
2736 if f not in area or t not in area: 2736 ↛ 2737line 2736 didn't jump to line 2737 because the condition on line 2736 was never true
2737 continue
2738 if area[f] == area[t]:
2739 out[area[f]]["losses_MW"] += pf + pt
2740 else:
2741 out[area[f]]["export_MW"] += pf
2742 out[area[t]]["export_MW"] += pt
2743 for x in out.values():
2744 if x["price_ref_bus"] in lam:
2745 x["lam_P"] = lam[x["price_ref_bus"]]
2746 return list(out.values())
2748# ---------------------------------------------------------------------------
2749# module helpers
2750# ---------------------------------------------------------------------------
2752def _extended(res,multipliers,flows):
2753 """Rows of `RESULT_COLUMNS` values of a solver result `res` (see
2754 `Case.solve`); `multipliers`: whether the solver gives OPF multipliers,
2755 `flows`: whether it gives branch flows"""
2756 out = {}
2757 for table,spec in RESULT_COLUMNS.items():
2758 rows = res[table] if table in res else []
2759 if table == "branch" and not flows:
2760 rows = [[]]*len(rows)
2761 out[table] = [[float(row[c["index"]])
2762 if len(row) > c["index"] and (multipliers or not c["opf"]) else None
2763 for c in spec] for row in rows]
2764 return out
2766def solvers() -> dict:
2767 """Return the PF and OPF solvers that can run here
2769 Returns
2770 -------
2772 - `dict`: `pf` and `opf`, each a list of `{"algorithm", "label"}` in
2773 menu order; `opf` lists only the solvers whose Python module is
2774 installed (see `OPF_SOLVERS`), plus `dc` (DC formulation); and
2775 `cvxopf`: `None` when cvxopf is not installed, else the choices of
2776 the `CVXOPF-*` solve options (`Case.solve`): `preparation` and
2777 `solvers`, the installed CVXPY solvers for the convex models
2779 Example
2780 -------
2782 >>> [x["algorithm"] for x in solvers()["pf"]]
2783 ['NR', 'NR-SC', 'NR-SH', 'NR-IP', 'NR-IC', 'NR-IH', 'FDXB', 'FDBX', 'GS', 'ZG']
2784 >>> solvers()["opf"][0]
2785 {'algorithm': 'PIPS', 'label': 'AC: PIPS interior point', 'dc': False}
2786 """
2787 cvx = None
2788 if importlib.util.find_spec("cvxopf") is not None: 2788 ↛ 2796line 2788 didn't jump to line 2796 because the condition on line 2788 was always true
2789 from ppedit._cvxopf import PREPARATIONS # pylint: disable=import-outside-toplevel
2790 try:
2791 import cvxpy # pylint: disable=import-outside-toplevel
2792 installed = [x for x in cvxpy.installed_solvers() if x != "IPOPT"]
2793 except ImportError:
2794 installed = []
2795 cvx = {"preparation":list(PREPARATIONS),"solvers":installed}
2796 return {
2797 "pf":[{"algorithm":k,"label":v[0]} for k,v in PF_SOLVERS.items()],
2798 "opf":[{"algorithm":k,"label":v[0],"dc":v[1]} for k,v in OPF_SOLVERS.items()
2799 if v[3] is None or importlib.util.find_spec(v[3]) is not None],
2800 "cvxopf":cvx,
2801 }
2803def builtin_cases() -> list[str]:
2804 """Return the names of the cases shipped with the `pypower8` package"""
2805 try:
2806 import pypower8 # pylint: disable=import-outside-toplevel
2807 except ImportError:
2808 return []
2809 folder = os.path.dirname(pypower8.__file__)
2810 skip = {"caseformat"}
2811 names = [os.path.splitext(x)[0] for x in os.listdir(folder)
2812 if re.fullmatch(r"case\w+\.py",x)]
2813 def order(name):
2814 m = re.match(r"case(\d+)",name)
2815 return (int(m.group(1)) if m else 99999,name)
2816 return sorted((x for x in names if x not in skip),key=order)
2818def _cost_rows(table,value):
2819 """Read `gencost`/`dclinecost` matrix rows as `[model, startup, shutdown, ncost, costs]`"""
2820 rows = []
2821 for n,row in enumerate(_tolist(value)):
2822 if len(row) < 4: 2822 ↛ 2823line 2822 didn't jump to line 2823 because the condition on line 2822 was never true
2823 raise CaseError(f"{table} row {n+1} has fewer than 4 columns")
2824 model,startup,shutdown,ncost = (_number(row[0],"int"),
2825 _number(row[1]),_number(row[2]),_number(row[3],"int"))
2826 costs = [float(x) for x in row[4:]]
2827 need = 2*ncost if model == 1 else ncost
2828 costs = costs[:need] if len(costs) >= need else costs
2829 rows.append([model,startup,shutdown,ncost,_costs_text(costs)])
2830 return rows
2832def _tolist(value):
2833 if hasattr(value,"tolist"):
2834 value = value.tolist()
2835 if value and not isinstance(value[0],(list,tuple)): 2835 ↛ 2836line 2835 didn't jump to line 2836 because the condition on line 2835 was never true
2836 value = [value]
2837 return [list(x) for x in value]
2839def _jsonsafe(value):
2840 """Replace infinities and NaN (not valid JSON) with strings"""
2841 if isinstance(value,float):
2842 if math.isinf(value):
2843 return "Inf" if value > 0 else "-Inf"
2844 if math.isnan(value): 2844 ↛ 2845line 2844 didn't jump to line 2845 because the condition on line 2844 was never true
2845 return None
2846 return value
2847 if isinstance(value,dict):
2848 return {k:_jsonsafe(v) for k,v in value.items()}
2849 if isinstance(value,(list,tuple)):
2850 return [_jsonsafe(v) for v in value]
2851 return value
2853# ----- geodata helpers -----
2855def _geo_value(value):
2856 """Return an auxiliary geodata value as a number if it reads as one, else text"""
2857 if isinstance(value,bool): 2857 ↛ 2858line 2857 didn't jump to line 2858 because the condition on line 2857 was never true
2858 return int(value)
2859 if isinstance(value,(int,float)):
2860 return value if math.isfinite(value) else str(value)
2861 text = "" if value is None else str(value).strip()
2862 if re.fullmatch(r"[+-]?\d+",text):
2863 return int(text)
2864 try:
2865 number = float(text)
2866 except ValueError:
2867 return text
2868 return number if math.isfinite(number) else text
2870def _geo_rows(rows,tags):
2871 """Check and normalize geodata rows; return `(rows, tags)`"""
2872 if hasattr(tags,"tolist"): 2872 ↛ 2873line 2872 didn't jump to line 2873 because the condition on line 2872 was never true
2873 tags = tags.tolist()
2874 if isinstance(tags,str): 2874 ↛ 2875line 2874 didn't jump to line 2875 because the condition on line 2874 was never true
2875 tags = [tags]
2876 tags = [str(x) for x in tags]
2877 rows = _tolist(rows) if len(rows) else []
2878 width = max((len(r) for r in rows),default=3) - 3
2879 tags += [f"col{k+4}" for k in range(len(tags),width)]
2880 out = []
2881 for n,row in enumerate(rows):
2882 if len(row) < 3: 2882 ↛ 2883line 2882 didn't jump to line 2883 because the condition on line 2882 was never true
2883 raise CaseError(f"geodata row {n+1} has {len(row)} values, "
2884 "expected at least 3 (BUS_I, LAT, LON)")
2885 try:
2886 bus,lat,lon = _number(row[0],"int"),_number(row[1]),_number(row[2])
2887 except CaseError as err:
2888 raise CaseError(f"geodata row {n+1}: {err}") from err
2889 if not -90 <= lat <= 90:
2890 raise CaseError(f"geodata row {n+1}: latitude {lat} is not in -90..90")
2891 if not -180 <= lon <= 180:
2892 raise CaseError(f"geodata row {n+1}: longitude {lon} is not in -180..180")
2893 aux = [_geo_value(v) for v in row[3:3+len(tags)]]
2894 out.append([bus,lat,lon]+aux+[""]*(len(tags)-len(aux)))
2895 return out,tags
2897def _geo_from_ppc(data):
2898 """Read `geodata`/`geotags` from a case dict
2900 `geodata` is a list of rows (named by `geotags`) or a dict of columns
2901 that includes `BUS_I`, `LAT` and `LON`.
2902 """
2903 geo = data.get("geodata")
2904 if geo is None:
2905 return [],[]
2906 if isinstance(geo,dict):
2907 keys = {str(k).upper():k for k in geo}
2908 missing = [c for c in GEODATA_COLUMNS if c not in keys]
2909 if missing: 2909 ↛ 2910line 2909 didn't jump to line 2910 because the condition on line 2909 was never true
2910 raise CaseError(f"geodata is missing column(s) {', '.join(missing)}")
2911 tags = [k for k in geo if str(k).upper() not in GEODATA_COLUMNS]
2912 cols = [geo[keys[c]] for c in GEODATA_COLUMNS] + [geo[k] for k in tags]
2913 cols = [x.tolist() if hasattr(x,"tolist") else list(x) for x in cols]
2914 if len({len(x) for x in cols}) > 1: 2914 ↛ 2915line 2914 didn't jump to line 2915 because the condition on line 2914 was never true
2915 raise CaseError("geodata columns have different lengths")
2916 return _geo_rows([list(r) for r in zip(*cols)],tags)
2917 if not isinstance(geo,(list,tuple)) and not hasattr(geo,"tolist"): 2917 ↛ 2918line 2917 didn't jump to line 2918 because the condition on line 2917 was never true
2918 raise CaseError("geodata must be a list of rows or a dict of columns")
2919 return _geo_rows(geo,data.get("geotags") or [])
2921def _read_geodata_csv(text):
2922 """Parse geodata CSV text; return `(rows, tags)` before checking"""
2923 lines = [r for r in csv.reader(io.StringIO(text.lstrip("\ufeff"))) if any(c.strip() for c in r)]
2924 if not lines:
2925 raise CaseError("geodata CSV is empty")
2926 header = [x.strip() for x in lines[0]]
2927 upper = [x.upper() for x in header]
2928 missing = [c for c in GEODATA_COLUMNS if c not in upper]
2929 if missing:
2930 raise CaseError(f"geodata CSV is missing column(s) {', '.join(missing)} "
2931 f"(found {', '.join(header)})")
2932 index = [upper.index(c) for c in GEODATA_COLUMNS]
2933 aux = [k for k,x in enumerate(upper) if x not in GEODATA_COLUMNS]
2934 rows = []
2935 for line in lines[1:]:
2936 line = line + [""]*(len(header)-len(line))
2937 rows.append([line[k] for k in index] + [line[k] for k in aux])
2938 return rows,[header[k] for k in aux]
2940DCLINECOST_CLASS = "dclinecost"
2941"""GLM runtime class of the DC line cost objects (one per `dclinecost` row,
2942parent the DC line, with the properties of `pypower.gencost`)"""
2944STORAGE_CLASS = "pp_storage"
2945"""GLM runtime class of the storage objects (one per `storage` row, parent
2946its generator, the `storage` columns after `gen_i` as properties)"""
2948GEODATA_CLASS = "pp_geodata"
2949"""GLM runtime class of the auxiliary geodata objects (one per geodata row,
2950parent the bus, one property per tag)"""
2952_GLM_HEADER = {"name","parent","rank","clock","valid_to","latitude","longitude",
2953 "in_svc","out_svc","in","out","flags","groupid","heartbeat","rng_state","guid",
2954 "id","class","library","child_count","schedule_skew","root_uid"}
2956def _glm_tag_names(tags):
2957 """Return a unique GLM property name for each geodata tag"""
2958 names = []
2959 for tag in tags:
2960 name = re.sub(r"\W","_",tag.strip()) or "tag"
2961 if name[0].isdigit(): 2961 ↛ 2962line 2961 didn't jump to line 2962 because the condition on line 2961 was never true
2962 name = "_" + name
2963 while name in _GLM_HEADER or name in names:
2964 name += "_"
2965 names.append(name)
2966 return names
2968def _glm_geo_type(values):
2969 """Return the GLM property type that holds all of `values`"""
2970 if all(isinstance(v,int) for v in values):
2971 return "int64"
2972 if all(isinstance(v,(int,float)) for v in values):
2973 return "double"
2974 return "char256" if all(len(str(v)) < 256 for v in values) else "char1024"
2976def _glm_geo_literal(value):
2977 """Format an auxiliary geodata value for GLM (text is quoted; `"` becomes `'`)"""
2978 if isinstance(value,(int,float)):
2979 return _fmt(value)
2980 return '"' + re.sub(r"\s+"," ",str(value)).replace('"',"'") + '"'
2982def _geo_literal(value):
2983 """Format a geodata value as a Python literal"""
2984 return _fmt(value) if isinstance(value,(int,float)) else json.dumps(value)
2986_LATLON = re.compile(r"^\s*(\d+(?:\.\d*)?)\s*([NSEW])\s*(\d+(?:\.\d*)?)(?:\s*:\s*(\d+(?:\.\d*)?))?\s*$",re.I)
2988def _glm_angle(text,hemispheres):
2989 """Read a GLM latitude/longitude: decimal degrees or `37N25:12.3` style"""
2990 text = _unquote(text)
2991 m = _LATLON.match(text)
2992 if m and m.group(2).upper() in hemispheres:
2993 value = float(m.group(1)) + float(m.group(3))/60 + float(m.group(4) or 0)/3600
2994 return -value if m.group(2).upper() == hemispheres[1] else value
2995 return _number(text)
2997def _glm_complex(real,imag):
2998 """Format two numbers as a GLM complex value `a+bj`"""
2999 sign = "-" if imag < 0 or (imag == 0 and math.copysign(1,imag) < 0) else "+"
3000 return f"{_fmt(real)}{sign}{_fmt(abs(imag))}j"
3002_COMPLEX = re.compile(r"^\s*([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)"
3003 r"(?:\s*([+-]\s*(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)\s*([ijdr]))?")
3005def _glm_complex_value(text):
3006 """Read a GLM complex value (`a+bj`, `a+bi`, polar `a+bd`/`a+br`, or real) as `(real, imag)`"""
3007 text = _unquote(text)
3008 m = _COMPLEX.match(text)
3009 if not m: 3009 ↛ 3010line 3009 didn't jump to line 3010 because the condition on line 3009 was never true
3010 raise CaseError(f"'{text}' is not a complex number")
3011 a = float(m.group(1))
3012 if m.group(2) is None:
3013 return a,0.0
3014 b = float(m.group(2).replace(" ",""))
3015 if m.group(3) in "ij":
3016 return a,b
3017 angle = math.radians(b) if m.group(3) == "d" else b
3018 return a*math.cos(angle),a*math.sin(angle)
3020def _glm_value(table,col,val):
3021 if col["kind"] == "enum":
3022 return col["options"].get(val,str(val))
3023 unit = GLM_UNITS.get(table,{}).get(col["name"])
3024 text = _fmt(val)
3025 if math.isinf(val) if isinstance(val,float) else False: 3025 ↛ 3026line 3025 didn't jump to line 3026 because the condition on line 3025 was never true
3026 text = "+INF" if val > 0 else "-INF"
3027 return f"{text} {unit}" if unit else text
3029# ----- PYPOWER .py parser (no code execution) -----
3031_NAMES = {"inf":math.inf,"Inf":math.inf,"INF":math.inf,"nan":math.nan,
3032 "pi":math.pi,"True":1,"False":0}
3034def _eval(node,env):
3035 """Evaluate a literal-only expression tree"""
3036 if isinstance(node,ast.Constant) and isinstance(node.value,(int,float,str)):
3037 return node.value
3038 if isinstance(node,(ast.List,ast.Tuple)):
3039 return [_eval(x,env) for x in node.elts]
3040 if isinstance(node,ast.Dict):
3041 return {_eval(k,env):_eval(v,env) for k,v in zip(node.keys,node.values)}
3042 if isinstance(node,ast.UnaryOp) and isinstance(node.op,(ast.USub,ast.UAdd)):
3043 val = _eval(node.operand,env)
3044 return -val if isinstance(node.op,ast.USub) else val
3045 if isinstance(node,ast.BinOp) and isinstance(node.op,(ast.Add,ast.Sub,ast.Mult,ast.Div,ast.Pow)):
3046 a,b = _eval(node.left,env),_eval(node.right,env)
3047 if not all(isinstance(x,(int,float)) for x in (a,b)): 3047 ↛ 3048line 3047 didn't jump to line 3048 because the condition on line 3047 was never true
3048 raise CaseError("arithmetic on non-numbers")
3049 ops = {ast.Add:lambda:a+b,ast.Sub:lambda:a-b,ast.Mult:lambda:a*b,
3050 ast.Div:lambda:a/b,ast.Pow:lambda:a**b if abs(b) < 64 else math.nan}
3051 return ops[type(node.op)]()
3052 if isinstance(node,ast.Name):
3053 if node.id in env:
3054 return env[node.id]
3055 if node.id in _NAMES: 3055 ↛ 3057line 3055 didn't jump to line 3057 because the condition on line 3055 was always true
3056 return _NAMES[node.id]
3057 if isinstance(node,ast.Attribute) and isinstance(node.value,ast.Name) \ 3057 ↛ 3059line 3057 didn't jump to line 3059 because the condition on line 3057 was never true
3058 and node.value.id in ("np","numpy","math") and node.attr in _NAMES:
3059 return _NAMES[node.attr]
3060 if isinstance(node,ast.Call): 3060 ↛ 3068line 3060 didn't jump to line 3068 because the condition on line 3060 was always true
3061 func = node.func.attr if isinstance(node.func,ast.Attribute) else \
3062 node.func.id if isinstance(node.func,ast.Name) else None
3063 if func in ("array","matrix","asarray") and node.args: 3063 ↛ 3065line 3063 didn't jump to line 3065 because the condition on line 3063 was always true
3064 return _eval(node.args[0],env)
3065 if func in ("float","int") and len(node.args) == 1:
3066 val = _eval(node.args[0],env)
3067 return float(val) if func == "float" else int(val)
3068 raise CaseError(f"unsupported expression at line {getattr(node,'lineno','?')}")
3070def _is_case(data):
3071 """Check that a dict has the required PYPOWER case keys"""
3072 return all(k in data for k in ("baseMVA","bus","gen","branch"))
3074def _parse_py(text,name):
3075 """Extract the ppc dict from a PYPOWER case file without running it
3077 The case is either assigned to a variable (`ppc = {...}`, optionally
3078 followed by `ppc[key] = ...`) or returned as a dict literal
3079 (`return {...}`).
3080 """
3081 try:
3082 tree = ast.parse(text)
3083 except SyntaxError as err:
3084 raise CaseError(f"invalid Python: {err}") from err
3085 funcs = [x for x in tree.body if isinstance(x,ast.FunctionDef)]
3086 bodies = [f.body for f in funcs if f.name == name] + [f.body for f in funcs] + [tree.body]
3087 for body in bodies: 3087 ↛ 3115line 3087 didn't jump to line 3115 because the loop on line 3087 didn't complete
3088 env,data = {},None
3089 target = None
3090 for stmt in body: 3090 ↛ 3113line 3090 didn't jump to line 3113 because the loop on line 3090 didn't complete
3091 if isinstance(stmt,ast.Assign) and len(stmt.targets) == 1:
3092 tgt = stmt.targets[0]
3093 try:
3094 if isinstance(tgt,ast.Name):
3095 value = _eval(stmt.value,env)
3096 env[tgt.id] = value
3097 if isinstance(value,dict) and target is None: 3097 ↛ 3090line 3097 didn't jump to line 3090 because the condition on line 3097 was always true
3098 target,data = tgt.id,value
3099 elif isinstance(tgt,ast.Subscript) and isinstance(tgt.value,ast.Name) \ 3099 ↛ 3090line 3099 didn't jump to line 3090 because the condition on line 3099 was always true
3100 and tgt.value.id == target:
3101 key = _eval(tgt.slice,env)
3102 data[key] = _eval(stmt.value,env) # pylint: disable=unsupported-assignment-operation
3103 except CaseError as err:
3104 _logger.debug("skipping statement at line %s: %s",stmt.lineno,err)
3105 elif isinstance(stmt,ast.Return) and stmt.value is not None:
3106 try:
3107 value = _eval(stmt.value,env)
3108 except CaseError as err:
3109 _logger.debug("skipping statement at line %s: %s",stmt.lineno,err)
3110 continue
3111 if isinstance(value,dict) and _is_case(value): 3111 ↛ 3090line 3111 didn't jump to line 3090 because the condition on line 3111 was always true
3112 return value
3113 if data and _is_case(data):
3114 return data
3115 raise CaseError("no PYPOWER case (a dict with baseMVA, bus, gen, branch) found")
3117# ----- GLM parser -----
3119_SOLVER_CLASSES = {"bus","gen","branch","gencost","dcline"}
3121def _strip_comments(text):
3122 out = []
3123 for line in text.splitlines():
3124 quoted = False
3125 for i,ch in enumerate(line):
3126 if ch == '"':
3127 quoted = not quoted
3128 elif ch == "/" and not quoted and line[i:i+2] == "//":
3129 line = line[:i]
3130 break
3131 out.append(line)
3132 return "\n".join(out)
3134def _glm_blocks(text):
3135 """Yield (header, body) for each top-level `{...}` block"""
3136 i,n = 0,len(text)
3137 while i < n:
3138 j = text.find("{",i)
3139 if j < 0:
3140 return
3141 header = text[i:j].strip().splitlines()
3142 header = header[-1].strip() if header else ""
3143 depth,k,quoted = 0,j,False
3144 while k < n: 3144 ↛ 3155line 3144 didn't jump to line 3155 because the condition on line 3144 was always true
3145 ch = text[k]
3146 if ch == '"':
3147 quoted = not quoted
3148 elif not quoted and ch == "{":
3149 depth += 1
3150 elif not quoted and ch == "}":
3151 depth -= 1
3152 if depth == 0:
3153 break
3154 k += 1
3155 yield header,text[j+1:k]
3156 i = k+1
3158def _glm_props(body):
3159 """Parse `name value;` lines at the top level of an object body"""
3160 props,depth,buf,quoted = {},0,"",False
3161 for ch in body:
3162 if ch == '"':
3163 quoted = not quoted
3164 if not quoted and ch == "{":
3165 depth += 1
3166 elif not quoted and ch == "}":
3167 depth -= 1
3168 buf = ""
3169 continue
3170 if depth > 0:
3171 continue
3172 if ch == ";" and not quoted:
3173 part = buf.strip()
3174 buf = ""
3175 if part:
3176 bits = part.split(None,1)
3177 props[bits[0]] = bits[1].strip() if len(bits) > 1 else ""
3178 else:
3179 buf += ch
3180 return props
3182def _unquote(text):
3183 text = text.strip()
3184 if len(text) >= 2 and text[0] == text[-1] == '"':
3185 return text[1:-1]
3186 return text
3188def _glm_number(text,kind="float",options=None):
3189 text = _unquote(text)
3190 if options:
3191 lookup = {v.upper():k for k,v in options.items()}
3192 if text.upper() in lookup:
3193 return lookup[text.upper()]
3194 if text.upper() == "PQREF": 3194 ↛ 3195line 3194 didn't jump to line 3195 because the condition on line 3194 was never true
3195 return 1
3196 m = re.match(r"^\s*([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?|[+-]?INF)",text,re.I)
3197 if not m: 3197 ↛ 3198line 3197 didn't jump to line 3198 because the condition on line 3197 was never true
3198 raise CaseError(f"'{text}' is not a number")
3199 return _number(m.group(1),kind)
3201def _parse_glm(text):
3202 """Extract a ppc dict from an Arras Energy GLM model"""
3203 text = _strip_comments(text)
3204 directives = sum(1 for line in text.splitlines() if line.strip().startswith("#"))
3205 sources = [" ".join(line.split()[:2]) for line in text.splitlines()
3206 if re.match(r"\s*#(include|input|begin)\b",line)]
3207 text = "\n".join("" if line.strip().startswith("#") else line for line in text.splitlines())
3208 data = {"version":"2","baseMVA":100.0,"bus":[],"gen":[],"branch":[],"gencost":[],"dcline":[]}
3209 geodata = []
3210 names = {"bus":{},"gen":{}}
3211 objects = {t:[] for t in _SOLVER_CLASSES}
3212 others = {}
3213 geoclass,geoobjects = None,[]
3214 dccosts,stores = [],[]
3215 module = False
3216 for header,body in _glm_blocks(text):
3217 words = header.split()
3218 if len(words) >= 2 and words[0] == "module" and words[1] == "pypower":
3219 module = True
3220 props = _glm_props(body)
3221 if "baseMVA" in props:
3222 data["baseMVA"] = _glm_number(props["baseMVA"])
3223 if "version" in props:
3224 data["version"] = _unquote(props["version"])
3225 extra = sorted(set(props) - {"baseMVA","version"})
3226 if extra:
3227 others["module pypower setting"] = len(extra)
3228 elif len(words) >= 2 and words[0] == "class" and words[1] in (DCLINECOST_CLASS,STORAGE_CLASS):
3229 pass
3230 elif len(words) >= 2 and words[0] == "class" and words[1] == GEODATA_CLASS:
3231 geoclass = [part.split()[-1] for part in body.split(";")
3232 if len(part.split()) >= 2]
3233 elif words and words[0] in ("module","clock","class","schedule","filter","global"):
3234 key = " ".join(words[:2]) if words[0] == "module" else words[0]
3235 others[key] = others.get(key,0) + 1
3236 elif len(words) >= 2 and words[0] == "object": 3236 ↛ 3216line 3236 didn't jump to line 3216 because the condition on line 3236 was always true
3237 for nested in re.findall(r"\bobject\s+([\w.]+)",body):
3238 nested = nested[8:] if nested.startswith("pypower.") else nested
3239 others[nested] = others.get(nested,0) + 1
3240 oclass = words[1].split(":")[0]
3241 if oclass.startswith("pypower."):
3242 oclass = oclass[8:]
3243 if oclass == GEODATA_CLASS:
3244 geoobjects.append(_glm_props(body))
3245 elif oclass == DCLINECOST_CLASS:
3246 dccosts.append(_glm_props(body))
3247 elif oclass == STORAGE_CLASS:
3248 stores.append(_glm_props(body))
3249 elif oclass in _SOLVER_CLASSES:
3250 props = _glm_props(body)
3251 if ":" in words[1] and "name" not in props: 3251 ↛ 3252line 3251 didn't jump to line 3252 because the condition on line 3251 was never true
3252 props["name"] = words[1]
3253 objects[oclass].append(props)
3254 else:
3255 others[oclass] = others.get(oclass,0) + 1
3256 if not objects["bus"] and sources:
3257 # the network comes from files the preprocessor would load; reading this
3258 # file alone would silently give an empty case
3259 raise CaseError("no pypower bus objects found in GLM; its data comes from "
3260 + ", ".join(sources) + ", which ppedit does not expand (open that file instead)")
3261 if not module and not any(objects.values()): 3261 ↛ 3262line 3261 didn't jump to line 3262 because the condition on line 3261 was never true
3262 raise CaseError("no 'module pypower' objects found in GLM")
3263 # buses
3264 for n,props in enumerate(objects["bus"]):
3265 row = []
3266 for col in COLUMNS["bus"]:
3267 try:
3268 row.append(_glm_number(props[col["name"]],col["kind"],col["options"])
3269 if col["name"] in props else col["default"])
3270 except CaseError as err:
3271 raise CaseError(f"bus object {n+1} {col['name']}: {err}") from err
3272 if "bus_i" not in props: 3272 ↛ 3273line 3272 didn't jump to line 3273 because the condition on line 3272 was never true
3273 row[0] = n+1
3274 names["bus"][_unquote(props.get("name",f"pp_bus_{n+1}"))] = row[0]
3275 data["bus"].append(row)
3276 if "latitude" in props and "longitude" in props:
3277 try:
3278 geodata.append([row[0],_glm_angle(props["latitude"],"NS"),
3279 _glm_angle(props["longitude"],"EW")])
3280 except CaseError as err:
3281 raise CaseError(f"bus object {n+1} location: {err}") from err
3282 # generators
3283 for n,props in enumerate(objects["gen"]):
3284 row = []
3285 for col in COLUMNS["gen"]:
3286 row.append(_glm_number(props[col["name"]],col["kind"],col["options"])
3287 if col["name"] in props else col["default"])
3288 if "bus" not in props and "parent" in props:
3289 parent = _unquote(props["parent"])
3290 if parent not in names["bus"]: 3290 ↛ 3291line 3290 didn't jump to line 3291 because the condition on line 3290 was never true
3291 raise CaseError(f"gen object {n+1} parent '{parent}' is not a bus")
3292 row[0] = names["bus"][parent]
3293 names["gen"][_unquote(props.get("name",f"pp_gen_{n+1}"))] = n
3294 data["gen"].append(row)
3295 # branches
3296 for n,props in enumerate(objects["branch"]):
3297 row = []
3298 for col in COLUMNS["branch"]:
3299 row.append(_glm_number(props[col["name"]],col["kind"],col["options"])
3300 if col["name"] in props else col["default"])
3301 for j,ref in ((0,"from"),(1,"to")):
3302 if ("fbus","tbus")[j] not in props and ref in props:
3303 bus = _unquote(props[ref])
3304 if bus not in names["bus"]: 3304 ↛ 3305line 3304 didn't jump to line 3305 because the condition on line 3304 was never true
3305 raise CaseError(f"branch object {n+1} {ref} '{bus}' is not a bus")
3306 row[j] = names["bus"][bus]
3307 data["branch"].append(row)
3308 # costs, ordered by parent generator
3309 data["gencost"] = _glm_costs(objects["gencost"],names["gen"])
3310 # DC lines (Sfrom = Pf + j Pt and Sto = Qf + j Qt, as GridLAB-D passes them to PYPOWER)
3311 spec = COLUMNS["dcline"]
3312 for n,props in enumerate(objects["dcline"]):
3313 try:
3314 row = [0,0,_glm_number(props.get("status","IN"),"enum",DCLINE_STATUS)]
3315 for j,(ref,num) in enumerate((("from","fbus"),("to","tbus"))):
3316 if ref in props: 3316 ↛ 3321line 3316 didn't jump to line 3321 because the condition on line 3316 was always true
3317 bus = _unquote(props[ref])
3318 if bus not in names["bus"]:
3319 raise CaseError(f"{ref} '{bus}' is not a bus")
3320 row[j] = names["bus"][bus]
3321 elif num in props:
3322 row[j] = _glm_number(props[num],"int")
3323 else:
3324 raise CaseError(f"'{ref}' is missing")
3325 row += list(_glm_complex_value(props.get("Sfrom","0")))
3326 row += list(_glm_complex_value(props.get("Sto","0")))
3327 row += [_glm_number(props[name]) if name in props else col["default"]
3328 for name,col in zip(DCLINE_GLM,spec[7:])]
3329 except CaseError as err:
3330 raise CaseError(f"dcline object {n+1}: {err}") from err
3331 data["dcline"].append(row)
3332 if dccosts:
3333 dclines = {_unquote(props.get("name",f"pp_dcline_{n+1}")):n
3334 for n,props in enumerate(objects["dcline"])}
3335 data["dclinecost"] = _glm_costs(dccosts,dclines)
3336 if stores:
3337 data["storage"] = []
3338 for n,props in enumerate(stores):
3339 parent = _unquote(props.get("parent",""))
3340 if parent not in names["gen"]: 3340 ↛ 3341line 3340 didn't jump to line 3341 because the condition on line 3340 was never true
3341 raise CaseError(f"{STORAGE_CLASS} object {n+1} parent '{parent}' is not a gen")
3342 try:
3343 row = [names["gen"][parent]+1] + [_glm_number(props[c["name"]],c["kind"],c["options"])
3344 if c["name"] in props else c["default"] for c in COLUMNS["storage"][1:]]
3345 except CaseError as err:
3346 raise CaseError(f"{STORAGE_CLASS} object {n+1}: {err}") from err
3347 data["storage"].append(row)
3348 notes = []
3349 if geoobjects:
3350 geodata,tags = _glm_geodata(geodata,geoclass,geoobjects,names["bus"],notes)
3351 data["geotags"] = tags
3352 if geodata:
3353 data["geodata"] = geodata
3354 if directives:
3355 others["# directive"] = directives
3356 if others:
3357 notes.append("not kept (only module pypower bus, gen, branch, gencost and dcline data "
3358 "are edited): "
3359 + ", ".join(f"{v} {k}" for k,v in sorted(others.items())))
3360 return data,notes
3362def _glm_costs(objects,parents):
3363 """Read cost objects (`gencost` or `dclinecost`) as matrix rows ordered
3364 by parent (`parents` maps object names to row numbers); a second cost
3365 object of the same parent is its Q cost and goes after all the P costs"""
3366 costs,seen = [],{}
3367 for n,props in enumerate(objects):
3368 index = parents.get(_unquote(props.get("parent","")),n)
3369 seen[index] = seen.get(index,-1) + 1
3370 model = _glm_number(props.get("model","POLYNOMIAL"),"enum",COST_MODELS)
3371 values = _costs_list(_unquote(props.get("costs","")))
3372 ncost = len(values)//2 if model == 1 else len(values)
3373 costs.append((seen[index],index,n,[model,_glm_number(props.get("startup","0")),
3374 _glm_number(props.get("shutdown","0")),ncost]+values))
3375 return [x[3] for x in sorted(costs)]
3377def _glm_geodata(geodata,tags,objects,buses,notes):
3378 """Add the auxiliary values of `pp_geodata` objects to the bus locations
3380 Each object adds its values to the first unclaimed location row of its
3381 parent bus, or adds a row when it has its own `latitude`/`longitude`.
3382 `tags` are the `class pp_geodata` property names, else the object
3383 properties in order of appearance. Returns `(rows, tags)`.
3384 """
3385 if tags is None:
3386 tags = []
3387 for props in objects:
3388 tags += [k for k in props if k not in _GLM_HEADER and k not in tags]
3389 rows = {} # bus -> location rows not yet claimed
3390 for row in geodata:
3391 rows.setdefault(row[0],[]).append(row)
3392 out,skipped = [],0
3393 for n,props in enumerate(objects):
3394 bus = buses.get(_unquote(props.get("parent","")))
3395 aux = [_geo_value(_unquote(props[t])) if t in props else "" for t in tags]
3396 try:
3397 if "latitude" in props and "longitude" in props and bus is not None:
3398 row = [bus,_glm_angle(props["latitude"],"NS"),_glm_angle(props["longitude"],"EW")]
3399 elif rows.get(bus):
3400 row = rows[bus].pop(0)[:3]
3401 else:
3402 skipped += 1
3403 continue
3404 except CaseError as err:
3405 raise CaseError(f"{GEODATA_CLASS} object {n+1} location: {err}") from err
3406 out.append(row+aux)
3407 if skipped:
3408 notes.append(f"{skipped} {GEODATA_CLASS} object(s) not kept: parent is not a bus "
3409 "with a location")
3410 # locations without auxiliary values keep their place after the others
3411 out += [row[:3]+[""]*len(tags) for left in rows.values() for row in left]
3412 return out,tags