hostcap-screen 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,53 @@
1
+ # Drawing positions for the IEEE 39-bus (New England) test system, used by the
2
+ # network map in reports. They follow the usual one-line arrangement of this
3
+ # system: generator 10 (bus 30) and bus 2 at the upper left, the 345 kV ring
4
+ # through buses 1-9 down the left side and across the bottom, bus 16 near the
5
+ # middle, generators 6 and 7 (buses 35, 36) at the right, and bus 39 (the
6
+ # slack, generator 1 in the original numbering) at the lower left.
7
+ #
8
+ # Units are arbitrary drawing units: x to the right, y downward. The positions
9
+ # are a drawing, not geography. The same file is meant to be shared with
10
+ # SCR-Screen so both tools draw this network the same way.
11
+ #
12
+ # Checked by tests/test_report_layout.py: every bus of the case has a position,
13
+ # no two lines cross, and no bus sits on a line it is not connected to.
14
+ positions:
15
+ 1: [1.0, 5.6]
16
+ 2: [2.0, 2.6]
17
+ 3: [3.5, 4.0]
18
+ 4: [4.0, 5.6]
19
+ 5: [3.4, 7.0]
20
+ 6: [4.8, 7.2]
21
+ 7: [3.6, 8.2]
22
+ 8: [2.6, 8.6]
23
+ 9: [1.6, 9.3]
24
+ 10: [7.0, 9.2]
25
+ 11: [5.9, 7.4]
26
+ 12: [7.0, 7.95]
27
+ 13: [8.1, 7.4]
28
+ 14: [6.0, 5.8]
29
+ 15: [7.6, 5.8]
30
+ 16: [9.2, 5.2]
31
+ 17: [8.0, 4.6]
32
+ 18: [5.5, 4.0]
33
+ 19: [10.0, 7.4]
34
+ 20: [9.4, 8.6]
35
+ 21: [11.5, 4.4]
36
+ 22: [13.5, 4.4]
37
+ 23: [13.5, 6.2]
38
+ 24: [11.0, 6.0]
39
+ 25: [3.5, 1.6]
40
+ 26: [7.5, 1.6]
41
+ 27: [8.0, 3.4]
42
+ 28: [11.0, 0.9]
43
+ 29: [13.0, 2.0]
44
+ 30: [0.6, 1.4]
45
+ 31: [5.2, 8.6]
46
+ 32: [7.0, 10.2]
47
+ 33: [11.0, 8.6]
48
+ 34: [9.4, 9.7]
49
+ 35: [15.4, 4.4]
50
+ 36: [15.4, 6.2]
51
+ 37: [3.5, 0.4]
52
+ 38: [14.6, 1.0]
53
+ 39: [0.6, 8.2]
@@ -0,0 +1,514 @@
1
+ """Core screening engine: transmission injection capability at each bus.
2
+
3
+ For each candidate bus, a new generating plant is added and its output is
4
+ increased until a thermal or voltage limit is violated in the base case or
5
+ in any single line/transformer outage (N-1). A bisection search finds the
6
+ largest output (within a tolerance) with no new or worsened violations.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import copy
12
+ import math
13
+ import time
14
+ import warnings
15
+ from dataclasses import dataclass, field
16
+ from typing import Optional
17
+
18
+ import numpy as np
19
+ import pandapower as pp
20
+ import pandapower.topology as top
21
+
22
+ from .criteria import Criteria
23
+ from .network import candidate_labels, label_to_index, voltage_controlled_buses
24
+ from .redispatch import REDISPATCH_MODES, proportional_pickup, proportional_reduction, redispatch_headroom
25
+
26
+ try: # numba makes pandapower much faster but is optional
27
+ import numba # noqa: F401
28
+ HAS_NUMBA = True
29
+ except ImportError: # pragma: no cover
30
+ HAS_NUMBA = False
31
+
32
+ REACTIVE_MODES = ("unity", "voltage")
33
+ BASE = ("base", None)
34
+
35
+
36
+ @dataclass
37
+ class Violation:
38
+ kind: str # "voltage_low", "voltage_high", "thermal_line", "thermal_trafo", "non_convergence"
39
+ element: str # readable element name
40
+ condition: str # "Base case" or outage name
41
+ value: float # per unit or percent
42
+ limit: float
43
+ severity: float # exceedance normalized by the limit (for ranking)
44
+ element_id: str = "" # "bus:<label>", "line:<index>", "trafo:<index>"
45
+ outage_id: str = "" # "" for the base case, else "line:<index>", "trafo:<index>" or "gen:<index>"
46
+ flow_from: str = "" # thermal only: label of the bus the active power flows from
47
+
48
+ def as_dict(self) -> dict:
49
+ return self.__dict__.copy()
50
+
51
+
52
+ @dataclass
53
+ class BusResult:
54
+ bus: str
55
+ capability_mw: float
56
+ status: str
57
+ binding: Optional[Violation] = None
58
+ violations_at_limit: list = field(default_factory=list)
59
+ plant_q_mvar: Optional[float] = None
60
+ plant_q_limited: bool = False
61
+ warnings: list = field(default_factory=list)
62
+ runtime_s: float = 0.0
63
+ next_mw: Optional[float] = None # capability if the binding element were upgraded
64
+ next_binding: Optional[Violation] = None
65
+ next_note: str = ""
66
+
67
+
68
+ class Screener:
69
+ def __init__(
70
+ self,
71
+ net,
72
+ criteria: Criteria,
73
+ redispatch: str = "proportional",
74
+ reactive: str = "voltage",
75
+ pf_limit: float = 0.95,
76
+ pmax_mw: float = 2000.0,
77
+ tol_mw: float = 1.0,
78
+ include_gen_outages: bool = True,
79
+ next_limit: bool = True,
80
+ ):
81
+ if redispatch not in REDISPATCH_MODES:
82
+ raise ValueError(f"redispatch must be one of {REDISPATCH_MODES}")
83
+ if reactive not in REACTIVE_MODES:
84
+ raise ValueError(f"reactive must be one of {REACTIVE_MODES}")
85
+ if not (0.0 < pf_limit <= 1.0):
86
+ raise ValueError("pf_limit must be in (0, 1]")
87
+ if pmax_mw <= 0 or tol_mw <= 0 or tol_mw >= pmax_mw:
88
+ raise ValueError("Require 0 < tol_mw < pmax_mw")
89
+ criteria.validate()
90
+
91
+ self.crit = criteria
92
+ self.redispatch = redispatch
93
+ self.reactive = reactive
94
+ self.pf_limit = pf_limit
95
+ self.q_per_mw = math.tan(math.acos(pf_limit))
96
+ self.pmax = float(pmax_mw)
97
+ self.tol = float(tol_mw)
98
+ self.base = copy.deepcopy(net)
99
+ self.next_limit = next_limit
100
+ self.vc_buses = voltage_controlled_buses(self.base)
101
+
102
+ # Slack generators set the system reference and balance the rest, so
103
+ # they are never redispatched, used for pickup, or tripped.
104
+ gen_on = self.base.gen.in_service.astype(bool)
105
+ if "slack" in self.base.gen:
106
+ gen_on &= ~self.base.gen["slack"].fillna(False).astype(bool)
107
+ self.gen_idx = self.base.gen.index[gen_on.values]
108
+ self.slack_gen_idx = list(self.base.gen.index[self.base.gen.in_service.astype(bool) & ~gen_on])
109
+ self.p0 = self.base.gen.loc[self.gen_idx, "p_mw"].to_numpy(float)
110
+ pmin = self.base.gen.loc[self.gen_idx, "min_p_mw"] if "min_p_mw" in self.base.gen else None
111
+ self.pmin = np.zeros_like(self.p0) if pmin is None else np.nan_to_num(pmin.to_numpy(float), nan=0.0)
112
+ self.headroom = redispatch_headroom(self.p0, self.pmin) if redispatch == "proportional" else math.inf
113
+ g = self.base.gen
114
+ if "max_p_mw" not in g:
115
+ g["max_p_mw"] = g["p_mw"]
116
+ g["max_p_mw"] = g["max_p_mw"].fillna(g["p_mw"])
117
+ sn = g["sn_mva"] if "sn_mva" in g else None
118
+ if sn is not None and sn.loc[self.gen_idx].notna().all() and (sn.loc[self.gen_idx] > 0).all():
119
+ self.gen_rating, self.pickup_basis = sn.astype(float), "machine MVA rating"
120
+ else:
121
+ self.gen_rating, self.pickup_basis = g["max_p_mw"].clip(lower=0.0).astype(float), "maximum MW"
122
+ self.include_gen_outages = include_gen_outages
123
+
124
+ if not self._runpp(self.base):
125
+ raise RuntimeError("Base case load flow does not converge with no plant added")
126
+ self.ref_vm = self.base.res_bus.vm_pu.copy()
127
+
128
+ self.contingencies, self.skipped = self._build_contingencies()
129
+ self.reference = {} # state -> {key: exceedance}
130
+ self.reference[BASE] = self._violation_map(self.base, BASE)[1]
131
+ for state in list(self.contingencies):
132
+ self._apply_outage(self.base, state, out=True)
133
+ ok = self._runpp(self.base)
134
+ if ok:
135
+ self.reference[state] = self._violation_map(self.base, state)[1]
136
+ self._apply_outage(self.base, state, out=False)
137
+ if not ok:
138
+ self.contingencies.remove(state)
139
+ self.skipped.append((self.state_name(state), "Load flow does not converge even with 0 MW added; review in a detailed study"))
140
+ self._runpp(self.base) # leave base solved
141
+ self._order = list(self.contingencies)
142
+ self._ignore = set() # element keys treated as upgraded (next-limit search)
143
+ self.preexisting = [] # pre-existing violations at 0 MW, for reporting
144
+ for state in [BASE] + self.contingencies:
145
+ self._apply_outage(self.base, state, out=True)
146
+ self._runpp(self.base)
147
+ self.preexisting.extend(v for _, v in self._violation_map(self.base, state)[0])
148
+ self._apply_outage(self.base, state, out=False)
149
+ self._runpp(self.base)
150
+
151
+ # ------------------------------------------------------------------ helpers
152
+ @staticmethod
153
+ def _runpp(net) -> bool:
154
+ try:
155
+ with warnings.catch_warnings():
156
+ warnings.simplefilter("ignore")
157
+ pp.runpp(net, numba=HAS_NUMBA, max_iteration=30)
158
+ return True
159
+ except pp.LoadflowNotConverged:
160
+ return False
161
+
162
+ def _lbl(self, bus_idx) -> str:
163
+ return str(self.base.bus.at[int(bus_idx), "label"])
164
+
165
+ def state_name(self, state) -> str:
166
+ kind, idx = state
167
+ if kind == "base":
168
+ return "Base case"
169
+ if kind == "gen":
170
+ return f"Outage of generator at bus {self._lbl(self.base.gen.at[idx, 'bus'])} (#{idx})"
171
+ if kind == "line":
172
+ row = self.base.line.loc[idx]
173
+ return f"Outage of line {self._lbl(row.from_bus)}-{self._lbl(row.to_bus)} (#{idx})"
174
+ row = self.base.trafo.loc[idx]
175
+ return f"Outage of transformer {self._lbl(row.hv_bus)}-{self._lbl(row.lv_bus)} (#{idx})"
176
+
177
+ def _build_contingencies(self):
178
+ """Lines, transformers and (optionally) generators.
179
+
180
+ Branch outages that island buses are skipped. When the island holds
181
+ only generator buses with no load, the outage is equivalent to losing
182
+ those generators, which the generator outages cover.
183
+ """
184
+ cons, skipped = [], []
185
+ candidates = [("line", i) for i in self.base.line.index[self.base.line.in_service]]
186
+ candidates += [("trafo", i) for i in self.base.trafo.index[self.base.trafo.in_service]]
187
+ load_buses = set(self.base.load.loc[self.base.load.in_service & (self.base.load.p_mw.abs() > 0), "bus"].astype(int))
188
+ gen_buses = set(self.base.gen.loc[self.gen_idx, "bus"].astype(int))
189
+ for state in candidates:
190
+ self._apply_outage(self.base, state, out=True)
191
+ unsupplied = set(top.unsupplied_buses(self.base))
192
+ self._apply_outage(self.base, state, out=False)
193
+ if not unsupplied:
194
+ cons.append(state)
195
+ continue
196
+ names = ", ".join(sorted((self._lbl(b) for b in unsupplied), key=lambda s: (len(s), s)))
197
+ if len(unsupplied) > len(self.base.bus) / 2:
198
+ why = f"Separates the slack source from most of the system ({len(unsupplied)} buses)"
199
+ elif self.include_gen_outages and unsupplied <= gen_buses and not (unsupplied & load_buses):
200
+ why = f"Islands generator bus(es) {names}; covered by the generator outage(s) studied"
201
+ else:
202
+ why = f"Islands bus(es) {names}"
203
+ skipped.append((self.state_name(state), why))
204
+ if self.include_gen_outages:
205
+ cons += [("gen", i) for i in self.gen_idx]
206
+ for i in self.slack_gen_idx:
207
+ skipped.append((self.state_name(("gen", i)), "Slack generator (system reference) is not tripped"))
208
+ return cons, skipped
209
+
210
+ def _apply_outage(self, net, state, out: bool) -> None:
211
+ """Take an element out of service (out=True) or restore it (out=False).
212
+
213
+ Generator outage: the unit's output is picked up by the other original
214
+ units in proportion to their rating (max_p_mw), capped at their maximum,
215
+ as with equal-droop governor response. The slack source covers any
216
+ remainder and the change in losses. The new plant never picks up.
217
+ """
218
+ kind, idx = state
219
+ if kind == "base":
220
+ return
221
+ if kind != "gen":
222
+ getattr(net, kind).at[idx, "in_service"] = not out
223
+ return
224
+ if out:
225
+ self._saved_p = net.gen.loc[self.gen_idx, "p_mw"].to_numpy(float).copy()
226
+ lost = float(net.gen.at[idx, "p_mw"])
227
+ net.gen.at[idx, "in_service"] = False
228
+ others = [g for g in self.gen_idx if g != idx]
229
+ p = net.gen.loc[others, "p_mw"].to_numpy(float)
230
+ pmax = net.gen.loc[others, "max_p_mw"].to_numpy(float)
231
+ net.gen.loc[others, "p_mw"] = proportional_pickup(p, pmax, self.gen_rating[others].to_numpy(float), lost)
232
+ else:
233
+ net.gen.at[idx, "in_service"] = True
234
+ net.gen.loc[self.gen_idx, "p_mw"] = self._saved_p
235
+
236
+ # ------------------------------------------------------------ violations
237
+ def _violation_map(self, net, state):
238
+ """Return ([(key, Violation)], {key: exceedance}) for a solved network."""
239
+ contingency = state != BASE
240
+ cond = self.state_name(state)
241
+ oid = "" if state == BASE else f"{state[0]}:{state[1]}"
242
+ viols, emap = [], {}
243
+
244
+ vm = net.res_bus.vm_pu
245
+ for b in net.bus.index:
246
+ v = vm.at[b]
247
+ vn = float(net.bus.at[b, "vn_kv"])
248
+ if not net.bus.at[b, "in_service"] or np.isnan(v) or vn < self.crit.monitor_min_kv:
249
+ continue
250
+ if "hc_monitor" in net.bus.columns and not bool(net.bus.at[b, "hc_monitor"]):
251
+ continue
252
+ lbl = self._lbl(b)
253
+ vmin, vmax = self.crit.voltage_limits(lbl, vn, contingency)
254
+ if v < vmin - 1e-9:
255
+ key = ("vlow", b)
256
+ emap[key] = vmin - v
257
+ viols.append((key, Violation("voltage_low", f"Bus {lbl}", cond, float(v), vmin, (vmin - v) / vmin, f"bus:{lbl}", oid)))
258
+ elif v > vmax + 1e-9:
259
+ key = ("vhigh", b)
260
+ emap[key] = v - vmax
261
+ viols.append((key, Violation("voltage_high", f"Bus {lbl}", cond, float(v), vmax, (v - vmax) / vmax, f"bus:{lbl}", oid)))
262
+
263
+ lim = self.crit.thermal_limit_pct(contingency)
264
+ for kind, tbl, res, a, b, pcol in (
265
+ ("line", net.line, net.res_line, "from_bus", "to_bus", "p_from_mw"),
266
+ ("trafo", net.trafo, net.res_trafo, "hv_bus", "lv_bus", "p_hv_mw"),
267
+ ):
268
+ mon = tbl["hc_monitor"].fillna(True).astype(bool) if "hc_monitor" in tbl else None
269
+ rate = tbl["hc_rating_mva"] if "hc_rating_mva" in tbl else None
270
+ for i in tbl.index[tbl.in_service]:
271
+ if mon is not None and not mon.at[i]:
272
+ continue
273
+ load = res.at[i, "loading_percent"]
274
+ if rate is not None and np.isfinite(rate.at[i]) and rate.at[i] > 0:
275
+ load = load * float(tbl.at[i, "sn_mva"]) / float(rate.at[i]) # percent of the PSS/E rating
276
+ if np.isnan(load) or load <= lim + 1e-9:
277
+ continue
278
+ key = (kind, i)
279
+ emap[key] = load - lim
280
+ name = ("Line " if kind == "line" else "Transformer ") + f"{self._lbl(tbl.at[i, a])}-{self._lbl(tbl.at[i, b])} (#{i})"
281
+ src = tbl.at[i, a] if res.at[i, pcol] >= 0 else tbl.at[i, b]
282
+ viols.append((key, Violation(f"thermal_{kind}", name, cond, float(load), lim, (load - lim) / lim,
283
+ f"{kind}:{i}", oid, self._lbl(src))))
284
+ return viols, emap
285
+
286
+ def _new_violations(self, net, state) -> list:
287
+ """Violations that are new, or pre-existing ones worsened beyond tolerance."""
288
+ viols, emap = self._violation_map(net, state)
289
+ ref = self.reference[state]
290
+ out = []
291
+ for key, v in viols:
292
+ if key in self._ignore:
293
+ continue
294
+ exc = emap[key]
295
+ if key not in ref:
296
+ out.append(v)
297
+ continue
298
+ if self.crit.preexisting_policy == "ignore":
299
+ continue
300
+ tol = self.crit.preexisting_tol_pu if key[0] in ("vlow", "vhigh") else self.crit.preexisting_tol_pct
301
+ if exc - ref[key] > tol:
302
+ v.element += " (pre-existing, worsened)"
303
+ out.append(v)
304
+ return out
305
+
306
+ # --------------------------------------------------------------- plant
307
+ def _prepare(self, bus_idx):
308
+ work = copy.deepcopy(self.base)
309
+ use_gen = self.reactive == "voltage" and bus_idx not in self.vc_buses
310
+ plant_gen = None
311
+ if use_gen:
312
+ plant_gen = pp.create_gen(work, bus_idx, p_mw=0.0, vm_pu=float(self.ref_vm.at[bus_idx]),
313
+ name="HostCap plant", in_service=False)
314
+ plant_sgen = pp.create_sgen(work, bus_idx, p_mw=0.0, q_mvar=0.0, name="HostCap plant (PQ)")
315
+ return work, plant_gen, plant_sgen
316
+
317
+ def _dispatch(self, work, p_mw: float) -> None:
318
+ if self.redispatch == "proportional":
319
+ work.gen.loc[self.gen_idx, "p_mw"] = proportional_reduction(self.p0, self.pmin, p_mw)
320
+
321
+ def _solve_with_plant(self, work, plant_gen, plant_sgen, p_mw: float):
322
+ """Solve load flow with the plant at p_mw. Returns (converged, q_mvar, q_limited)."""
323
+ qmax = self.q_per_mw * p_mw
324
+ if plant_gen is not None:
325
+ work.gen.at[plant_gen, "in_service"] = True
326
+ work.gen.at[plant_gen, "p_mw"] = p_mw
327
+ work.sgen.at[plant_sgen, "in_service"] = False
328
+ if not self._runpp(work):
329
+ return False, None, False
330
+ q = float(work.res_gen.at[plant_gen, "q_mvar"])
331
+ if abs(q) <= qmax + 1e-6:
332
+ return True, q, False
333
+ # Reactive limit reached: hold Q at the limit, bus voltage floats
334
+ work.gen.at[plant_gen, "in_service"] = False
335
+ q = math.copysign(qmax, q)
336
+ else:
337
+ q = 0.0
338
+ work.sgen.at[plant_sgen, "in_service"] = True
339
+ work.sgen.at[plant_sgen, "p_mw"] = p_mw
340
+ work.sgen.at[plant_sgen, "q_mvar"] = q
341
+ ok = self._runpp(work)
342
+ return ok, (q if ok else None), plant_gen is not None
343
+
344
+ def _check(self, work, pg, ps, p_mw: float, full: bool):
345
+ """Evaluate base case and all N-1 outages at p_mw.
346
+
347
+ Returns (feasible, violations, plant_q, q_limited) where plant_q is
348
+ from the base case. With full=False, stops at the first failure.
349
+ """
350
+ self._dispatch(work, p_mw)
351
+ found, q_base, qlim_base = [], None, False
352
+ # Base case always first (it supplies the plant Q for the report).
353
+ # Outages are checked most-recently-failed first: this only changes
354
+ # speed, not the result, because every outage is checked before a
355
+ # step is declared feasible.
356
+ for state in [BASE] + self._order:
357
+ self._apply_outage(work, state, out=True)
358
+ ok, q, qlim = self._solve_with_plant(work, pg, ps, p_mw)
359
+ if ok:
360
+ new = self._new_violations(work, state)
361
+ else:
362
+ oid = "" if state == BASE else f"{state[0]}:{state[1]}"
363
+ new = [Violation("non_convergence", "Load flow", self.state_name(state), math.nan, math.nan, math.inf, "", oid)]
364
+ if state == BASE:
365
+ q_base, qlim_base = q, qlim
366
+ self._apply_outage(work, state, out=False)
367
+ if new:
368
+ found.extend(new)
369
+ if state != BASE and self._order[0] != state:
370
+ self._order.remove(state)
371
+ self._order.insert(0, state)
372
+ if not full:
373
+ break
374
+ return (not found), found, q_base, qlim_base
375
+
376
+ # --------------------------------------------------------------- search
377
+ def screen_bus(self, label: str) -> BusResult:
378
+ t0 = time.time()
379
+ bus_idx = label_to_index(self.base, label)
380
+ work, pg, ps = self._prepare(bus_idx)
381
+ res = BusResult(bus=str(label), capability_mw=0.0, status="")
382
+ if self.reactive == "voltage" and pg is None:
383
+ res.warnings.append("Bus voltage is already controlled by an existing unit; plant modeled at unity power factor")
384
+
385
+ hi_cap = min(self.pmax, self.headroom)
386
+ ok_top, _, q_top, ql_top = self._check(work, pg, ps, hi_cap, full=False)
387
+ if ok_top:
388
+ res.capability_mw = hi_cap
389
+ res.plant_q_mvar, res.plant_q_limited = q_top, ql_top
390
+ if self.headroom < self.pmax:
391
+ res.status = "Limited by redispatch headroom (no network limit found)"
392
+ else:
393
+ res.status = f"No limit found up to the search maximum ({self.pmax:g} MW)"
394
+ res.runtime_s = time.time() - t0
395
+ return res
396
+
397
+ lo, hi = 0.0, hi_cap
398
+ while hi - lo > self.tol:
399
+ mid = 0.5 * (lo + hi)
400
+ if self._check(work, pg, ps, mid, full=False)[0]:
401
+ lo = mid
402
+ else:
403
+ hi = mid
404
+
405
+ # Bisection assumes violations only grow with output. Spot-check below.
406
+ probes = [f * lo for f in (0.25, 0.5, 0.75) if f * lo > self.tol]
407
+ bad = [p for p in probes if not self._check(work, pg, ps, p, full=False)[0]]
408
+ if bad:
409
+ res.warnings.append("Non-monotonic result: a violation appears at a lower output; rescanned from 0 MW")
410
+ step = max(10 * self.tol, hi_cap / 50.0)
411
+ p_ok, p_bad = 0.0, None
412
+ p = step
413
+ while p <= hi_cap + 1e-9:
414
+ if self._check(work, pg, ps, p, full=False)[0]:
415
+ p_ok = p
416
+ else:
417
+ p_bad = p
418
+ break
419
+ p += step
420
+ lo, hi = p_ok, (p_bad if p_bad is not None else hi_cap)
421
+ while hi - lo > self.tol:
422
+ mid = 0.5 * (lo + hi)
423
+ if self._check(work, pg, ps, mid, full=False)[0]:
424
+ lo = mid
425
+ else:
426
+ hi = mid
427
+
428
+ res.capability_mw = math.floor(lo / self.tol) * self.tol
429
+ _, q_res, ql_res = self._check(work, pg, ps, res.capability_mw, full=False)[1:]
430
+ res.plant_q_mvar, res.plant_q_limited = q_res, ql_res
431
+ _, viols, _, _ = self._check(work, pg, ps, hi, full=True)
432
+ viols.sort(key=lambda v: v.severity, reverse=True)
433
+ res.violations_at_limit = viols
434
+ res.binding = viols[0] if viols else None
435
+ res.status = "Network limit found"
436
+ if res.capability_mw <= 0:
437
+ res.status = "No capability: a limit is violated at the smallest step"
438
+ if self.next_limit and res.binding is not None:
439
+ self._next_limit(work, pg, ps, res, hi_cap)
440
+ res.runtime_s = time.time() - t0
441
+ return res
442
+
443
+ def _next_limit(self, work, pg, ps, res, hi_cap) -> None:
444
+ """Capability if the binding branch were upgraded (its limit ignored).
445
+
446
+ Only branch (line or transformer) overloads can be upgraded this way.
447
+ Voltage limits call for reactive support instead, so none is computed.
448
+ """
449
+ b = res.binding
450
+ if not b.kind.startswith("thermal"):
451
+ res.next_note = ("Voltage-limited: reactive support or voltage control is needed, not a branch upgrade"
452
+ if b.kind.startswith("voltage") else "Not available for this limit type")
453
+ return
454
+ kind, idx = b.element_id.split(":")
455
+ self._ignore = {(kind, int(idx))}
456
+ try:
457
+ lo = res.capability_mw
458
+ ok, _, _, _ = self._check(work, pg, ps, hi_cap, full=False)
459
+ if ok:
460
+ res.next_mw = hi_cap
461
+ res.next_note = ("No further limit up to the redispatch headroom" if self.headroom < self.pmax
462
+ else f"No further limit up to the search maximum ({self.pmax:g} MW)")
463
+ return
464
+ hi = hi_cap
465
+ while hi - lo > self.tol:
466
+ mid = 0.5 * (lo + hi)
467
+ if self._check(work, pg, ps, mid, full=False)[0]:
468
+ lo = mid
469
+ else:
470
+ hi = mid
471
+ res.next_mw = math.floor(lo / self.tol) * self.tol
472
+ viols = self._check(work, pg, ps, hi, full=True)[1]
473
+ viols.sort(key=lambda v: v.severity, reverse=True)
474
+ res.next_binding = viols[0] if viols else None
475
+ finally:
476
+ self._ignore = set()
477
+
478
+ def screen(self, labels=None, progress=None, workers: int = 1) -> list:
479
+ """Screen several buses. Results are returned in the order requested."""
480
+ if labels is None:
481
+ labels = candidate_labels(self.base)
482
+ labels = [str(x) for x in labels]
483
+ for lbl in labels: # fail early on a bad label
484
+ label_to_index(self.base, lbl)
485
+ if workers <= 1:
486
+ out = []
487
+ for n, lbl in enumerate(labels, 1):
488
+ out.append(self.screen_bus(lbl))
489
+ if progress:
490
+ progress(n, len(labels), out[-1])
491
+ return out
492
+
493
+ from concurrent.futures import ProcessPoolExecutor, as_completed
494
+ results = {}
495
+ with ProcessPoolExecutor(max_workers=workers, initializer=_init_worker, initargs=(self,)) as pool:
496
+ futs = {pool.submit(_worker_screen, lbl): lbl for lbl in labels}
497
+ for n, fut in enumerate(as_completed(futs), 1):
498
+ r = fut.result()
499
+ results[r.bus] = r
500
+ if progress:
501
+ progress(n, len(labels), r)
502
+ return [results[lbl] for lbl in labels]
503
+
504
+
505
+ _WORKER = None
506
+
507
+
508
+ def _init_worker(screener):
509
+ global _WORKER
510
+ _WORKER = screener
511
+
512
+
513
+ def _worker_screen(label):
514
+ return _WORKER.screen_bus(label)
@@ -0,0 +1,5 @@
1
+ """Error raised for problems the user can fix (bad input, unsupported model data)."""
2
+
3
+
4
+ class InputError(ValueError):
5
+ """A clear, user-facing error about the input files or settings."""