pf-tool 0.2.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.
exporter.py ADDED
@@ -0,0 +1,886 @@
1
+ """Export a solved power flow to an Excel workbook, one sheet per component.
2
+
3
+ Usage::
4
+
5
+ solver = NewtonRaphsonPowerFlow("tests/data/CASO01-FLOW.dat")
6
+ solver.solve()
7
+ ExportSolution(solver, output_path="results/CASO01.xlsx")
8
+
9
+ Sheets: Summary, Buses, Generators, Loads, Lines, Transformers, LTC, PST,
10
+ HVDC, SVC, CSC and Shunts. Powers are in MW/Mvar, voltages in pu (and kV
11
+ where the DGBT base is known), angles in degrees.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import math
17
+ from collections.abc import Iterable, Sequence
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ import numpy as np
23
+ from openpyxl import Workbook
24
+ from openpyxl.styles import Font
25
+
26
+ from models.branch import Branch
27
+ from models.bus import BusType
28
+ from models.case import PowerFlowCase
29
+ from models.network_reduction import ZERO_IMPEDANCE_THRESHOLD_PU, ReducedCase
30
+ from models.transformer import TapControl, branch_stamps
31
+ from utils.network import build_ybus, calculate_power
32
+
33
+ _FLOW_HEADERS = (
34
+ "MW:From-To",
35
+ "Mvar:From-To",
36
+ "Power Factor:From-To",
37
+ "F:Capac/Inductive",
38
+ "MW:To-From",
39
+ "Mvar:To-From",
40
+ "Power Factor:To-From",
41
+ "T:Capac/Inductive",
42
+ )
43
+
44
+ SHEET_HEADERS: dict[str, tuple[str, ...]] = {
45
+ "Summary": ("Field", "Value"),
46
+ "Buses": (
47
+ "Bus",
48
+ "Name",
49
+ "Type",
50
+ "Area",
51
+ "InServ",
52
+ "Vm(pu)",
53
+ "Vm(kV)",
54
+ "Va(deg)",
55
+ "Pg(MW)",
56
+ "Qg(MVAr)",
57
+ "Pl(MW)",
58
+ "Ql(MVAr)",
59
+ "Qshunt(MVAr)",
60
+ "Qsvc(MVAr)",
61
+ "Phvdc(MW)",
62
+ "Qhvdc(MVAr)",
63
+ "Vmin",
64
+ "Vmax",
65
+ "Violation",
66
+ "RepresentativeBus",
67
+ "Collapsed",
68
+ ),
69
+ "Generators": (
70
+ "Bus",
71
+ "Name",
72
+ "Type",
73
+ "Pg(MW)",
74
+ "Qg(MVAr)",
75
+ "Qmin(MVAr)",
76
+ "Qmax(MVAr)",
77
+ "Pmax(MW)",
78
+ "Reserve(MW)",
79
+ "Vm(pu)",
80
+ "Va(deg)",
81
+ "QLimit",
82
+ ),
83
+ "Loads": ("Bus", "Name", "Pl(MW)", "Ql(MVAr)", "Vm(pu)", "Source"),
84
+ "Lines": (
85
+ "Line",
86
+ "From",
87
+ "To",
88
+ "Circuit",
89
+ "R(pu)",
90
+ "X(pu)",
91
+ "B(pu)",
92
+ "Tap",
93
+ "Shift(deg)",
94
+ "Rate(MVA)",
95
+ *_FLOW_HEADERS,
96
+ "Loading%",
97
+ "P_loss(MW)",
98
+ "Q_loss(MVAr)",
99
+ "Violation",
100
+ "Collapsed",
101
+ ),
102
+ "Transformers": (
103
+ "Device",
104
+ "From",
105
+ "To",
106
+ "Circuit",
107
+ "R(pu)",
108
+ "X(pu)",
109
+ "Tap",
110
+ "Shift(deg)",
111
+ "Rate(MVA)",
112
+ *_FLOW_HEADERS,
113
+ "Loading%",
114
+ "P_loss(MW)",
115
+ "Q_loss(MVAr)",
116
+ "Violation",
117
+ "Collapsed",
118
+ ),
119
+ "LTC": (
120
+ "Device",
121
+ "From",
122
+ "To",
123
+ "Circuit",
124
+ "CtrlBus",
125
+ "Tap",
126
+ "TapMin",
127
+ "TapMax",
128
+ "Vset(pu)",
129
+ "Vctrl(pu)",
130
+ "State",
131
+ *_FLOW_HEADERS,
132
+ ),
133
+ "PST": (
134
+ "Device",
135
+ "From",
136
+ "To",
137
+ "Circuit",
138
+ "CtrlBus",
139
+ "Shift(deg)",
140
+ "ShiftMin(deg)",
141
+ "ShiftMax(deg)",
142
+ "Ptarget(MW)",
143
+ "Pmeasured(MW)",
144
+ "State",
145
+ *_FLOW_HEADERS,
146
+ ),
147
+ "HVDC": (
148
+ "Link",
149
+ "Bus#",
150
+ "BusName",
151
+ "Volt(pu)",
152
+ "Type",
153
+ "Control",
154
+ "Porder(MW)",
155
+ "P(MW)",
156
+ "Q(MVAr)",
157
+ "Loss(MW)",
158
+ "Vdc(kV)",
159
+ "Idc(kA)",
160
+ "Idc(A)",
161
+ "Angle(deg)",
162
+ "Mu(deg)",
163
+ "Phi(deg)",
164
+ "Tap",
165
+ "Status",
166
+ ),
167
+ "SVC": (
168
+ "Device",
169
+ "Bus",
170
+ "Name",
171
+ "CtrlBus",
172
+ "Mode",
173
+ "Slope(%)",
174
+ "Vref(pu)",
175
+ "Vctrl(pu)",
176
+ "Vterm(pu)",
177
+ "Qsvc(MVAr)",
178
+ "Qmin(MVAr)",
179
+ "Qmax(MVAr)",
180
+ "Residual",
181
+ "State",
182
+ ),
183
+ "CSC": (
184
+ "Device",
185
+ "From",
186
+ "To",
187
+ "Circuit",
188
+ "Mode",
189
+ "X(pu)",
190
+ "Xmin(pu)",
191
+ "Xmax(pu)",
192
+ "Bypass",
193
+ *_FLOW_HEADERS,
194
+ "Loading%",
195
+ "Status",
196
+ ),
197
+ "Shunts": (
198
+ "Device",
199
+ "Bus",
200
+ "Kind",
201
+ "Line",
202
+ "Control",
203
+ "CtrlBus",
204
+ "Vmin(pu)",
205
+ "Vmax(pu)",
206
+ "Vctrl(pu)",
207
+ "Units",
208
+ "Qnom(MVAr)",
209
+ "Q(MVAr)",
210
+ "Qmin(MVAr)",
211
+ "Qmax(MVAr)",
212
+ "State",
213
+ ),
214
+ }
215
+
216
+ SheetRows = tuple[Sequence[str], Iterable[Sequence[object]]]
217
+
218
+
219
+ class ExportSolution:
220
+ """Export the solved components of a power-flow solver to a workbook.
221
+
222
+ ``solver`` is a :class:`NewtonRaphsonPowerFlow` or
223
+ :class:`OptimizationPowerFlow` on which ``solve()`` has been called.
224
+ """
225
+
226
+ def __init__(
227
+ self,
228
+ solver: Any,
229
+ output_path: str | Path,
230
+ *,
231
+ format: str = "excel",
232
+ export: bool = True,
233
+ ) -> None:
234
+ if format.strip().lower() not in {"excel", "xlsx"}:
235
+ raise ValueError(f"Unsupported solution export format: {format!r}")
236
+ if getattr(solver, "result", None) is None or getattr(solver, "reduction", None) is None:
237
+ raise ValueError("Call solve() on the solver before exporting its solution")
238
+ self.solver = solver
239
+ self.format = "excel"
240
+ self.output_path = Path(output_path)
241
+ self.sheets = _SolutionTables(solver).sheets(self.output_path)
242
+ if export:
243
+ self.output_path.parent.mkdir(parents=True, exist_ok=True)
244
+ _write_excel(self.sheets, self.output_path)
245
+
246
+
247
+ @dataclass(slots=True)
248
+ class _Flow:
249
+ from_power: complex
250
+ to_power: complex
251
+ collapsed: bool
252
+
253
+
254
+ class _SolutionTables:
255
+ """Derive component results from the solved original-network case."""
256
+
257
+ def __init__(self, solver: Any) -> None:
258
+ self.solver = solver
259
+ self.result = solver.result
260
+ self.case: PowerFlowCase = solver.case
261
+ self.reduction: ReducedCase = solver.reduction
262
+ self.base = self.case.base_mva
263
+ self.voltage = np.asarray(self.result.voltage, dtype=np.complex128)
264
+ self.magnitude = np.abs(self.voltage)
265
+ self.angle_deg = np.degrees(np.angle(self.voltage))
266
+ self.index = self.case.bus_index
267
+ self.node = self.reduction.original_to_reduced
268
+ self._bus_quantities()
269
+ self._generation()
270
+ self._flows()
271
+ self._control_states()
272
+
273
+ # ------------------------------------------------------------------ buses
274
+ def _bus_quantities(self) -> None:
275
+ count = len(self.case.buses)
276
+ self.rect_p = np.zeros(count)
277
+ self.rect_q = np.zeros(count)
278
+ self.inv_p = np.zeros(count)
279
+ self.inv_q = np.zeros(count)
280
+ for link in self.case.hvdc_links:
281
+ rectifier = self.index[link.rectifier_bus]
282
+ inverter = self.index[link.inverter_bus]
283
+ self.rect_p[rectifier] += link.rectifier_active_mw
284
+ self.rect_q[rectifier] += link.rectifier_reactive_mvar
285
+ self.inv_p[inverter] += link.inverter_active_mw
286
+ self.inv_q[inverter] += link.inverter_reactive_mvar
287
+ self.svc_q = np.zeros(count)
288
+ for svc in self.case.svcs:
289
+ self.svc_q[self.index[svc.bus]] += svc.q_mvar
290
+ buses = self.case.buses
291
+ self.load_p = np.array([bus.p_load_mw for bus in buses]) - self.rect_p
292
+ self.load_q = np.array([bus.q_load_mvar for bus in buses]) - self.rect_q - self.inv_q
293
+ self.hvdc_p = self.inv_p - self.rect_p
294
+ self.hvdc_q = -(self.rect_q + self.inv_q)
295
+ self.scheduled_p = np.array([bus.p_generation_mw for bus in buses]) - self.inv_p
296
+ self.scheduled_q = np.array([bus.q_generation_mvar for bus in buses]) - self.svc_q
297
+ self.shunt_b = np.array([bus.shunt_susceptance_pu for bus in buses])
298
+ self.shunt_q = self.shunt_b * self.magnitude**2 * self.base
299
+ self.ybus = build_ybus(self.case)
300
+ self.injection = calculate_power(self.ybus, self.voltage) * self.base
301
+ self.node_type = [
302
+ self.case.buses[self.reduction.representatives[n]].bus_type
303
+ for n in range(len(self.reduction.members))
304
+ ]
305
+
306
+ def _generation(self) -> None:
307
+ """Machine outputs: node balance split among the node's generators."""
308
+ self.gen_p = self.scheduled_p.copy()
309
+ self.gen_q = self.scheduled_q.copy()
310
+ self.is_generator = np.array(
311
+ [
312
+ bus.dbar_type in (1, 2)
313
+ or abs(self.scheduled_p[i]) > 1e-9
314
+ or abs(self.scheduled_q[i]) > 1e-9
315
+ for i, bus in enumerate(self.case.buses)
316
+ ]
317
+ )
318
+ for node, members in enumerate(self.reduction.members):
319
+ members = list(members)
320
+ node_p = sum(self.injection[m].real - self.hvdc_p[m] + self.load_p[m] for m in members)
321
+ node_q = sum(
322
+ self.injection[m].imag - self.svc_q[m] - self.hvdc_q[m] + self.load_q[m]
323
+ for m in members
324
+ )
325
+ kind = self.node_type[node]
326
+ if kind == BusType.SLACK:
327
+ slack = [m for m in members if self.case.buses[m].dbar_type == 2] or [
328
+ self.reduction.representatives[node]
329
+ ]
330
+ fixed = sum(self.scheduled_p[m] for m in members if m not in slack)
331
+ for m in slack:
332
+ self.gen_p[m] = (node_p - fixed) / len(slack)
333
+ if kind in (BusType.PV, BusType.SLACK):
334
+ regulating = [m for m in members if self.case.buses[m].dbar_type in (1, 2)] or [
335
+ self.reduction.representatives[node]
336
+ ]
337
+ fixed = sum(self.scheduled_q[m] for m in members if m not in regulating)
338
+ ranges = np.array(
339
+ [
340
+ max(
341
+ (self.case.buses[m].q_max_mvar or 0.0)
342
+ - (self.case.buses[m].q_min_mvar or 0.0),
343
+ 0.0,
344
+ )
345
+ for m in regulating
346
+ ]
347
+ )
348
+ weights = (
349
+ ranges / ranges.sum()
350
+ if ranges.sum() > 0
351
+ else np.full(len(regulating), 1.0 / len(regulating))
352
+ )
353
+ for m, weight in zip(regulating, weights):
354
+ self.gen_q[m] = (node_q - fixed) * weight
355
+ self.local = (
356
+ (self.gen_p + self.hvdc_p - self.load_p)
357
+ + 1j * (self.gen_q + self.svc_q + self.hvdc_q - self.load_q)
358
+ ) / self.base
359
+
360
+ # --------------------------------------------------------------- branches
361
+ def _branch_flow(self, branch: Branch) -> tuple[complex, complex]:
362
+ impedance = complex(branch.resistance_pu, branch.reactance_pu)
363
+ yff, yft, ytf, ytt = branch_stamps(
364
+ 1.0 / impedance, branch.charging_pu, branch.tap_ratio, branch.phase_shift_radians
365
+ )
366
+ vf = self.voltage[self.index[branch.from_bus]]
367
+ vt = self.voltage[self.index[branch.to_bus]]
368
+ return vf * np.conj(yff * vf + yft * vt), vt * np.conj(ytf * vf + ytt * vt)
369
+
370
+ def _flows(self) -> None:
371
+ """Branch flows; contracted links are solved from KCL in their group."""
372
+ self.flows: list[_Flow] = []
373
+ collapsed: dict[int, list[int]] = {}
374
+ charging: dict[int, tuple[complex, complex]] = {}
375
+ outflow = np.zeros(len(self.case.buses), dtype=np.complex128)
376
+ for position, branch in enumerate(self.case.branches):
377
+ start = self.index[branch.from_bus]
378
+ end = self.index[branch.to_bus]
379
+ if (
380
+ self.node[start] == self.node[end]
381
+ and math.hypot(branch.resistance_pu, branch.reactance_pu)
382
+ <= ZERO_IMPEDANCE_THRESHOLD_PU
383
+ ):
384
+ # The series part of a contracted link is lossless and solved
385
+ # from KCL; its line charging still draws -j b/2 |V|^2 per end.
386
+ half = 0.5 * branch.charging_pu
387
+ charge_from = -1j * half * self.magnitude[start] ** 2 / branch.tap_ratio**2
388
+ charge_to = -1j * half * self.magnitude[end] ** 2
389
+ charging[position] = (charge_from, charge_to)
390
+ outflow[start] += charge_from
391
+ outflow[end] += charge_to
392
+ collapsed.setdefault(int(self.node[start]), []).append(position)
393
+ self.flows.append(_Flow(charge_from, charge_to, True))
394
+ continue
395
+ from_power, to_power = self._branch_flow(branch)
396
+ outflow[start] += from_power
397
+ outflow[end] += to_power
398
+ self.flows.append(_Flow(from_power, to_power, False))
399
+
400
+ shunt_power = -1j * self.shunt_b * self.magnitude**2
401
+ demand = self.local - shunt_power - outflow
402
+ for node, positions in collapsed.items():
403
+ members = list(self.reduction.members[node])
404
+ row = {bus: k for k, bus in enumerate(members)}
405
+ incidence = np.zeros((len(members), len(positions)))
406
+ for column, position in enumerate(positions):
407
+ branch = self.case.branches[position]
408
+ incidence[row[self.index[branch.from_bus]], column] += 1.0
409
+ incidence[row[self.index[branch.to_bus]], column] -= 1.0
410
+ values, *_ = np.linalg.lstsq(
411
+ incidence.astype(np.complex128), demand[members], rcond=None
412
+ )
413
+ for column, position in enumerate(positions):
414
+ series = complex(values[column])
415
+ charge_from, charge_to = charging[position]
416
+ self.flows[position] = _Flow(series + charge_from, -series + charge_to, True)
417
+
418
+ # --------------------------------------------------------------- controls
419
+ def _control_states(self) -> None:
420
+ self.ltc_state: dict[int, tuple[str, TapControl]] = {}
421
+ self.pst_state: dict[int, tuple[str, TapControl]] = {}
422
+ for control in self.reduction.case.tap_controls:
423
+ if not control.enabled:
424
+ state = "Disabled"
425
+ elif control.conflicting:
426
+ state = "Conflict"
427
+ elif control.limited:
428
+ state = "AtLimit"
429
+ elif control.regulating:
430
+ state = "Regulating"
431
+ else:
432
+ state = "InBand"
433
+ target = self.pst_state if control.mode == "P" else self.ltc_state
434
+ for branch in control.branches:
435
+ target[branch.original_index] = (state, control)
436
+
437
+ # ----------------------------------------------------------------- sheets
438
+ def sheets(self, output_path: Path) -> dict[str, SheetRows]:
439
+ rows = {
440
+ "Summary": self._summary(output_path),
441
+ "Buses": self._buses(),
442
+ "Generators": self._generators(),
443
+ "Loads": self._loads(),
444
+ "Lines": self._branch_rows(lambda b: _branch_kind(b) == "line", True),
445
+ "Transformers": self._branch_rows(lambda b: _branch_kind(b) == "transformer", False),
446
+ "LTC": self._ltc(),
447
+ "PST": self._pst(),
448
+ "HVDC": self._hvdc(),
449
+ "SVC": self._svc(),
450
+ "CSC": self._csc(),
451
+ "Shunts": self._shunts(),
452
+ }
453
+ return {name: (SHEET_HEADERS[name], list(rows[name])) for name in SHEET_HEADERS}
454
+
455
+ def _summary(self, output_path: Path) -> list[tuple[str, object]]:
456
+ solver = self.solver
457
+ method = type(solver).__name__
458
+ if method == "NewtonRaphsonPowerFlow":
459
+ method = "Newton-Raphson"
460
+ elif method == "OptimizationPowerFlow":
461
+ start = "warm start" if getattr(solver, "warm_start", False) else "cold start"
462
+ method = f"Optimization (Pyomo/Ipopt, {start})"
463
+ kinds = [_branch_kind(branch) for branch in self.case.branches]
464
+ losses = sum(flow.from_power + flow.to_power for flow in self.flows)
465
+ overloads = sum(
466
+ 1
467
+ for branch, flow in zip(self.case.branches, self.flows)
468
+ if _loading(branch, flow, self.base) > 100.0
469
+ )
470
+ upper = sum(
471
+ 1
472
+ for i, bus in enumerate(self.case.buses)
473
+ if self.magnitude[i] > bus.voltage_max_pu + 1e-6
474
+ )
475
+ lower = sum(
476
+ 1
477
+ for i, bus in enumerate(self.case.buses)
478
+ if self.magnitude[i] < bus.voltage_min_pu - 1e-6
479
+ )
480
+ return [
481
+ ("Case", str(getattr(solver, "data_file", ""))),
482
+ ("Workbook", str(output_path)),
483
+ ("Method", method),
484
+ ("Converged", bool(self.result.converged)),
485
+ ("Iterations", int(self.result.iterations)),
486
+ ("Max Mismatch (pu)", float(self.result.max_mismatch)),
487
+ ("Failure Reason", self.result.failure_reason or ""),
488
+ ("Base MVA", self.base),
489
+ ("Buses", len(self.case.buses)),
490
+ ("Buses After Reduction", len(self.reduction.members)),
491
+ ("Generators", int(self.is_generator.sum())),
492
+ (
493
+ "Loads",
494
+ int(sum(1 for p, q in zip(self.load_p, self.load_q) if abs(p) + abs(q) > 1e-9)),
495
+ ),
496
+ ("Branches", len(self.case.branches)),
497
+ ("Lines", kinds.count("line")),
498
+ ("Transformers", kinds.count("transformer")),
499
+ ("CSC", kinds.count("csc")),
500
+ ("LTC", len(self.ltc_state)),
501
+ ("PST", len(self.pst_state)),
502
+ ("HVDC Links", len(self.case.hvdc_links)),
503
+ ("SVC", len(self.case.svcs)),
504
+ ("Shunts", len(self.case.switched_shunts)),
505
+ ("Total Generation (MW)", float(self.gen_p.sum())),
506
+ ("Total Generation (MVAr)", float(self.gen_q.sum())),
507
+ ("Total Load (MW)", float(self.load_p.sum())),
508
+ ("Total Load (MVAr)", float(self.load_q.sum())),
509
+ ("AC Losses (MW)", float(losses.real * self.base)),
510
+ ("AC Losses (MVAr)", float(losses.imag * self.base)),
511
+ ("Voltage Upper Violations", upper),
512
+ ("Voltage Lower Violations", lower),
513
+ ("Line Flow Overloads", overloads),
514
+ ]
515
+
516
+ def _buses(self) -> Iterable[Sequence[object]]:
517
+ representative = {
518
+ m: self.case.buses[self.reduction.representatives[node]].number
519
+ for node, members in enumerate(self.reduction.members)
520
+ for m in members
521
+ }
522
+ for i, bus in enumerate(self.case.buses):
523
+ node = int(self.node[i])
524
+ yield (
525
+ bus.number,
526
+ bus.name,
527
+ bus.bus_type.value,
528
+ bus.area,
529
+ True,
530
+ self.magnitude[i],
531
+ self.magnitude[i] * bus.base_kv if bus.base_kv else None,
532
+ self.angle_deg[i],
533
+ self.gen_p[i],
534
+ self.gen_q[i],
535
+ self.load_p[i],
536
+ self.load_q[i],
537
+ self.shunt_q[i],
538
+ self.svc_q[i],
539
+ self.hvdc_p[i],
540
+ self.hvdc_q[i],
541
+ bus.voltage_min_pu,
542
+ bus.voltage_max_pu,
543
+ _voltage_violation(self.magnitude[i], bus.voltage_min_pu, bus.voltage_max_pu),
544
+ representative[i],
545
+ len(self.reduction.members[node]) > 1,
546
+ )
547
+
548
+ def _generators(self) -> Iterable[Sequence[object]]:
549
+ for i, bus in enumerate(self.case.buses):
550
+ if not self.is_generator[i]:
551
+ continue
552
+ q_limit = ""
553
+ if bus.dbar_type == 1 and bus.bus_type == BusType.PQ:
554
+ low, high = bus.q_min_mvar or 0.0, bus.q_max_mvar or 0.0
555
+ if abs(high - low) <= 1e-9:
556
+ q_limit = "ZeroRange"
557
+ elif self.gen_q[i] >= high - 0.5:
558
+ q_limit = "Qmax"
559
+ elif self.gen_q[i] <= low + 0.5:
560
+ q_limit = "Qmin"
561
+ reserve = bus.p_max_mw - self.gen_p[i] if bus.p_max_mw else None
562
+ yield (
563
+ bus.number,
564
+ bus.name,
565
+ bus.bus_type.value,
566
+ self.gen_p[i],
567
+ self.gen_q[i],
568
+ bus.q_min_mvar,
569
+ bus.q_max_mvar,
570
+ bus.p_max_mw,
571
+ reserve,
572
+ self.magnitude[i],
573
+ self.angle_deg[i],
574
+ q_limit,
575
+ )
576
+
577
+ def _loads(self) -> Iterable[Sequence[object]]:
578
+ for i, bus in enumerate(self.case.buses):
579
+ if abs(self.load_p[i]) + abs(self.load_q[i]) > 1e-9:
580
+ yield (
581
+ bus.number,
582
+ bus.name,
583
+ self.load_p[i],
584
+ self.load_q[i],
585
+ self.magnitude[i],
586
+ "DBAR",
587
+ )
588
+
589
+ def _flow_columns(self, flow: _Flow) -> tuple[object, ...]:
590
+ from_power = flow.from_power * self.base
591
+ to_power = flow.to_power * self.base
592
+ return (
593
+ from_power.real,
594
+ from_power.imag,
595
+ _power_factor(from_power),
596
+ _reactive_type(from_power),
597
+ to_power.real,
598
+ to_power.imag,
599
+ _power_factor(to_power),
600
+ _reactive_type(to_power),
601
+ )
602
+
603
+ def _branch_rows(self, select: Any, with_charging: bool) -> Iterable[Sequence[object]]:
604
+ for position, (branch, flow) in enumerate(zip(self.case.branches, self.flows), start=1):
605
+ if not select(branch):
606
+ continue
607
+ loss = (flow.from_power + flow.to_power) * self.base
608
+ loading = _loading(branch, flow, self.base)
609
+ electrical = (branch.resistance_pu, branch.reactance_pu)
610
+ if with_charging:
611
+ electrical += (branch.charging_pu,)
612
+ yield (
613
+ position,
614
+ branch.from_bus,
615
+ branch.to_bus,
616
+ branch.circuit,
617
+ *electrical,
618
+ branch.tap_ratio,
619
+ -math.degrees(branch.phase_shift_radians),
620
+ branch.rating_mva,
621
+ *self._flow_columns(flow),
622
+ loading,
623
+ loss.real,
624
+ loss.imag,
625
+ loading > 100.0,
626
+ flow.collapsed,
627
+ )
628
+
629
+ def _ltc(self) -> Iterable[Sequence[object]]:
630
+ voltage_set = {bus.number: bus.voltage_pu for bus in self.case.buses}
631
+ for position, (branch, flow) in enumerate(zip(self.case.branches, self.flows), start=1):
632
+ if not branch.tap_max > branch.tap_min > 0.0:
633
+ continue
634
+ state, _ = self.ltc_state.get(position - 1, ("Fixed", None))
635
+ if flow.collapsed:
636
+ state = "Contracted"
637
+ controlled = branch.controlled_bus
638
+ actual = self.magnitude[self.index[controlled]] if controlled in self.index else None
639
+ yield (
640
+ position,
641
+ branch.from_bus,
642
+ branch.to_bus,
643
+ branch.circuit,
644
+ controlled,
645
+ branch.tap_ratio,
646
+ branch.tap_min,
647
+ branch.tap_max,
648
+ voltage_set.get(controlled),
649
+ actual,
650
+ state,
651
+ *self._flow_columns(flow),
652
+ )
653
+
654
+ def _pst(self) -> Iterable[Sequence[object]]:
655
+ originals = {
656
+ branch.original_index: control
657
+ for control in self.case.tap_controls
658
+ if control.mode == "P"
659
+ for branch in control.branches
660
+ }
661
+ for index, control in sorted(originals.items()):
662
+ branch = self.case.branches[index]
663
+ flow = self.flows[index]
664
+ state, _ = self.pst_state.get(index, ("Contracted", None))
665
+ base_phase = control.branches[0].base_phase
666
+ shift_min = -math.degrees(base_phase + control.shift_max)
667
+ shift_max = -math.degrees(base_phase + control.shift_min)
668
+ measured = flow.from_power if control.measure_from else flow.to_power
669
+ yield (
670
+ index + 1,
671
+ branch.from_bus,
672
+ branch.to_bus,
673
+ branch.circuit,
674
+ control.controlled_bus,
675
+ -math.degrees(branch.phase_shift_radians),
676
+ shift_min,
677
+ shift_max,
678
+ control.setpoint * self.base,
679
+ measured.real * self.base,
680
+ state,
681
+ *self._flow_columns(flow),
682
+ )
683
+
684
+ def _hvdc(self) -> Iterable[Sequence[object]]:
685
+ buses = self.case.buses
686
+ for link in self.case.hvdc_links:
687
+ active = link.p_dc_mw > 1e-12
688
+ current = link.current_ka if active else 0.0
689
+ loss = current**2 * link.r_dc_ohm
690
+ for kind in ("Rectifier", "Inverter"):
691
+ rectifier = kind == "Rectifier"
692
+ number = link.rectifier_bus if rectifier else link.inverter_bus
693
+ bus = buses[self.index[number]]
694
+ slack = link.rectifier_slack if rectifier else link.inverter_slack
695
+ angle = link.alpha_deg if rectifier else link.gamma_deg
696
+ mu = link.mu_rectifier_deg if rectifier else link.mu_inverter_deg
697
+ power = link.rectifier_active_mw if rectifier else link.inverter_active_mw
698
+ reactive = (
699
+ link.rectifier_reactive_mvar if rectifier else link.inverter_reactive_mvar
700
+ )
701
+ phi = math.degrees(math.atan2(reactive, power)) if active and power else None
702
+ yield (
703
+ link.name,
704
+ number,
705
+ bus.name,
706
+ self.magnitude[self.index[number]],
707
+ kind,
708
+ "Slack" if slack else "Power",
709
+ link.p_dc_mw,
710
+ power,
711
+ reactive,
712
+ loss,
713
+ link.vdc_rectifier_kv if rectifier else link.vdc_inverter_kv,
714
+ current,
715
+ current * 1000.0,
716
+ angle,
717
+ mu,
718
+ phi,
719
+ link.tap_rectifier if rectifier else link.tap_inverter,
720
+ "InSvc" if active else "Idle (Porder = 0)",
721
+ )
722
+
723
+ def _svc(self) -> Iterable[Sequence[object]]:
724
+ for position, svc in enumerate(self.case.svcs, start=1):
725
+ device = self.index[svc.bus]
726
+ control = self.index[svc.controlled_bus]
727
+ terminal = self.magnitude[device]
728
+ controlled = self.magnitude[control]
729
+ q = svc.q_mvar / self.base
730
+ low = svc.q_min_mvar * terminal**2
731
+ high = svc.q_max_mvar * terminal**2
732
+ active = self.node_type[int(self.node[device])] == BusType.PQ
733
+ droop = q / terminal if svc.mode == "I" else q
734
+ residual = controlled - svc.reference_voltage + svc.slope * droop
735
+ if not active:
736
+ state = "Inactive"
737
+ elif svc.q_mvar <= low + 1e-3:
738
+ state = "Qmin"
739
+ elif svc.q_mvar >= high - 1e-3:
740
+ state = "Qmax"
741
+ else:
742
+ state = "Free"
743
+ yield (
744
+ position,
745
+ svc.bus,
746
+ self.case.buses[device].name,
747
+ svc.controlled_bus,
748
+ svc.mode,
749
+ svc.slope * 100.0,
750
+ svc.reference_voltage,
751
+ controlled,
752
+ terminal,
753
+ svc.q_mvar,
754
+ low,
755
+ high,
756
+ residual if state == "Free" else None,
757
+ state,
758
+ )
759
+
760
+ def _csc(self) -> Iterable[Sequence[object]]:
761
+ for position, (branch, flow) in enumerate(zip(self.case.branches, self.flows), start=1):
762
+ if not branch.is_csc:
763
+ continue
764
+ yield (
765
+ position,
766
+ branch.from_bus,
767
+ branch.to_bus,
768
+ branch.circuit,
769
+ branch.csc_mode,
770
+ 0.0 if branch.bypassed else branch.reactance_pu,
771
+ branch.csc_x_min_pu,
772
+ branch.csc_x_max_pu,
773
+ branch.bypassed,
774
+ *self._flow_columns(flow),
775
+ _loading(branch, flow, self.base),
776
+ "Bypassed" if branch.bypassed else "InSvc",
777
+ )
778
+
779
+ def _shunts(self) -> Iterable[Sequence[object]]:
780
+ for position, shunt in enumerate(self.case.switched_shunts, start=1):
781
+ bus_voltage = self.magnitude[self.index[shunt.bus]]
782
+ controlled = (
783
+ self.magnitude[self.index[shunt.controlled_bus]]
784
+ if shunt.controlled_bus in self.index
785
+ else None
786
+ )
787
+ units = ", ".join(
788
+ f"{stage.in_service}/{stage.units} x {stage.unit_mvar:g}" for stage in shunt.stages
789
+ )
790
+ if shunt.fixed:
791
+ state = "Fixed"
792
+ elif shunt.frozen:
793
+ state = "Frozen"
794
+ elif controlled is None:
795
+ state = "NoControl"
796
+ elif controlled < shunt.minimum_voltage_pu:
797
+ state = "BelowBand"
798
+ elif controlled > shunt.maximum_voltage_pu:
799
+ state = "AboveBand"
800
+ else:
801
+ state = "InBand"
802
+ yield (
803
+ position,
804
+ shunt.bus,
805
+ "Line" if shunt.line else "Bus",
806
+ shunt.line,
807
+ "Fixed" if shunt.fixed else "Controlled",
808
+ shunt.controlled_bus,
809
+ shunt.minimum_voltage_pu,
810
+ shunt.maximum_voltage_pu,
811
+ controlled,
812
+ units,
813
+ shunt.current_q_mvar,
814
+ shunt.current_q_mvar * bus_voltage**2,
815
+ shunt.minimum_q_mvar,
816
+ shunt.maximum_q_mvar,
817
+ state,
818
+ )
819
+
820
+
821
+ def _branch_kind(branch: Branch) -> str:
822
+ if branch.is_csc:
823
+ return "csc"
824
+ if branch.is_transformer or branch.tap_max > branch.tap_min > 0.0:
825
+ return "transformer"
826
+ return "line"
827
+
828
+
829
+ def _loading(branch: Branch, flow: _Flow, base_mva: float) -> float:
830
+ if branch.rating_mva <= 0.0:
831
+ return 0.0
832
+ return 100.0 * max(abs(flow.from_power), abs(flow.to_power)) * base_mva / branch.rating_mva
833
+
834
+
835
+ def _power_factor(power: complex) -> float:
836
+ magnitude = abs(power)
837
+ return abs(power.real) / magnitude if magnitude > 1e-9 else 1.0
838
+
839
+
840
+ def _reactive_type(power: complex) -> str:
841
+ return "Inductive" if power.imag >= 0.0 else "Capacitive"
842
+
843
+
844
+ def _voltage_violation(value: float, minimum: float, maximum: float) -> str:
845
+ if value > maximum + 1e-6:
846
+ return "Vmax"
847
+ if value < minimum - 1e-6:
848
+ return "Vmin"
849
+ return ""
850
+
851
+
852
+ def _write_excel(sheets: dict[str, SheetRows], output_path: Path) -> None:
853
+ workbook = Workbook()
854
+ workbook.remove(workbook.active)
855
+ bold = Font(bold=True)
856
+ for name, (headers, rows) in sheets.items():
857
+ sheet = workbook.create_sheet(name)
858
+ sheet.freeze_panes = "A2"
859
+ sheet.append(list(headers))
860
+ for cell in sheet[1]:
861
+ cell.font = bold
862
+ for row in rows:
863
+ sheet.append([_excel_value(value) for value in row])
864
+ for row in sheet.iter_rows(min_row=2):
865
+ for cell in row:
866
+ if isinstance(cell.value, float):
867
+ cell.number_format = "0.0000"
868
+ for column, header in enumerate(headers, start=1):
869
+ letter = sheet.cell(row=1, column=column).column_letter
870
+ sheet.column_dimensions[letter].width = max(len(str(header)) + 3, 11)
871
+ workbook.save(output_path)
872
+
873
+
874
+ def _excel_value(value: object) -> object:
875
+ if value is None:
876
+ return ""
877
+ if isinstance(value, (np.floating,)):
878
+ return float(value)
879
+ if isinstance(value, (np.integer,)):
880
+ return int(value)
881
+ if isinstance(value, (np.bool_,)):
882
+ return bool(value)
883
+ return value
884
+
885
+
886
+ __all__ = ["SHEET_HEADERS", "ExportSolution"]