Coverage for ppedit/__init__.py: 75.0%

8 statements  

« prev     ^ index     » next       coverage.py v7.18.0, created at 2026-11-30 17:40 +0000

1"""Browser-based editor for PYPOWER and Arras Energy `module pypower` models 

2 

3Syntax 

4------ 

5 

6 ppedit serve [FILE] [-g CSV] [-p PORT] [--host HOST] [--no-browser] [--token TOKEN] [-d] [-v] [-w] 

7 ppedit convert INPUT OUTPUT [-g CSV] [-d] [-v] [-w] 

8 ppedit check FILE [-d] [-v] [-w] 

9 ppedit --version 

10 

11Positional arguments 

12-------------------- 

13 

14 - `serve`: start the editor web server and open it in a browser 

15 

16 - `convert`: convert a case between `.py`, `.json`, and `.glm`, or from a 

17 PSS/E `.raw` case (read only) to one of them 

18 

19 - `check`: print validation issues; exit code 1 if there are errors 

20 

21 - `FILE`, `INPUT`, `OUTPUT`: case files; the extension selects the format 

22 (`INPUT` and `FILE` may also be PSS/E `.raw`, revisions 23 to 35) 

23 

24Optional arguments 

25------------------ 

26 

27 - `-d|--debug`: enable debug logging and traceback on exceptions 

28 

29 - `-g|--geodata CSV`: add bus locations from a CSV file with at least the 

30 columns `BUS_I`, `LAT` and `LON` (other columns are kept as auxiliary 

31 data) to the case being served or converted 

32 

33 - `-h|--help`: show this help message and exit 

34 

35 - `-p|--port PORT`: server port (default 8050) 

36 

37 - `--host HOST`: interface to listen on (default `127.0.0.1`) 

38 

39 - `--no-browser`: do not open a browser window 

40 

41 - `--token TOKEN`: session token the editor URL must carry (letters, 

42 digits, `-`, `_`, `.`); default a new random token each time the server 

43 starts. `serve` prints and opens `http://localhost:PORT/?token=TOKEN`; 

44 the browser then keeps the token in a cookie, and requests without it 

45 are refused, so other users and programs that can reach the port cannot 

46 use the editor. Give a fixed token to restart a server without 

47 reopening the page (the page's **Restart server** command does) 

48 

49 - `-v|--verbose`: enable `INFO:` messages on stderr (files loaded and 

50 saved, and with `serve` each HTTP request; request lines are shown 

51 only with this option, not with `-d` alone) 

52 

53 - `--version`: print `ppedit` and the installed version, then exit 

54 

55 - `-w|--warning`: enable warning messages from python 

56 

57Description 

58----------- 

59 

60`ppedit` is a local web application for building and editing power system 

61models used by the PYPOWER solver, either as PYPOWER case files or as 

62Arras Energy GridLAB-D models that use `module pypower`. A Flask server 

63holds one case in memory and exposes it through a JSON API; the browser 

64page edits the bus, generator, branch, generator cost, DC line, DC line 

65cost and area tables, draws the network, checks the case, and runs PYPOWER power flow 

66and optimal power flow. 

67 

68Given a case file, `ppedit.Case` is expected to satisfy: 

69 

70 1. **Round trip.** `Case.load(path).dumps(fmt)` re-read with `Case.load` 

71 gives the same tables for `py`, `json`, and `glm`, except the price 

72 reference buses and names of `areas`, which GLM cannot hold (bus 

73 `area` numbers are kept, and `areas` rows are rebuilt from them). 

74 

75 2. **Referential integrity.** Edits through `Case.set_value`, 

76 `Case.add_row`, and `Case.delete_rows` never leave a generator, branch 

77 or DC line, or an area's price reference bus, pointing to a bus that 

78 does not exist: renumbering a bus renumbers its references, and 

79 deleting a bus with connections (or that is a price reference bus) is 

80 refused unless `cascade=True`. Renumbering an area in the `areas` 

81 table renumbers the `area` of its buses. 

82 

83 3. **Cost alignment.** When the case has `gencost` (`dclinecost`), adding 

84 or deleting a generator (DC line) adds or deletes its cost row(s). 

85 

86 4. **No code execution.** `.py` case files are parsed, never imported or 

87 run, so a case file from elsewhere cannot run code on the server. 

88 

89 5. **Geodata.** Bus locations (`Case.geodata`, rows of `[BUS_I, LAT, LON, 

90 aux...]` with auxiliary column names in `Case.geotags`) are read from a 

91 CSV file, from the `geodata` (and `geotags`) keys of a `.py`/`.json` 

92 case, or from GLM bus `latitude`/`longitude` and `pp_geodata` objects 

93 (a runtime class holding the auxiliary values, parent the bus), and are 

94 written back the same way. Renumbering a bus renumbers its geodata and deleting a 

95 bus deletes its geodata. 

96 

97 6. **Time series.** A case may carry a time series of bus `Pd`/`Qd`, 

98 generator `Pmin`/`Pmax` and DC line `Pmin`/`Pmax` by step 

99 (`Case.series`, set with `Case.set_series` or read from a data file on 

100 the *Multistep* tab; issue #124). It is saved in `.py` and `.json` cases 

101 (not GLM) and follows the case as references do: renumbering a bus 

102 renames its columns, and deleting buses, generators or DC lines drops 

103 their columns and renumbers the rows after them. *Run OPF ▾ › 

104 Multistep* (`Case.solve(..., multistep=True)`) solves every step as 

105 one cvxopf problem and returns one result per step; the step's values 

106 replace the case values in that step only. A *panel* sets one value 

107 (`Case.set_series_panel`): steps in rows and one column per table row 

108 number or geohash cell, a cell's value shared among the elements whose 

109 bus geodata lies in it (in proportion to their case values, equally, 

110 or whole to each). A case holds several named series (one per import, 

111 e.g. a load profile and a generator limit profile); multistep OPF 

112 combines them (`Case.combined_series`): by time when every series has 

113 a time column (the times common to all), else step by step (same 

114 number of steps); a value given by several series is their sum. 

115 The solve may cover only a window of the combined steps (`window` of 

116 `Case.solve`, `Case.series_window`; the *Multistep OPF window* start 

117 and stop on the Multistep tab, limited to the series range; issue 

118 #157). 

119 Multistep builder options (`multistep` of the cvxopf solve options, 

120 `ppedit._cvxopf.MULTISTEP_OPTIONS`) choose the temporal assembly and 

121 cvxopf `OPFOptions` such as branch limits and the lossy DC loss weight. 

122 

123The *Agent* tab runs any number of agent sessions that read and edit the 

124case through the same checked, undoable edits as the browser, optionally 

125using web data or local files. Sessions can also read the multistep time 

126series, the last solution (from the page or the session, each multistep 

127step included) and the Issues tab's case issues and solver messages, and 

128run a multistep OPF. The agent is chosen in the *Settings* tab 

129(*Agents*); the only one is Claude (`ppedit.claude`), which needs an 

130Anthropic API key: the server default (`ANTHROPIC_API_KEY` or 

131`~/.anthropic`), or a key or a key file on the server machine given in the 

132*Settings* tab. 

133 

134*Open ▾* opens a case file chosen on the browser's computer (*Local file…*) 

135or downloaded from an `http`/`https` URL typed in the menu (*From URL*). The 

136ppedit server downloads the URL (`ppedit.server.download_case`, at most 

137`ppedit.server.DOWNLOAD_LIMIT` bytes), so the server machine needs network 

138access to that host. A GitHub file page link (`.../blob/...`) is changed 

139to its raw file link, and other web pages are refused. The extension of the URL path selects the format, and 

140`.py` cases are parsed, never executed. Neither kind has a file path until 

141it is saved with *Save as*, or a folder is chosen in the top bar. 

142 

143The top bar shows the folder of the open file (the full path is its 

144tooltip). Clicking it opens a folder chooser that browses folders on the 

145server machine (`POST /api/folders`, `ppedit.server.list_folder`); *Use 

146this folder* moves the file path into the chosen folder (`POST 

147/api/folder`) without writing anything, keeping the file name (or the case 

148name with `.glm` when there is no path). *Save* then writes it there. 

149 

150The page takes optional URL parameters, so another tool can open it ready to 

151show (pptools `pprun` does): `?solve=pf` or `?solve=opf` runs that solver 

152when the page loads (`&algorithm=NAME` picks a PF algorithm or OPF solver as 

153in `POST /api/solve`, else the default), and `?view=NAME` opens the tab 

154`NAME` (`network`, `case`, `multistep`, `results`, `issues`, `agent`, 

155`settings`, or a table name such as `bus`; the former tab names `tables`, 

156`series` and `claude` open the Case, Multistep and Agent tabs). 

157Unknown values are ignored, and a solver error is shown as usual. 

158 

159Each case table can be imported from and exported to a data file 

160(*Import…*, *Export ▾*; `POST /api/table/import`, `GET /api/table/export`), 

161read and written with pandas in the format of the file extension (`.csv`, 

162`.tsv`, `.json`, optionally compressed, `.parquet`, `.feather`, `.xlsx`; 

163see `ppedit.server`). With no rows selected, import appends rows and export 

164writes all rows; with rows selected, import replaces them 

165(`ppedit.Case.import_rows`, same columns and row count) and export writes 

166only them. 

167 

168The network diagram has a *Geodata* layout, available when the case has 

169geodata, that places buses at their locations on a map (Web Mercator) with 

170optional USGS satellite imagery, Census TIGERweb roads, and state and county 

171boundaries and names. Buses without geodata are drawn next to their located 

172neighbors (dashed) or left out. Clicking where several buses overlap lists 

173them to choose from. 

174 

175A search box in the network toolbar finds a bus (by number or geodata 

176text) or a branch or DC line (by its two bus numbers, or all those at a 

177bus) and selects it for editing; several matches are listed to choose from. 

178 

179What is not promised 

180-------------------- 

181 

182 - One case per server, held in memory, for one user on the local machine. 

183 Requests must carry the session token `serve` prints (`--token`), but 

184 traffic is plain HTTP, so the token is visible to anyone who can watch 

185 the network: do not expose the server on a shared network. 

186 

187 - Only the solver-layer GLM objects (`bus`, `gen`, `branch`, `gencost`, 

188 `dcline`) are edited; other `module pypower` objects (`load`, 

189 `powerplant`, ...) and other modules are reported on load and dropped on 

190 save. GLM preprocessor directives (`#include`, `#input`, `#begin`, ...) 

191 are not expanded; a GLM whose buses come only from them is refused with 

192 an error naming the files to open instead. 

193 

194 - PSS/E `.raw` cases (revisions 23 to 35) are read, not written, and 

195 are converted as MATPOWER's `psse2mpc` does (see `ppedit._psse`): 

196 names and the data PYPOWER cannot hold (owners, zones, magnetizing 

197 admittance, impedance correction, switched shunt blocks other than the 

198 initial susceptance, VSC and multi-terminal DC lines, FACTS devices, 

199 ...) are listed when the case is opened and dropped; constant current 

200 and admittance loads become constant power at the case voltage; each 

201 3-winding transformer adds a star bus; there are no cost rows. 

202 

203 - `storage` (ppedit's own table, issue #128) is written to GLM as 

204 `pp_storage` runtime-class objects, parent the generator that 

205 discharges it; only multistep CVXOPF OPF models it (other solves warn 

206 and run its generator as an ordinary generator), and charging and 

207 discharging in the same step are not excluded. 

208 

209 - `areas` is not written to GLM (there is no GridLAB-D object for it). 

210 `dclinecost` is written to GLM as `dclinecost` runtime-class objects 

211 with the `pypower.gencost` properties, parent the DC line (GridLAB-D 

212 keeps them but does not solve with them). `areas` is not passed to the solver: the 

213 per-area results (`Case.solve`) are sums over the bus `area` column, and 

214 an area's price is the OPF `lam_P` at its price reference bus. 

215 

216 - DC lines are solved with ppedit's own implementation of PYPOWER's 

217 `toggle_dcline` model (that function fails with current numpy, and 

218 pypower8 has none). 

219 As in PYPOWER, power flow does not enforce the DC line reactive power 

220 limits, and a DC line terminal bus becomes a PV bus held at the line's 

221 voltage setpoint (taking precedence over a generator's `Vg` at that 

222 bus). A bus connected only by DC lines is still isolated, so its DC 

223 lines are not solved. 

224 

225 - The force-directed layout is not geography and its positions are not 

226 saved; bus positions are kept only as geodata, which the diagram does not 

227 edit (load a CSV or edit the case file). Map layers are fetched by the 

228 browser from public U.S. government map services (USGS The National Map, 

229 Census Bureau TIGERweb): they need network access, cover the United 

230 States only, and are not cached by `ppedit`. GLM output writes 

231 auxiliary geodata as `pp_geodata` objects; tags that are not GLM 

232 property names are renamed (e.g. `KV level` to `KV_level`). In the classic style a bus with both generation and load 

233 is drawn as a generator (circle); its label shows both MW values. The 

234 one-line style computes its own layered layout from the topology (it 

235 is not dragged); each line has a column at each of its buses joined by 

236 one horizontal segment, which keeps bus bars short but makes large 

237 meshed cases wide, and lines that skip rows still cross bus bars. 

238 Clicking a one-line load switch sets that bus's `Pd` and `Qd` to 0 and 

239 keeps their values in server memory (with the undo history) to restore 

240 on the next click; they are not saved in the case file, and editing 

241 `Pd` or `Qd`, renumbering or deleting the bus, or opening another case 

242 forgets them. 

243 Label choices (**Labels ▾**) are kept in the browser, not in the case. 

244 Labels are not moved to make room: a data label that would overlap 

245 another label or a bus symbol is not drawn (bus numbers always are), so 

246 a dense diagram shows few data labels until zoomed in; the popup shown 

247 over a bus or branch lists the chosen items anyway. 

248 

249 - Claude sessions send the case data they read, and the files and web 

250 pages they use, to the Anthropic API; they are kept in server memory 

251 only and end when the server stops. Changes Claude makes are checked 

252 like any other edit but not reviewed: look at them (and undo them) 

253 before saving. 

254 

255 - Buses with no in-service branch are solved as isolated (type NONE) 

256 without changing the case. 

257 

258 - Run OPF offers only the OPF solvers whose Python module is installed 

259 (`ppedit.case.solvers`); PIPS (AC and DC) ships with `pypower8`, while 

260 IPOPT, CPLEX, MOSEK and Gurobi are offered when their modules are 

261 present but are not tested by ppedit. A DC OPF solution has flat 

262 voltages, no reactive power and no losses; applying it copies those 

263 into the case. 

264 

265 - The cvxopf solvers (`CVXOPF-*`, offered when cvxopf is installed) 

266 report no LMPs or multipliers; ignore reactive power costs; model DC 

267 lines without `loss0`, terminal reactive power or voltage set points 

268 (the copper plate ignores DC lines and has no branch flows); and 

269 give the SOCP relaxation's voltages, which need not be AC feasible 

270 (the log says whether they are). The cvxopf DC network-flow model has no 

271 voltage angles. The cvxopf solve options (Settings tab, `options` of 

272 `ppedit.Case.solve`) cover numerical preparation, solver choice, 

273 solver output and solver options; cvxopf's device models (storage, 

274 nondispatchable units, curtailable loads) are not offered. From the 

275 editor, a `CVXOPF-*` solve runs in a separate process that reports 

276 its progress and that *Stop* ends at any point (issue #130); PYPOWER 

277 solves cannot be stopped. 

278 

279 - Multistep OPF (issue #124) needs a `CVXOPF-*` solver and a time series. 

280 The steps share one problem but nothing couples them: there are no ramp 

281 limits, unit commitment or storage. Per-step generator limits are 

282 constraints ppedit adds to cvxopf's problem (cvxopf has none), so they 

283 need the default preparation. The diagram draws the case loads, not the 

284 step's; the Results tab, solution columns and dispatch show the step. 

285 Full AC multistep memory grows with the number of steps inside cvxopf 

286 (about 0.5 GB per step on case118 and 2.3 GB on `wecc240_2020`), so 

287 long AC horizons do not fit in memory; the DC models are light. 

288 Series columns name generators and DC lines by row number, which is 

289 kept up to date only by edits made in ppedit. Full AC (`CVXOPF-AC`) 

290 multistep problems need memory in proportion to the number of steps 

291 in cvxopf (about 0.5 GB per step for `case118`); the DC models need 

292 far less. 

293 

294 - The extended (result) columns shown in the tables after a solve 

295 (`ppedit.case.RESULT_COLUMNS`, the `extended` rows of 

296 `ppedit.Case.solve`) are not part of the case: they are not edited, 

297 saved, imported or kept after the next edit (table export includes 

298 them while they are shown). Multipliers are given 

299 only by the PYPOWER OPF solvers, as PYPOWER computes them. 

300 

301 - Solver messages (`messages` of a solution, listed on the Issues tab) 

302 report what the solver reports and what ppedit changed to solve the 

303 case; they are not a diagnosis of why a solve failed. The `detail` of a 

304 warning (its physical meaning and the constraints involved) covers the 

305 warnings ppedit knows; other cvxopf and Python warnings have none, and 

306 its text may need revising as cvxopf changes. 

307 

308Data 

309---- 

310 

311Columns follow `pypower8.caseformat`; units are listed in `ppedit.case.COLUMNS`. 

312 

313```mermaid 

314flowchart LR 

315 file[(.py / .json / .glm)] <--> Case 

316 raw[(PSS/E .raw)] --> Case 

317 csv[(geodata .csv)] --> Case 

318 maps[USGS / TIGERweb map services] --> browser 

319 Case <-->|JSON API| server[Flask server] 

320 server <--> browser[Browser editor] 

321 Case --> solver[PYPOWER runpf / runopf] 

322 server <-->|tools| claude[Claude sessions] 

323 claude <--> api[Anthropic API] 

324 web[(web data)] --> claude 

325 files[(local files)] --> claude 

326``` 

327 

328Examples 

329-------- 

330 

331The [examples](https://github.com/eudoxys/ppedit/tree/main/examples) folder contains  

332example models from PyPower IEEE cases, the WECC 240 model, and the IEEE 118 

333model with time-series data for multistep OPF. 

334""" 

335 

336try: 

337 import importlib.metadata 

338 __version__ = importlib.metadata.version("ppedit") 

339except Exception: # pylint: disable=broad-exception-caught 

340 __version__ = "dev" 

341 

342from ppedit.case import Case, CaseError, COLUMNS, TABLES, builtin_cases 

343from ppedit.server import create_app 

344from ppedit.cli import main