Coverage for ppedit/_cvxopf.py: 87.6%
568 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"""@private OPF with cvxopf (github.com/cvxgrp/cvxopf), for `Case.solve`
3`runopf(ppc,formulation,log)` solves a PYPOWER case (numpy arrays, isolated
4buses already set to type NONE) with one cvxopf network formulation and
5returns the solution in the layout of `pypower8.runopf` results (`bus`
6with 17 columns, `gen` with 25, `branch` with 21, `dcline` with 19, plus
7`f`, `success`, `et`, `baseMVA`), so `Case.solve` and `pypower8.printpf`
8read it like a PYPOWER solution. Values cvxopf does not give are left as
9in the case (voltages of unsolved buses) or zero (multipliers, `lam_P`);
10`Case.solve` reports the multipliers and prices as unknown. `flows` is
11false when the formulation has no branch flows (`singlenode_dc`).
13How the case is passed:
15 - Buses of type NONE are removed, with the generators on them and the
16 branches touching them (cvxopf has no isolated-bus type).
18 - Reactive power cost rows (`gencost` with twice as many rows as `gen`)
19 are dropped: cvxopf has no reactive power costs.
21 - In-service DC lines become `cvxopf.HVDCLink` objects made by
22 `cvxopf.hvdc_from_dcline` (cvxopf PR 32): an HVDCLink bounds the power
23 injected at its from bus, `p_in = -Pf`, so `p_min_mw = -Pmax` and
24 `p_max_mw = -Pmin`. `loss1` is the proportional loss; `loss0`,
25 reactive power limits and the terminal voltage set points `Vf`, `Vt`
26 are not modeled by cvxopf. `dclinecost` must be polynomial (model 2)
27 of degree 2 or less, applied to `|Pf|` with its sign converted for
28 reverse lines; cvxopf refuses costs it cannot represent and reverse or
29 two-way lines (`Pmin < 0`) with losses. An older cvxopf, whose import
30 runs PYPOWER DC lines backwards, is refused for cases with DC lines.
31 The copper-plate model (`singlenode_dc`) ignores DC lines.
33Sparse derivatives (issue #122): every formulation is built with
34`automatic_sparse_dispatch=True`, so CVXPY keeps its density threshold
35(`cvxpy.settings.SPARSE_DENSITY_THRESHOLD`) during the build and the
36solve. cvxopf's AC default sets it to 0 instead, which makes CVXPY's
37derivative engine treat the sparse injection matrices as dense. IPOPT
38then factors a far denser KKT system: case300 runs in about 13 s
39instead of 55 s with the threshold kept, with the same iterations and
40objective. Convex formulations ignore the flag.
42Solve options (`solve_options`, issue #88; decision #48):
44 - `preparation`: `default` builds with cvxopf's defaults (original
45 coordinates, no `NumericalPreparation`); `recommended` builds with
46 `OPFOptions(numerical_preparation=NumericalPreparation(**RECOMMENDED[formulation]))`,
47 the profile the cvxopf authors recommend for each network model with
48 `build_opf`. Prepared execution runs only with CLARABEL (convex
49 models) or IPOPT (`ac`).
51 - `solver`: CVXPY solver name for the convex models (`socp`,
52 `lossy_dc`, `singlenode_dc`; default CLARABEL); `ac` always uses IPOPT.
54 - `verbose`: write the solver's own output to `log`.
56 - `solver_options`: other keyword arguments for `OPFBuild.solve` (CVXPY
57 and solver options such as IPOPT `tol` and `max_iter`, or CLARABEL
58 `tol_gap_rel`), passed as given.
60 - `multistep`: builder options for multistep OPF only (`multistep_options`,
61 `MULTISTEP_OPTIONS`): `temporal_assembly` (`vectorized`, the default,
62 or `stepwise`), `sparse_dispatch` (AC; default on, issue #122), and the
63 `cvxopf.OPFOptions` fields `enforce_branch_limits` (AC, SOCP; default
64 on), `enforce_vset` (AC, SOCP), `init_flat` (AC; default on),
65 `sparsity_tol` (AC; above 0 only without branch limits), `sparse_pq`
66 and `vectorize_pq` (AC; default on), `loss_weight` (lossy DC; default
67 1) and `branch_limit_sentinel` (lossy DC; MW for branches with
68 `rateA` 0; default 1e6), each passed only to the models it applies to.
70Notes about data cvxopf does not model and the warnings cvxopf issues while
71building and solving are written to `log` and returned in `warnings`, each
72as `{"message", "detail"}`. `detail` (or `None`) says what the warning
73means physically and lists the constraints involved (decision #53):
75 - `explain`: what the warning means for the network and the solution
77 - `constraints`: at most `MAX_CONSTRAINTS` rows of `constraint` (the
78 constraint, as cvxopf builds it or as the relaxation leaves it out),
79 `element` (a label such as `branch 3 (1-4)`, or `None`), `table` and
80 `row` (the case table and row index of the element, or `None`), and
81 `value` (the violation or data value, or `None`)
83 - `more`: how many further constraints are not listed
85cvxopf reports branches and buses by its internal zero-based indexes;
86details (and the rewritten messages) use case rows and bus numbers.
87Warnings cvxopf issues once per element (`rateA` = 0 branches, slow CVXPY
88constraints) are grouped into one message.
89"""
91import contextlib
92import math
93import os
94import re
95import sys
96import tempfile
97import time
98import warnings
99import numpy as np
101FORMULATIONS = ("ac","socp","lossy_dc","singlenode_dc")
102"""cvxopf network formulations `runopf` accepts"""
104PREPARATIONS = ("default","recommended")
105"""Numerical preparation choices (`preparation` solve option)"""
107RECOMMENDED = {
108 "singlenode_dc":{"exact_fixed_boxes":True,"canonical_scaling":"joint5"},
109 "lossy_dc":{"exact_fixed_boxes":True,"canonical_scaling":"joint5"},
110 "socp":{"normalize_device_limits":True,"exact_fixed_boxes":True,"canonical_scaling":"joint5"},
111 "ac":{"normalize_device_limits":True,"exact_fixed_boxes":True,"cost_coordinates":True},
112}
113"""`NumericalPreparation` fields of the `recommended` preparation for each
114formulation built with `build_opf` (from the cvxopf authors in issue #88;
115`joint5` is five passes of joint objective and constraint scaling; `ac`
116keeps the `hourly` objective assembly, since `component_first` applies to
117the time-vectorized builder)"""
119MULTISTEP_OPTIONS = {
120 "temporal_assembly":("vectorized",None),
121 "sparse_dispatch":(True,("ac",)),
122 "enforce_branch_limits":(True,("ac","socp")),
123 "enforce_vset":(False,("ac","socp")),
124 "init_flat":(True,("ac",)),
125 "sparsity_tol":(0.0,("ac",)),
126 "sparse_pq":(True,("ac",)),
127 "vectorize_pq":(True,("ac",)),
128 "loss_weight":(1.0,("lossy_dc",)),
129 "branch_limit_sentinel":(1e6,("lossy_dc",)),
130}
131"""Multistep builder options (`multistep` of the solve options): name ->
132(default, formulations it applies to, `None` for all). `temporal_assembly`
133(`vectorized` or `stepwise`) and `sparse_dispatch` (cvxopf's
134`automatic_sparse_dispatch`, issue #122) are `build_opf_multistep`
135arguments; the others are `cvxopf.OPFOptions` fields, passed only to the
136formulations they apply to (cvxopf rejects some elsewhere, e.g. a
137`loss_weight` other than 1 with SOCP)"""
139TEMPORAL_ASSEMBLIES = ("vectorized","stepwise")
141HOURS_PER_MONTH = 730.0
142"""Hours per month of the storage `self_discharge` rate (cvxopf's value)"""
144MAX_CONSTRAINTS = 20
145"""Most constraints listed in a warning's `detail`"""
147RESERVED = ("solver","verbose","nlp")
148"""Solve keyword arguments `solver_options` may not set (ppedit sets them)"""
150def solve_options(options:dict|None,formulation:str) -> dict:
151 """Check the cvxopf solve `options` (see the module docstring) for
152 `formulation` and return them complete (`preparation`, `solver` or
153 `None` for cvxopf's default, `verbose`, `solver_options`)
155 Exceptions
156 ----------
158 - `ValueError`: an unknown option or value, a solver that is not
159 installed or cannot run `formulation`, or a solver other than
160 CLARABEL/IPOPT with the `recommended` preparation
161 """
162 if formulation not in FORMULATIONS: 162 ↛ 163line 162 didn't jump to line 163 because the condition on line 162 was never true
163 raise ValueError(f"cvxopf formulation must be one of {', '.join(FORMULATIONS)}")
164 options = dict(options or {})
165 unknown = set(options) - {"preparation","solver","verbose","solver_options","multistep"}
166 if unknown:
167 raise ValueError(f"unknown cvxopf option(s): {', '.join(sorted(unknown))}")
168 out = {"preparation":options.get("preparation") or "default",
169 "solver":(options.get("solver") or "").strip().upper() or None,
170 "verbose":bool(options.get("verbose",False)),
171 "solver_options":dict(options.get("solver_options") or {}),
172 "multistep":multistep_options(options.get("multistep"))}
173 if formulation == "ac" and out["multistep"]["sparsity_tol"] > 0 and out["multistep"]["enforce_branch_limits"]:
174 raise ValueError("a multistep sparsity_tol above 0 needs enforce_branch_limits off "
175 "(cvxopf enforces branch limits only with exact sparsity)")
176 if out["preparation"] not in PREPARATIONS:
177 raise ValueError(f"cvxopf preparation must be one of {', '.join(PREPARATIONS)}")
178 native = "IPOPT" if formulation == "ac" else "CLARABEL"
179 if out["solver"] == native:
180 out["solver"] = None
181 if out["solver"]:
182 if formulation == "ac":
183 raise ValueError("cvxopf full AC (ac) solves only with IPOPT")
184 import cvxpy # pylint: disable=import-outside-toplevel
185 if out["solver"] not in cvxpy.installed_solvers():
186 raise ValueError(f"CVXPY solver {out['solver']} is not installed "
187 f"(installed: {', '.join(cvxpy.installed_solvers())})")
188 if out["preparation"] == "recommended":
189 raise ValueError(f"the recommended cvxopf preparation solves only with {native}; "
190 "choose the default preparation to use another solver")
191 bad = [k for k in out["solver_options"] if k in RESERVED or not str(k).isidentifier()]
192 if bad:
193 raise ValueError(f"solver option(s) {', '.join(map(str,bad))} cannot be set "
194 f"(not names, or set by ppedit: {', '.join(RESERVED)})")
195 return out
197def multistep_options(options:dict|None) -> dict:
198 """Check the multistep builder `options` (`MULTISTEP_OPTIONS`) and
199 return them complete; `ValueError` for an unknown option or a bad value"""
200 options = dict(options or {})
201 unknown = set(options) - set(MULTISTEP_OPTIONS)
202 if unknown:
203 raise ValueError(f"unknown multistep option(s): {', '.join(sorted(unknown))}")
204 out = {k:options.get(k,d) for k,(d,_) in MULTISTEP_OPTIONS.items()}
205 if out["temporal_assembly"] not in TEMPORAL_ASSEMBLIES:
206 raise ValueError(f"multistep temporal_assembly must be one of {', '.join(TEMPORAL_ASSEMBLIES)}")
207 for k,(d,_) in MULTISTEP_OPTIONS.items():
208 if isinstance(d,bool):
209 if not isinstance(out[k],bool):
210 raise ValueError(f"multistep option {k} must be true or false")
211 elif isinstance(d,float):
212 try:
213 out[k] = float(out[k])
214 except (TypeError,ValueError) as err:
215 raise ValueError(f"multistep option {k} must be a number") from err
216 if not math.isfinite(out[k]) or out[k] < 0 or (k == "branch_limit_sentinel" and out[k] == 0):
217 raise ValueError(f"multistep option {k} must be a finite "
218 + ("positive" if k == "branch_limit_sentinel" else "nonnegative") + " number")
219 return out
221def _multistep_build(opts:dict,formulation:str) -> tuple[dict,dict]:
222 """`build_opf_multistep` keyword arguments and `OPFOptions` fields of the
223 multistep options `opts` that apply to `formulation`"""
224 build,fields = {"temporal_assembly":opts["temporal_assembly"]},{}
225 for k,(_,forms) in MULTISTEP_OPTIONS.items():
226 if k == "temporal_assembly" or (forms is not None and formulation not in forms):
227 continue
228 if k == "sparse_dispatch":
229 build["automatic_sparse_dispatch"] = opts[k]
230 else:
231 fields[k] = opts[k]
232 return build,fields
234@contextlib.contextmanager
235def _capture_output(log,enabled):
236 """Copy what the solver writes to file descriptors 1 and 2 (IPOPT
237 writes from C, CVXPY's verbose log goes to `sys.stderr`) into `log`"""
238 if not enabled:
239 yield
240 return
241 with tempfile.TemporaryFile(mode="w+b") as tmp:
242 for f in (sys.__stdout__,sys.__stderr__):
243 if f: 243 ↛ 242line 243 didn't jump to line 242 because the condition on line 243 was always true
244 f.flush()
245 saved = [os.dup(1),os.dup(2)]
246 os.dup2(tmp.fileno(),1)
247 os.dup2(tmp.fileno(),2)
248 try:
249 yield
250 finally:
251 for f in (sys.__stdout__,sys.__stderr__):
252 if f: 252 ↛ 251line 252 didn't jump to line 251 because the condition on line 252 was always true
253 f.flush()
254 os.dup2(saved[0],1)
255 os.dup2(saved[1],2)
256 for fd in saved:
257 os.close(fd)
258 tmp.seek(0)
259 text = tmp.read().decode(errors="replace")
260 log.write("\nSolver output\n-------------\n" + text + ("" if text.endswith("\n") else "\n"))
262PROGRESS_INTERVAL = 0.5
263"""Least seconds between two IPOPT iteration progress reports"""
265IPOPT_MAX_ITER = 3000
266"""IPOPT's default `max_iter`, shown in progress reports"""
268@contextlib.contextmanager
269def _ipopt_progress(progress,max_iter):
270 """Report IPOPT progress to `progress` while solving: a `derivatives`
271 report when CVXPY starts building its derivative oracles (the
272 differentiation structure, slow for large AC models) and `iterate`
273 reports from IPOPT's intermediate callback. CVXPY's IPOPT interface
274 (`cvxpy.reductions.solvers.nlp_solvers.nlp_solver.Oracles`, cvxpy 1.9)
275 has no callback of its own; cyipopt calls the problem object's
276 `intermediate` method after each iteration when it has one, so one is
277 added to `Oracles` for the duration of the solve. Does nothing when
278 `progress` is `None` or the CVXPY internals are not found."""
279 if progress is None: 279 ↛ 282line 279 didn't jump to line 282 because the condition on line 279 was always true
280 yield
281 return
282 try:
283 from cvxpy.reductions.solvers.nlp_solvers.nlp_solver import Oracles # pylint: disable=import-outside-toplevel
284 except ImportError:
285 yield
286 return
287 if hasattr(Oracles,"intermediate"): # CVXPY has its own now: leave it alone
288 yield
289 return
290 init = Oracles.__init__
291 last = [0.0]
292 def oracles_init(self,*args,**kwargs):
293 progress({"phase":"derivatives","text":"computing the derivative structure"})
294 init(self,*args,**kwargs)
295 progress({"phase":"iterate","text":"IPOPT is starting","iteration":None,"max_iter":max_iter})
296 def intermediate(self,alg_mod,iter_count,obj_value,inf_pr,inf_du,*args): # pylint: disable=unused-argument
297 now = time.time()
298 if now - last[0] >= PROGRESS_INTERVAL:
299 last[0] = now
300 progress({"phase":"iterate","text":f"IPOPT iteration {iter_count}","iteration":int(iter_count),
301 "max_iter":max_iter,"objective":float(obj_value),"inf_pr":float(inf_pr),
302 "inf_du":float(inf_du)})
303 return True
304 Oracles.__init__ = oracles_init
305 Oracles.intermediate = intermediate
306 try:
307 yield
308 finally:
309 Oracles.__init__ = init
310 del Oracles.intermediate
312def _hvdc_links(ppc,note):
313 """Return the cvxopf `HVDCLink` list for the in-service DC lines and
314 their row numbers in `ppc["dcline"]` (`cvxopf.hvdc_from_dcline`, cvxopf
315 PR 32); `ValueError` for a DC line or cost cvxopf cannot import, or a
316 cvxopf whose import runs DC lines backwards"""
317 from cvxopf import hvdc_from_dcline # pylint: disable=import-outside-toplevel
318 dcline = np.asarray(ppc["dcline"],dtype=float)
319 costs = ppc.get("dclinecost")
320 costs = None if costs is None or len(costs) == 0 else np.asarray(costs,dtype=float)
321 if costs is not None and len(costs) != len(dcline): 321 ↛ 322line 321 didn't jump to line 322 because the condition on line 321 was never true
322 raise ValueError(f"dclinecost has {len(costs)} rows for {len(dcline)} DC lines")
323 rows = [n for n,d in enumerate(dcline) if d[2] > 0]
324 if not rows: 324 ↛ 325line 324 didn't jump to line 325 because the condition on line 324 was never true
325 return [],[]
326 with warnings.catch_warnings():
327 # ppedit reports the omitted converter terms itself, with details
328 warnings.filterwarnings("ignore",message="hvdc_from_dcline omitted",category=UserWarning)
329 warnings.filterwarnings("ignore",message="hvdc_from_dcline: one or more",category=UserWarning)
330 probe = hvdc_from_dcline(np.array([[1,2,1,0,0,0,0,0,0,1,2,0,0,0,0,0,0]],dtype=float))
331 if probe[0].p_max_mw > 0:
332 raise ValueError("this cvxopf runs PYPOWER DC lines backwards (its hvdc_from_dcline "
333 "predates cvxopf PR 32); install a cvxopf with the DC-line import fix")
334 try:
335 links = hvdc_from_dcline(dcline,costs)
336 except ValueError as err:
337 # cvxopf numbers DC line rows from 0; ppedit from 1
338 raise ValueError(re.sub(r"(dcline|dclinecost) row (\d+)",
339 lambda m: f"{'DC line' if m[1] == 'dcline' else 'dclinecost row'} {int(m[2])+1}",
340 str(err))) from err
341 for link,n in zip(links,rows):
342 link.device_id = f"dcline-{n+1}"
343 for n in rows:
344 if dcline[n][15] != 0:
345 note(f"DC line {n+1}: loss0 = {dcline[n][15]:g} MW is not modeled by cvxopf",
346 _detail("dcline_loss0",[_row("Pt = Pf - loss1 Pf (cvxopf) instead of "
347 "Pt = Pf - (loss0 + loss1 Pf)",f"dcline {n+1}","dcline",n,f"loss0 = {dcline[n][15]:g} MW")]))
348 if links: 348 ↛ 353line 348 didn't jump to line 353 because the condition on line 348 was always true
349 note("DC lines: cvxopf models unity power factor terminals (no Qf, Qt) "
350 "and does not hold Vf, Vt",_detail("dcline_terminals",
351 [_row(f"Qf = Qt = 0; Vf = {ppc['dcline'][n][7]:g}, Vt = {ppc['dcline'][n][8]:g} "
352 "pu not held",f"dcline {n+1}","dcline",n) for n in rows]))
353 return links,rows
355EXPLAIN = {
356 "storage_cut":"A storage unit discharges through its generator and charges at its "
357 "charging bus. When that generator is out of service or at an isolated bus, or the "
358 "charging bus is isolated, the unit cannot exchange energy with the network, so it is "
359 "left out of the solve (no charge, discharge or stored energy). Put the generator in "
360 "service, or set the storage status to OUT to make this explicit.",
361 "reactive_cost":"PYPOWER cases can give a second set of gencost rows that price "
362 "generator reactive power. cvxopf's objective has real power costs only, so these "
363 "rows are dropped: the dispatch does not account for the cost of reactive power and "
364 "the objective leaves it out. Reactive power limits (Qmin, Qmax) still apply.",
365 "dcline_loss0":"loss0 is a DC line's fixed converter loss, drawn whenever the line is "
366 "in service. cvxopf models only the loss proportional to the flow (loss1), so the "
367 "line delivers loss0 MW more at its to bus than in PYPOWER, and total losses are "
368 "lower by that amount.",
369 "dcline_terminals":"In PYPOWER each DC line terminal also acts like a generator that "
370 "supplies reactive power within its Qmin..Qmax limits and holds its bus voltage at "
371 "Vf or Vt (a PV bus). cvxopf models the converters at unity power factor: they "
372 "exchange no reactive power, and the terminal bus voltages follow from the rest of "
373 "the network instead of being held.",
374 "dcline_copper":"The copper-plate model treats the whole system as one bus: there is "
375 "no network, so neither AC branches nor DC lines carry flow, and generation only "
376 "has to match total load and losses are zero.",
377 "rate_a":"PYPOWER treats rateA = 0 as an unlimited branch. The lossy network-flow "
378 "model needs a finite bound on every branch flow, so cvxopf uses a large "
379 "placeholder limit (branch_limit_sentinel) for these branches. The branch stays "
380 "effectively unlimited unless its flow approaches that value, so this is not a data "
381 "error; give the branch a rateA to make its thermal limit count.",
382 "subexpressions":"This note is about how long CVXPY takes to convert the problem into "
383 "the solver's form, not about the network or the solution: the listed constraint "
384 "groups are built element by element, which compiles slowly on large cases. "
385 "Results are not affected. Constraint numbers are CVXPY's (zero-based) positions in "
386 "the problem's constraint list.",
387 "hvdc_straddle":"The loss on a DC line depends on its flow direction. When Pmin < 0 < "
388 "Pmax the line may flow either way, and a convex model cannot represent a loss that "
389 "switches with direction, so cvxopf solves this line as lossless (Pt = Pf).",
390 "pwl_nonconvex":"A piecewise-linear cost whose segment slopes decrease is nonconvex "
391 "(marginal cost falls as output rises). A convex solver cannot represent it, so "
392 "cvxopf uses the lower convex hull of the breakpoints, which lowers the cost between "
393 "the breakpoints it skips. The dispatch can differ from PYPOWER's and the objective "
394 "can be below the case's cost curve.",
395 "inaccurate":"The solver stopped close to, but not within, its convergence tolerances "
396 "(status optimal_inaccurate). The dispatch is approximately optimal, and power "
397 "balance and limits may be violated by small amounts. The recommended preparation "
398 "or a higher iteration limit (Settings, CVXOPF solve options) may give an accurate "
399 "solution.",
400 "cost_accuracy":"cvxopf checks, after an AC solve with cost coordinates (recommended "
401 "preparation), that the solver's objective matches the generator cost curves "
402 "evaluated at the dispatch. That check failed: the dispatch and solver status are "
403 "kept, but the objective may not equal the true cost. The default preparation "
404 "avoids cost coordinates.",
405 "socp":"The SOCP model is a convex relaxation of the AC power flow equations. For each "
406 "pair of connected buses it replaces the voltage product W_ij = V_i V_j* by a "
407 "variable bounded only by the cone |W_ij|^2 <= w_i w_j (w = Vm^2), and it does not "
408 "require voltage angle differences to add up to zero around each loop of a meshed "
409 "network. The solution is exact only when every cone holds with equality and every "
410 "loop closes. Otherwise no set of bus voltages produces these flows: the objective "
411 "is a lower bound on the AC OPF cost, and Vm, Va and the flows are approximations. "
412 "The rows below are the relaxed constraints that are not met, then the AC "
413 "constraints the recovered voltages violate (worst element of each). Solve with "
414 "CVXOPF-AC for an AC-feasible dispatch.",
415}
416"""Physical meaning of each kind of cvxopf warning (`detail["explain"]`)"""
418VARIABLES = {
419 "theta":"bus voltage angles","v":"bus voltage magnitudes",
420 "w":"squared bus voltage magnitudes","W_re":"voltage products of connected buses (real)",
421 "W_im":"voltage products of connected buses (imaginary)",
422 "P_vec":"real power terms of the bus admittance matrix",
423 "Q_vec":"reactive power terms of the bus admittance matrix",
424 "p":"net real power injections at buses","q":"net reactive power injections at buses",
425 "Pg":"generator real power","Qg":"generator reactive power",
426 "branch_p_from_pu":"branch real power flows at the from bus",
427 "branch_q_from_pu":"branch reactive power flows at the from bus",
428 "branch_p_to_pu":"branch real power flows at the to bus",
429 "branch_q_to_pu":"branch reactive power flows at the to bus",
430 "p_flows":"branch real power flows","p_hvdc_in":"DC line power at the from bus",
431 "p_hvdc_out":"DC line power at the to bus",
432}
433"""Physical meaning of cvxopf's CVXPY variables, to describe a constraint"""
435def _detail(kind,constraints=(),explain=None) -> dict:
436 """Return a warning `detail` of `kind` (see the module docstring)"""
437 rows = list(constraints)
438 return {"explain":explain or EXPLAIN[kind],"constraints":rows[:MAX_CONSTRAINTS],
439 "more":max(0,len(rows)-MAX_CONSTRAINTS)}
441def _row(constraint,element=None,table=None,row=None,value=None) -> dict:
442 """Return one `detail["constraints"]` row"""
443 return {"constraint":constraint,"element":element,"table":table,
444 "row":None if row is None else int(row),"value":value}
446class _Elements:
447 """Map cvxopf's internal indexes to case rows and labels"""
449 def __init__(self,bus,gen,branch,live,gkeep,bkeep,gencost):
450 self.bus,self.gen,self.branch = bus,gen,branch
451 self.gencost = gencost # real power cost rows of the kept generators
452 self.brow = np.flatnonzero(live) # internal bus -> case bus row
453 self.grow = np.flatnonzero(gkeep)
454 self.lrow = np.flatnonzero(bkeep)
456 def bus_id(self,k):
457 """Bus number of internal bus `k`"""
458 return int(self.bus[self.brow[k],0])
460 def bus_ref(self,k):
461 """(label, table, row) of internal bus `k`"""
462 return f"bus {self.bus_id(k)}","bus",int(self.brow[k])
464 def branch_ref(self,e):
465 """(label, table, row) of internal branch `e`"""
466 n = int(self.lrow[e])
467 return f"branch {n+1} ({int(self.branch[n,0])}-{int(self.branch[n,1])})","branch",n
469 def gen_ref(self,k):
470 """(label, table, row) of internal generator `k`"""
471 n = int(self.grow[k])
472 return f"gen {n+1} @{int(self.gen[n,0])}","gen",n
474 def pair_refs(self,i,j):
475 """(label, table, row) of the case branches joining internal buses `i` and `j`"""
476 a,b = self.bus_id(i),self.bus_id(j)
477 refs = [self.branch_ref(e) for e,n in enumerate(self.lrow)
478 if {int(self.branch[n,0]),int(self.branch[n,1])} == {a,b}]
479 return refs or [(f"buses {a}-{b}",None,None)]
481def _describe_constraint(build,n) -> str:
482 """Describe CVXPY constraint `n` of `build` by the variables it involves"""
483 try:
484 con = build.prob.constraints[n]
485 names = sorted({v.name() for v in con.variables()})
486 except Exception: # pylint: disable=broad-exception-caught
487 return "not identified (CVXPY numbering of a prepared problem)"
488 size = int(np.prod(con.shape)) if con.shape else 1
489 kind = type(con).__name__.lower()
490 what = "; ".join(VARIABLES.get(x,x) for x in names)
491 if any(x.startswith("branch_") for x in names) and {"theta","v"} <= set(names): 491 ↛ 493line 491 didn't jump to line 493 because the condition on line 491 was always true
492 return f"{size} AC branch flow equations (pi model): {what}"
493 if {"P_vec","theta","v"} <= set(names) or {"Q_vec","theta","v"} <= set(names):
494 return f"{size} AC power flow terms from voltages: {what}"
495 return f"{kind} over {size} element(s): {what}"
497def _pwl_nonconvex(gencost,elements) -> list:
498 """Constraint rows for the in-service piecewise-linear costs with decreasing slopes"""
499 rows = []
500 for k,c in enumerate(gencost):
501 if int(c[0]) != 1 or int(c[3]) < 3:
502 continue
503 pts = np.asarray(c[4:4+2*int(c[3])],dtype=float).reshape(-1,2)
504 slopes = np.diff(pts[:,1]) / np.diff(pts[:,0])
505 if np.any(np.diff(slopes) < -1e-12):
506 label,_,n = elements.gen_ref(k)
507 rows.append(_row("cost curve replaced by its lower convex hull",
508 label.replace("gen","gencost for gen"),"gencost",n,
509 "segment slopes " + ", ".join(f"{x:.4g}" for x in slopes) + " $/MWh"))
510 return rows
512def _socp_detail(build,res,recovered,elements) -> dict:
513 """Detail of a non-exact SOCP relaxation: relaxed constraints that fail, then
514 the worst AC violation of each kind at the recovered voltages"""
515 rows = []
516 pairs = np.asarray(build.data["voltage_product_pairs"])
517 tol = recovered.get("tolerances") or {}
518 if recovered.get("edge_tight") is False: 518 ↛ 528line 518 didn't jump to line 528 because the condition on line 518 was always true
519 from cvxopf import audit_socp_relaxation # pylint: disable=import-outside-toplevel
520 audit = audit_socp_relaxation(build,res) or {}
521 gaps = np.atleast_2d((audit.get("edge_gaps") or {})["normalized_signed"])[0]
522 for k in np.argsort(-np.abs(gaps)): 522 ↛ 528line 522 didn't jump to line 528 because the loop on line 522 didn't complete
523 if abs(gaps[k]) <= tol.get("rank_relative",1e-5):
524 break
525 for label,table,row in elements.pair_refs(*pairs[k]):
526 rows.append(_row("|W_ij|^2 = w_i w_j, relaxed to <= (voltage product cone)",
527 label,table,row,f"relative gap {gaps[k]:.3g}"))
528 cycle = recovered.get("cycle_angles")
529 if cycle is not None and np.size(cycle): 529 ↛ 539line 529 didn't jump to line 539 because the condition on line 529 was always true
530 errs = np.atleast_2d(cycle)[0]
531 edges = np.asarray(recovered["non_tree_edges"])
532 for k in np.argsort(-np.abs(errs)):
533 if abs(errs[k]) <= tol.get("cycle_angle",1e-5): 533 ↛ 534line 533 didn't jump to line 534 because the condition on line 533 was never true
534 break
535 for label,table,row in elements.pair_refs(*pairs[edges[k]]):
536 rows.append(_row("angle differences around the loop this branch closes sum to "
537 "zero (theta_i - theta_j = angle of W_ij); dropped by the relaxation",
538 label,table,row,f"{np.degrees(errs[k]):.3g} deg"))
539 ac = recovered.get("ac_audit") or {}
540 checks = {"p_balance":("real power balance at the bus (recovered voltages)","bus"),
541 "q_balance":("reactive power balance at the bus (recovered voltages)","bus"),
542 "voltage_bounds":("Vmin^2 <= Vm^2 <= Vmax^2","bus"),
543 "voltage_setpoints":("Vm = Vg at a PV or reference bus","bus"),
544 "branch_from":("|S| <= rateA at the from bus (recovered voltages)","branch"),
545 "branch_to":("|S| <= rateA at the to bus (recovered voltages)","branch"),
546 "generator_p":("Pmin <= Pg <= Pmax","gen"),"generator_q":("Qmin <= Qg <= Qmax","gen")}
547 for key,(text,table) in checks.items():
548 r = (ac.get("residuals") or {}).get(key)
549 if not r or r.get("passed") is not False or not r.get("worst"):
550 continue
551 k = r["worst"]["identity"]
552 label,table,row = {"bus":elements.bus_ref,"branch":elements.branch_ref,
553 "gen":elements.gen_ref}[table](int(k))
554 rows.append(_row(text,label,table,row,f"{r['maximum']:.4g} {r['units']} "
555 + ("mismatch" if key.endswith("balance") or key == "voltage_setpoints"
556 else "over the limit")))
557 return _detail("socp",rows)
559def _cvxopf_warnings(caught,build,elements,rows) -> list:
560 """Return `(message, detail)` for the distinct cvxopf warnings in `caught`,
561 with internal indexes replaced by case rows and per-element warnings grouped"""
562 out,seen = [],set()
563 rate,sentinel,slow = [],None,[]
564 for w in caught:
565 text = str(w.message).strip()
566 if text in seen or not (issubclass(w.category,UserWarning) 566 ↛ 568line 566 didn't jump to line 568 because the condition on line 566 was never true
567 or w.category.__name__ == "CostAccuracyWarning"):
568 continue
569 seen.add(text)
570 m = re.match(r"Branch (\d+) \(bus \d+ -> \d+\) has rateA=0; substituting "
571 r"branch_limit_sentinel=([0-9.eE+-]+) MW",text)
572 if m:
573 rate.append(int(m[1]))
574 sentinel = float(m[2])
575 continue
576 m = re.match(r"Constraint #(\d+) contains too many subexpressions",text)
577 if m: 577 ↛ 578line 577 didn't jump to line 578 because the condition on line 577 was never true
578 slow.append(int(m[1]))
579 continue
580 message,detail = f"cvxopf warning: {text}",None
581 m = re.match(r"HVDC link (\d+) at step \d+: box \[([^,]+), ([^\]]+)\] straddles zero "
582 r"with loss_percent=([0-9.eE+-]+)",text)
583 if m and int(m[1]) < len(rows): 583 ↛ 584line 583 didn't jump to line 584 because the condition on line 583 was never true
584 n = rows[int(m[1])]
585 message = f"cvxopf warning: DC line {n+1} can flow either way (Pmin < 0 < Pmax); " \
586 "solved without loss"
587 detail = _detail("hvdc_straddle",[_row("Pt = Pf (lossless) instead of "
588 "Pt = Pf - loss1 |Pf|",f"dcline {n+1}","dcline",n,
589 f"loss1 = {float(m[4])/100:g}")])
590 elif "piecewise-linear cost is nonconvex" in text: 590 ↛ 591line 590 didn't jump to line 591 because the condition on line 590 was never true
591 detail = _detail("pwl_nonconvex",_pwl_nonconvex(elements.gencost,elements))
592 elif text.startswith("Solution may be inaccurate"): 592 ↛ 594line 592 didn't jump to line 594 because the condition on line 592 was always true
593 detail = _detail("inaccurate")
594 elif w.category.__name__ == "CostAccuracyWarning":
595 detail = _detail("cost_accuracy")
596 out.append((message,detail))
597 if rate:
598 out.insert(0,(f"cvxopf warning: {len(rate)} branch(es) with rateA = 0 limited to "
599 f"{sentinel:g} MW (lossy network flow model)",_detail("rate_a",[
600 _row(f"|P| <= {sentinel:g} MW (rateA = 0 in the case)",*elements.branch_ref(e))
601 for e in rate])))
602 if slow: 602 ↛ 603line 602 didn't jump to line 603 because the condition on line 602 was never true
603 out.append((f"CVXPY: constraint(s) {', '.join(f'#{n}' for n in slow)} are slow to "
604 "compile (too many subexpressions); results are not affected",
605 _detail("subexpressions",[_row(f"#{n}: {_describe_constraint(build,n)}")
606 for n in slow])))
607 return out
609def _pad(a,ncol):
610 """Return a float copy of the 2-D array `a` with at least `ncol` columns (zero filled)"""
611 a = np.asarray(a,dtype=float).reshape(len(a),-1)
612 out = np.zeros((a.shape[0],max(ncol,a.shape[1])))
613 out[:,:a.shape[1]] = a
614 return out
616def _step(res,t):
617 """Return the results of time step `t` of a multistep `res` (time first),
618 or `res` itself when `t` is `None`"""
619 if t is None:
620 return res
621 return {k:(v[t] if isinstance(v,np.ndarray) and v.ndim >= 1 and v.shape[0] > t else v)
622 for k,v in res.items()}
624def _step_cost(ppc,g,d,gkeep):
625 """Generator and DC line cost ($/h) of one step's dispatch: `g` and `d`,
626 the `runopf`-layout `gen` and `dcline` arrays"""
627 from pypower8.totcost import totcost # pylint: disable=import-outside-toplevel
628 gen = ppc["gen"]
629 on = gkeep & (gen[:,7] == 1)
630 cost = float(np.sum(totcost(ppc["gencost"][:len(gen)][on],g[on,1]))) if on.any() else 0.0
631 costs = ppc.get("dclinecost")
632 if d is not None and costs is not None and len(costs):
633 on = d[:,2] != 0
634 if on.any():
635 cost += float(np.sum(totcost(np.asarray(costs)[:len(d)][on],np.abs(d[on,3]))))
636 return cost
638def _series_frames(series,live,rows,formulation):
639 """Return the `build_opf_multistep` keyword arguments for the per-step
640 case values in `series` (see `runopf`)"""
641 import pandas as pd # pylint: disable=import-outside-toplevel
642 out = {"T":int(series["T"]),"delta":float(series["delta"]),
643 "df_P":pd.DataFrame(np.asarray(series["Pd"],dtype=float)[:,live]),
644 "df_Q":pd.DataFrame(np.asarray(series["Qd"],dtype=float)[:,live])
645 if formulation in ("ac","socp") else None}
646 if rows:
647 pmin,pmax = np.asarray(series["dcline_Pmin"],dtype=float),np.asarray(series["dcline_Pmax"],dtype=float)
648 out["df_hvdc_min"] = pd.DataFrame({f"dcline-{n+1}":-pmax[:,n] for n in rows})
649 out["df_hvdc_max"] = pd.DataFrame({f"dcline-{n+1}":-pmin[:,n] for n in rows})
650 return out
652def _gen_limits(build,series,gen,gkeep,base,extra_gens=0):
653 """Add the per-step generator limits of `series["gen_limited"]` rows to
654 `build` (`extra_gens`: storage charging generators after the kept ones)"""
655 import cvxpy as cp # pylint: disable=import-outside-toplevel
656 pg = build.variables["Pg"]
657 T = int(series["T"])
658 kept = np.cumsum(gkeep) - 1
659 pmin,pmax = np.asarray(series["gen_Pmin"],dtype=float),np.asarray(series["gen_Pmax"],dtype=float)
660 extra = []
661 for n in series["gen_limited"]:
662 if not gkeep[n] or gen[n,7] == 0: 662 ↛ 663line 662 didn't jump to line 663 because the condition on line 662 was never true
663 continue
664 k = int(kept[n])
665 if isinstance(pg,(list,tuple)): # stepwise assembly: one variable per step
666 for t in range(T):
667 extra += [pg[t][k] <= pmax[t,n]/base,pg[t][k] >= pmin[t,n]/base]
668 continue
669 x = pg[k,:] if pg.shape == (int(gkeep.sum()) + extra_gens,T) else pg[:,k]
670 extra += [x <= pmax[:,n]/base,x >= pmin[:,n]/base]
671 if extra: 671 ↛ exitline 671 didn't return from function '_gen_limits' because the condition on line 671 was always true
672 build.prob = cp.Problem(build.prob.objective,list(build.prob.constraints) + extra)
674def _pg_column(pg,k,T,ng):
675 """CVXPY expression of the `T` per-step outputs of kept generator `k`
676 (`ng` kept generators) from cvxopf's `Pg` variable (vectorized: one
677 matrix; stepwise: one vector per step)"""
678 import cvxpy as cp # pylint: disable=import-outside-toplevel
679 if isinstance(pg,(list,tuple)):
680 return cp.hstack([pg[t][k] for t in range(T)])
681 return pg[k,:] if pg.shape == (ng,T) else pg[:,k]
683def _storage_units(series,ppc,gkeep,live,note):
684 """Return the storage of `series["storage"]` that can be modeled, each
685 with `k` (its generator among the kept ones) and `cbus` (charging bus
686 number); notes the rows left out"""
687 gen,bus = ppc["gen"],ppc["bus"]
688 kept = np.cumsum(gkeep) - 1
689 ids = set(bus[live,0].astype(int))
690 out,skipped = [],[]
691 for unit in series.get("storage") or []:
692 g = unit["gen"]
693 cbus = int(gen[g,0]) if unit["bus"] is None else unit["bus"]
694 if not gkeep[g] or gen[g,7] == 0 or cbus not in ids:
695 skipped.append(unit)
696 continue
697 out.append(dict(unit,k=int(kept[g]),cbus=cbus))
698 if skipped:
699 note(f"Storage row(s) {', '.join(str(u['row']+1) for u in skipped)} not modeled: "
700 "its generator is out of service or at an isolated bus, or its charging bus is isolated",
701 _detail("storage_cut",[_row("storage left out (no charge or discharge)",
702 f"storage {u['row']+1}","storage",u["row"]) for u in skipped]))
703 return out
705def _charge_gens(cgen,gencost,units,bus):
706 """Append one charging generator per storage unit to `cgen` (output
707 -Smax..0 at its charging bus, no reactive power) and zero cost rows to
708 `gencost`"""
709 vm = {int(b[0]):float(b[7]) for b in bus}
710 rows,costs = [],[]
711 for u in units:
712 row = np.zeros(cgen.shape[1])
713 row[0],row[5],row[6],row[7] = u["cbus"],vm.get(u["cbus"],1.0),cgen[u["k"],6],1
714 row[9] = -u["Smax"]
715 rows.append(row)
716 cost = np.zeros(gencost.shape[1])
717 cost[0],cost[3] = 2,gencost.shape[1] - 4
718 costs.append(cost)
719 return np.vstack([cgen]+rows),np.vstack([gencost]+costs)
721def _storage_constraints(build,units,T,delta,base,ng):
722 """Add the storage energy balance to `build` (`ng` kept generators, the
723 charging generators after them) and return each unit's energy variable,
724 discharge and charge expressions (MW)"""
725 import cvxpy as cp # pylint: disable=import-outside-toplevel
726 pg = build.variables["Pg"]
727 ntot = ng + len(units)
728 extra,cost,out = [],0,[]
729 for j,u in enumerate(units):
730 d = base*_pg_column(pg,u["k"],T,ntot)
731 c = -base*_pg_column(pg,ng+j,T,ntot)
732 e = cp.Variable(T,name=f"storage_{u['row']+1}_E")
733 keep = (1 - u["self_discharge"])**(delta/HOURS_PER_MONTH)
734 net = delta*(u["eta_ch"]*c - d/u["eta_dis"])
735 extra += [d >= 0,d <= u["Smax"],e >= u["Emin"],e <= u["Emax"],
736 e[0] == keep*u["Es"] + net[0]]
737 if T > 1: 737 ↛ 739line 737 didn't jump to line 739 because the condition on line 737 was always true
738 extra.append(e[1:] == keep*e[:-1] + net[1:])
739 if u["Eend"] >= 0:
740 extra.append(e[T-1] == u["Eend"])
741 if u["aging"]: 741 ↛ 743line 741 didn't jump to line 743 because the condition on line 741 was always true
742 cost = cost + u["aging"]*delta*cp.sum(c + d)
743 out.append(e)
744 build.prob = cp.Problem(cp.Minimize(build.prob.objective.expr + cost),
745 list(build.prob.constraints) + extra)
746 return out
748def runopf(ppc:dict,formulation:str,log,options:dict|None=None,series:dict|None=None,
749 progress=None) -> dict:
750 """Solve `ppc` with the cvxopf `formulation` (see the module docstring)
752 Arguments
753 ---------
755 - `ppc`: PYPOWER case of numpy arrays (`Case.to_ppc(arrays=True)`)
757 - `formulation`: one of `FORMULATIONS`
759 - `log`: text stream for notes and cvxopf warnings
761 - `options`: solve options (see the module docstring and `solve_options`)
763 - `series`: `None` for one OPF, or a multistep horizon (issue #124):
764 `T` (steps), `delta` (hours per step), `Pd` and `Qd` (`T` rows of
765 one value per `bus` row), `gen_Pmin`, `gen_Pmax` (one per `gen`
766 row), `dcline_Pmin`, `dcline_Pmax` (one per `dcline` row), and
767 `gen_limited` (the `gen` rows whose limits change by step). The
768 horizon is built with `build_opf_multistep`: loads by step (`df_P`;
769 `df_Q` for `ac` and `socp`), DC line limits by step (`df_hvdc_min`,
770 `df_hvdc_max`, signs reversed as above). cvxopf has no per-step
771 generator limits, so the case `Pmin`/`Pmax` of a `gen_limited` row
772 are set to the smallest `Pmin` and largest `Pmax` of the horizon and
773 `Pmin(t) <= Pg(t) <= Pmax(t)` is added to the CVXPY problem; this
774 needs the `default` preparation.
776 - `progress`: `None`, or a function called with a progress report
777 dict at each phase of the solve: `phase` (`build`, `derivatives`,
778 `iterate`, `solve`, `results`) and `text`; while IPOPT iterates
779 (`ac`), also `iteration`, `max_iter`, `objective` (IPOPT's internal
780 objective value), `inf_pr` and `inf_du` (primal and dual
781 infeasibility), at most every `PROGRESS_INTERVAL` seconds
782 (`_ipopt_progress`)
784 Returns
785 -------
787 - `dict`: PYPOWER-style OPF results (see the module docstring), plus
788 `status` (the solver status) and `warnings` (notes on data cvxopf
789 does not model, cvxopf's warnings and relaxation checks that failed,
790 as `{"message", "detail"}`). With `series`, `f` is cvxopf's horizon
791 objective ($, rates times `delta`) and `steps` lists one result per
792 step (`bus`, `gen`, `branch`, `dcline`, `success`, `flows`,
793 `baseMVA`, and `f`: that step's generator and DC line cost in $/h)
795 Exceptions
796 ----------
798 - `ValueError`: data or options cvxopf cannot use; cvxopf's own errors pass through
799 """
800 from cvxopf import build_opf, build_opf_multistep, extract_results, ACCEPTED_SOLVER_STATUSES, \
801 OPFOptions, NumericalPreparation # pylint: disable=import-outside-toplevel
802 opts = solve_options(options,formulation)
803 if series and series.get("gen_limited") and opts["preparation"] != "default": 803 ↛ 804line 803 didn't jump to line 804 because the condition on line 803 was never true
804 raise ValueError("per-step generator limits (gen Pmin, Pmax series) need the default "
805 "cvxopf preparation")
806 notes = []
807 def note(text,detail=None):
808 notes.append({"message":text,"detail":detail})
809 log.write(text + "\n")
810 start = time.time()
811 bus,gen,branch = ppc["bus"],ppc["gen"],ppc["branch"]
812 live = bus[:,1] != 4
813 ids = set(bus[live,0].astype(int))
814 gkeep = np.array([int(b) in ids for b in gen[:,0]],dtype=bool)
815 bkeep = np.array([int(f) in ids and int(t) in ids for f,t in branch[:,:2]],dtype=bool)
816 gencost = ppc["gencost"]
817 if len(gencost) == 2*len(gen):
818 note("Reactive power cost rows are ignored: cvxopf has no reactive power costs",
819 _detail("reactive_cost",[_row("cost of Qg left out of the objective",
820 f"gencost for Q of gen {n+1} @{int(gen[n,0])}","gencost",len(gen)+n)
821 for n in np.flatnonzero(gkeep)]))
822 gencost = gencost[:len(gen)]
823 cgen = gen[gkeep].copy()
824 if series and series.get("gen_limited"):
825 kept = np.cumsum(gkeep) - 1
826 pmin = np.asarray(series["gen_Pmin"],dtype=float).min(axis=0) # once, not per gen (T x gens)
827 pmax = np.asarray(series["gen_Pmax"],dtype=float).max(axis=0)
828 for n in series["gen_limited"]:
829 if gkeep[n]: 829 ↛ 828line 829 didn't jump to line 828 because the condition on line 829 was always true
830 cgen[kept[n],9] = float(pmin[n])
831 cgen[kept[n],8] = float(pmax[n])
832 ccost = gencost[gkeep]
833 units = _storage_units(series,ppc,gkeep,live,note) if series else []
834 if units:
835 if opts["preparation"] != "default": 835 ↛ 836line 835 didn't jump to line 836 because the condition on line 835 was never true
836 raise ValueError("storage needs the default cvxopf preparation")
837 cgen,ccost = _charge_gens(cgen,ccost,units,bus)
838 case = {"version":"2","baseMVA":float(ppc["baseMVA"]),"bus":bus[live],
839 "gen":cgen,"branch":branch[bkeep],"gencost":ccost}
840 links,rows = [],[]
841 if "dcline" in ppc:
842 if formulation == "singlenode_dc":
843 note("DC lines are ignored by the copper-plate model (singlenode_dc)",
844 _detail("dcline_copper",[_row("not modeled (no network)",f"dcline {n+1}",
845 "dcline",n) for n,d in enumerate(ppc["dcline"]) if d[2] != 0]))
846 else:
847 dppc = ppc
848 if series: # static boxes enclose every step's box
849 dppc = dict(ppc,dcline=ppc["dcline"].copy())
850 dppc["dcline"][:,9] = np.min(np.asarray(series["dcline_Pmin"],dtype=float),axis=0)
851 dppc["dcline"][:,10] = np.max(np.asarray(series["dcline_Pmax"],dtype=float),axis=0)
852 links,rows = _hvdc_links(dppc,note)
853 build_options = None
854 if opts["preparation"] == "recommended":
855 build_options = OPFOptions(numerical_preparation=NumericalPreparation(**RECOMMENDED[formulation]))
856 ms_build,ms_fields = _multistep_build(opts["multistep"],formulation) if series else ({},{})
857 if ms_fields:
858 prep = build_options.numerical_preparation if build_options else None
859 build_options = OPFOptions(**ms_fields,**({"numerical_preparation":prep} if prep else {}))
860 kwargs = dict(opts["solver_options"])
861 if opts["solver"]:
862 kwargs["solver"] = opts["solver"]
863 if opts["verbose"]:
864 kwargs["verbose"] = True
865 log.write(f"cvxopf {formulation}: {opts['preparation']} preparation"
866 + "".join(f", {k}={v}" for k,v in (RECOMMENDED[formulation].items()
867 if opts["preparation"] == "recommended" else ()))
868 + f"; solver {opts['solver'] or ('IPOPT' if formulation == 'ac' else 'CLARABEL')}"
869 + "".join(f", {k}={v!r}" for k,v in opts["solver_options"].items()) + "\n")
870 if series:
871 log.write(f"cvxopf multistep horizon: {int(series['T'])} step(s) of {float(series['delta']):g} h; "
872 + ", ".join(f"{k}={v}" for k,v in {**ms_build,**ms_fields}.items()) + "\n")
873 report = progress or (lambda p: None)
874 solver = opts["solver"] or ("IPOPT" if formulation == "ac" else "CLARABEL")
875 with warnings.catch_warnings(record=True) as caught:
876 warnings.simplefilter("always")
877 report({"phase":"build","text":f"building the {formulation} model"
878 + (f" ({int(series['T'])} steps)" if series else "")})
879 if series:
880 build = build_opf_multistep(case,formulation=formulation,hvdc=links or None,
881 options=build_options,**{"automatic_sparse_dispatch":True,**ms_build}, # issue #122
882 **_series_frames(series,live,rows,formulation))
883 if series.get("gen_limited"):
884 _gen_limits(build,series,gen,gkeep,float(ppc["baseMVA"]),len(units))
885 energy = _storage_constraints(build,units,int(series["T"]),float(series["delta"]),
886 float(ppc["baseMVA"]),int(gkeep.sum())) if units else []
887 else:
888 build = build_opf(case,formulation=formulation,hvdc=links or None,options=build_options,
889 automatic_sparse_dispatch=True) # issue #122: keep CVXPY's sparse derivatives
890 report({"phase":"solve","text":f"solving with {solver}"})
891 with _capture_output(log,opts["verbose"]),_ipopt_progress(progress,
892 opts["solver_options"].get("max_iter",IPOPT_MAX_ITER)):
893 build.solve(**kwargs)
894 report({"phase":"results","text":"reading the results"})
895 res = extract_results(build)
896 stored = None
897 # take the charging generators out of the results; a failed solve may
898 # have no Pg to reshape, so its status is reported instead (issue #160)
899 if units and res["status"] in ACCEPTED_SOLVER_STATUSES:
900 ng = int(gkeep.sum())
901 pgs = np.asarray(res["Pg"],dtype=float).reshape(int(series["T"]),-1)
902 stored = {"dis":pgs[:,[u["k"] for u in units]],"ch":-pgs[:,ng:],
903 "E":[None if e.value is None else np.ravel(e.value) for e in energy]}
904 res = dict(res,Pg=pgs[:,:ng])
905 if res.get("Qg") is not None:
906 res["Qg"] = np.asarray(res["Qg"],dtype=float).reshape(int(series["T"]),-1)[:,:ng]
907 recovered = None
908 if formulation == "socp" and res["status"] in ACCEPTED_SOLVER_STATUSES:
909 from cvxopf import recover_socp_voltage # pylint: disable=import-outside-toplevel
910 recovered = recover_socp_voltage(build,res)
911 elements = _Elements(bus,gen,branch,live,gkeep,bkeep,gencost[gkeep])
912 for text,detail in _cvxopf_warnings(caught,build,elements,rows):
913 note(text,detail)
914 success = res["status"] in ACCEPTED_SOLVER_STATUSES
915 log.write(f"cvxopf {formulation}: solver status {res['status']}\n")
916 out = {"baseMVA":ppc["baseMVA"],"success":success,"et":time.time()-start,
917 "flows":formulation != "singlenode_dc","status":str(res["status"]),"warnings":notes}
918 if formulation == "socp" and success:
919 exact = recovered and recovered.get("exact_product_recovery")
920 feasible = recovered and recovered.get("ac_feasible")
921 log.write("SOCP relaxation: Vm is sqrt(w); Va is "
922 + ("from cvxopf's spanning-forest voltage recovery"
923 if recovered and recovered.get("candidate") else "not available (0)")
924 + "; exact relaxation: " + {True:"yes",False:"no",None:"unknown"}[exact]
925 + ", recovered voltages AC feasible: " + {True:"yes",False:"no",None:"unknown"}[feasible] + "\n")
926 text = "SOCP relaxation is not exact: Vm and Va are not an AC power flow solution" \
927 if exact is False else "SOCP relaxation: the recovered voltages are not AC feasible" \
928 if feasible is False else None
929 if text:
930 try:
931 detail = _socp_detail(build,res,recovered,elements)
932 except Exception as err: # pylint: disable=broad-exception-caught
933 detail = _detail("socp",
934 explain=EXPLAIN["socp"] + f" (constraint check unavailable: {err})")
935 notes.append({"message":text + (" (details for the first step)" if series else ""),
936 "detail":detail})
937 elif formulation in ("lossy_dc","singlenode_dc") and success:
938 log.write("DC formulation: flat voltages (1 pu) and no angles "
939 + ("(lossy_dc is a network-flow model, not a phase-angle DC power flow)\n"
940 if formulation == "lossy_dc" else "(copper plate: no network, no branch flows)\n"))
941 fill = lambda t: _fill(ppc,formulation,_step(res,t),recovered,t,success,live,gkeep,bkeep,rows)
942 if not series:
943 out.update(fill(None))
944 if success:
945 out["f"] = float(res["objective"])
946 return out
947 out["steps"] = []
948 for t in range(int(series["T"])):
949 step = fill(t)
950 step.update({"baseMVA":ppc["baseMVA"],"success":success,"flows":out["flows"]})
951 step["storage"] = _storage_step(series,units,stored,t,success)
952 if success:
953 step["f"] = _step_cost(ppc,step["gen"],step.get("dcline"),gkeep) \
954 + sum(x["cost"] for x in step["storage"])
955 out["steps"].append(step)
956 out.update({k:out["steps"][0][k] for k in ("bus","gen","branch","dcline") if k in out["steps"][0]})
957 if success:
958 out["f"] = float(res["objective"])
959 return out
961def _storage_step(series,units,stored,t,success) -> list:
962 """Storage results of step `t`: one row per `storage` table row"""
963 by_row = {u["row"]:j for j,u in enumerate(units)}
964 out = []
965 for n in range(int(series.get("storage_rows",0))):
966 row = {"row":n,"solved":False,"Pdis":0.0,"Pch":0.0,"E":None,"cost":0.0}
967 j = by_row.get(n)
968 if j is not None and success and stored is not None:
969 u = units[j]
970 dis,ch = float(stored["dis"][t,j]),float(stored["ch"][t,j])
971 e = stored["E"][j]
972 row.update(solved=True,Pdis=dis,Pch=ch,E=None if e is None else float(e[t]),
973 cost=u["aging"]*(abs(ch) + abs(dis)))
974 out.append(row)
975 return out
977def _fill(ppc,formulation,res,recovered,t,success,live,gkeep,bkeep,rows) -> dict:
978 """Return `bus`, `gen`, `branch` (and `dcline`) arrays in the `runopf`
979 layout for one solution `res` (step `t` of a horizon, or `None`)"""
980 bus,gen,branch = ppc["bus"],ppc["gen"],ppc["branch"]
981 out = {"bus":_pad(bus,17),"gen":_pad(gen,25),"branch":_pad(branch,21)}
982 out["gen"][:,1:3] = 0.0
983 out["branch"][:,13:21] = 0.0
984 if "dcline" in ppc:
985 out["dcline"] = _pad(ppc["dcline"],19)
986 out["dcline"][:,3:9] = 0.0
987 out["dcline"][:,17:19] = 0.0
988 if formulation == "singlenode_dc":
989 out["dcline"][:,2] = 0
990 if not success:
991 return out
992 b,g,br = out["bus"],out["gen"],out["branch"]
993 if formulation == "ac":
994 b[live,7],b[live,8] = res["Vm"],res["Va_deg"]
995 elif formulation == "socp":
996 b[live,7],b[live,8] = res["Vm_relaxed"],0.0
997 cand = recovered and recovered.get("candidate")
998 if cand and cand.get("Va_deg") is not None:
999 va = np.asarray(cand["Va_deg"],dtype=float)
1000 b[live,8] = np.ravel(va if t is None or va.ndim < 2 else va[t])
1001 else:
1002 b[live,7],b[live,8] = 1.0,0.0
1003 g[gkeep,1] = res["Pg"]
1004 if res.get("Qg") is not None:
1005 g[gkeep,2] = res["Qg"]
1006 g[g[:,7] == 0,1:3] = 0.0
1007 if formulation in ("ac","socp"):
1008 for col,key in zip(range(13,17),("branch_p_from","branch_q_from","branch_p_to","branch_q_to")):
1009 br[bkeep,col] = res[key]
1010 elif formulation == "lossy_dc":
1011 br[bkeep,13],br[bkeep,15] = res["p_flows"],-np.asarray(res["p_flows"])
1012 br[br[:,10] == 0,13:17] = 0.0
1013 if rows:
1014 d = out["dcline"]
1015 vm = {int(x[0]):x[7] for x in b}
1016 for k,n in enumerate(rows):
1017 d[n,3] = -float(np.ravel(res["p_hvdc_in"])[k])
1018 d[n,4] = float(np.ravel(res["p_hvdc_out"])[k])
1019 d[n,7],d[n,8] = vm[int(d[n,0])],vm[int(d[n,1])]
1020 return out