Skip to main content

powerio_matrix/
mcopf.rs

1//! Solver-independent preparation for multiconductor rectangular IVR OPF.
2//!
3//! All currents are retained, including at exact zero series impedance. No
4//! admittance inversion, neutral reduction, or switch contraction takes place.
5//! Canonical instance inputs use SI; coefficients use explicitly chosen bases.
6//! This is an exact AC IVR preparation profile, not a network validity test or a
7//! solver. Rejection of an ideal cycle, initial point, or angle window indicates
8//! a profile limitation, not electrical infeasibility. See the MC IVR guide for
9//! supported equipment and the downstream expression/derivative boundary.
10use crate::diagnostics::{Diagnostic, codes};
11use powerio_core::Error;
12use powerio_dist::{Configuration, DistLoadVoltageModel, MulticonductorNetwork};
13use powerio_prob::{ConstraintSelection, McAcOpfInstance, ObjectiveTerm};
14use serde::{Deserialize, Serialize};
15use std::collections::{BTreeMap, BTreeSet};
16
17mod inverter;
18mod starts;
19mod transformer;
20pub use transformer::{
21    McOpfComplexRow, McOpfTransformer, McOpfTransformerCoil, McOpfTransformerPort,
22};
23
24type Positions = BTreeMap<(String, String), usize>;
25type CoilPairs = Vec<(usize, Option<usize>)>;
26type Result<T> = std::result::Result<T, Error>;
27
28/// What preparation does with a voltage-bounded load law.
29///
30/// The IVR power-law terms cannot represent the low-voltage transitions,
31/// high-voltage continuation and dropout of a bounded ZIP law, so the default
32/// refuses it. Ordinary OpenDSS loads with `model=1` or `model=5` read as such
33/// a law.
34#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36#[non_exhaustive]
37pub enum BoundedLoadLawPolicy {
38    /// Refuse the load with an unsupported-equipment error.
39    #[default]
40    Refuse,
41    /// Replace the law by its nominal (middle-band) law and record one
42    /// [`McOpfLoadLawProjection`] per load. This is an approximation of the
43    /// source model, chosen by the caller.
44    ProjectToNominal,
45}
46
47/// Explicit system bases; no physical bound is inferred from these values.
48#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
49#[non_exhaustive]
50pub struct McAcOpfAssemblyOptions {
51    /// Voltage base in volts, shared by terminal and coil voltages.
52    pub voltage_base_v: f64,
53    /// Power base in VA per coil; I_base = S_base / V_base.
54    pub power_base_va: f64,
55    /// Handling of voltage-bounded load laws. Refused unless the caller opts
56    /// in to the nominal projection.
57    #[serde(default)]
58    pub bounded_load_laws: BoundedLoadLawPolicy,
59}
60impl McAcOpfAssemblyOptions {
61    /// Choose voltage (V) and power (VA) bases. The preparation builder validates
62    /// that both and their derived current/impedance bases are finite and positive.
63    #[must_use]
64    pub const fn new(voltage_base_v: f64, power_base_va: f64) -> Self {
65        Self {
66            voltage_base_v,
67            power_base_va,
68            bounded_load_laws: BoundedLoadLawPolicy::Refuse,
69        }
70    }
71    /// Choose how voltage-bounded load laws are handled.
72    #[must_use]
73    pub const fn with_bounded_load_laws(mut self, policy: BoundedLoadLawPolicy) -> Self {
74        self.bounded_load_laws = policy;
75        self
76    }
77}
78impl Default for McAcOpfAssemblyOptions {
79    fn default() -> Self {
80        Self {
81            voltage_base_v: 230.0,
82            power_base_va: 1000.0,
83            bounded_load_laws: BoundedLoadLawPolicy::Refuse,
84        }
85    }
86}
87/// A source terminal in canonical bus/terminal order.
88#[derive(Clone, Debug, Serialize, Deserialize)]
89#[non_exhaustive]
90pub struct McOpfTerminal {
91    /// Canonical bus name.
92    pub bus: String,
93    /// Canonical terminal label within the bus.
94    pub terminal: String,
95    /// True for an explicit physical ground.
96    pub grounded: bool,
97    /// Prescribed rectangular `[real, imaginary]` voltage in per unit, when fixed.
98    pub fixed: Option<[f64; 2]>,
99    /// Rectangular per-unit voltage seed; not an additional physical reference.
100    pub start: [f64; 2],
101}
102/// A magnitude bound on a difference of terminal voltages, in per unit.
103#[derive(Clone, Debug, Serialize, Deserialize)]
104#[non_exhaustive]
105pub struct McOpfVoltageLimit {
106    /// Stable diagnostic identity derived from the source limit.
107    pub identity: String,
108    /// Index into preparation.terminals for ordinary voltage differences.
109    pub positive: usize,
110    /// Return terminal index, or physical ground when absent.
111    pub negative: Option<usize>,
112    /// Optional per-unit magnitude lower bound, not squared.
113    pub lower: Option<f64>,
114    /// Optional per-unit magnitude upper bound, not squared.
115    pub upper: Option<f64>,
116    /// For sequence limits: (terminal index, complex coefficient) of the measured voltage; empty for ordinary differences.
117    pub combination: Vec<(usize, [f64; 2])>,
118}
119/// Centered angle of `V[first] * conj(V[second])`, in radians.
120#[derive(Clone, Debug, Serialize, Deserialize)]
121#[non_exhaustive]
122pub struct McOpfAngleLimit {
123    /// Source limit identity.
124    pub identity: String,
125    /// First index into preparation.terminals.
126    pub first: usize,
127    /// Second index into preparation.terminals.
128    pub second: usize,
129    /// Reference rotation in radians subtracted from the measured angle.
130    pub offset: f64,
131    /// Lower bound after reference rotation, radians.
132    pub lower: f64,
133    /// Upper bound after reference rotation, radians.
134    pub upper: f64,
135}
136/// A line or ideal switch, with dense *local* conductor matrices.
137#[derive(Clone, Debug, Serialize, Deserialize)]
138#[non_exhaustive]
139pub struct McOpfBranch {
140    /// Source kind and name (`line:name` or `switch:name`).
141    pub identity: String,
142    /// From-terminal global indices, in local conductor order.
143    pub from: Vec<usize>,
144    /// To-terminal global indices paired with from.
145    pub to: Vec<usize>,
146    /// Local square series resistance matrix divided by Z_base.
147    pub r: Vec<Vec<f64>>,
148    /// Local square series reactance matrix divided by Z_base.
149    pub x: Vec<Vec<f64>>,
150    /// Local square from-end conductance matrix multiplied by Z_base.
151    pub g_from: Vec<Vec<f64>>,
152    /// Local square from-end susceptance matrix multiplied by Z_base.
153    pub b_from: Vec<Vec<f64>>,
154    /// Local square to-end conductance matrix multiplied by Z_base.
155    pub g_to: Vec<Vec<f64>>,
156    /// Local square to-end susceptance matrix multiplied by Z_base.
157    pub b_to: Vec<Vec<f64>>,
158    /// Optional current magnitude cap per conductor, per unit.
159    pub current_max: Vec<Option<f64>>,
160    /// Optional apparent-power cap per conductor, per unit.
161    pub apparent_max: Vec<Option<f64>>,
162    /// Open contacts carry no series current.
163    pub open: bool,
164}
165#[derive(Clone, Debug, Serialize, Deserialize)]
166#[non_exhaustive]
167pub struct McOpfShunt {
168    /// Source shunt or synthesized capacitor/grounding identity.
169    pub identity: String,
170    /// Global terminal indices defining the local matrix axis.
171    pub terminals: Vec<usize>,
172    /// Local square conductance matrix multiplied by Z_base.
173    pub g: Vec<Vec<f64>>,
174    /// Local square susceptance matrix multiplied by Z_base.
175    pub b: Vec<Vec<f64>>,
176}
177#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
178/// Distinguishes demand (positive consumption) from injection device tables.
179#[non_exhaustive]
180pub enum McOpfDeviceKind {
181    Load,
182    Generator,
183    Ibr,
184    Source,
185}
186/// A sum of voltage power laws: coefficient times (|U|/nominal)^exponent.
187/// Coefficients are per-unit power; exponents are dimensionless.
188#[derive(Clone, Debug, Serialize, Deserialize)]
189#[non_exhaustive]
190pub struct McOpfLoadLaw {
191    /// Coil nominal voltage divided by V_base.
192    pub nominal: f64,
193    /// Active then reactive terms; each `[coefficient, exponent]` contributes coefficient * (|U| / nominal)^exponent in per-unit power.
194    pub terms: [Vec<[f64; 2]>; 2],
195}
196impl McOpfLoadLaw {
197    /// A law of active then reactive `[coefficient, exponent]` terms at the
198    /// per unit coil nominal voltage `nominal`.
199    #[must_use]
200    pub fn new(nominal: f64, terms: [Vec<[f64; 2]>; 2]) -> Self {
201        Self { nominal, terms }
202    }
203
204    /// The law's per unit active and reactive power at the per unit voltage
205    /// magnitude `voltage` (on `V_base`), each with its derivative with
206    /// respect to `voltage`: the terms summed by the one power law term
207    /// evaluation ([`powerio_core::electrical::calc_voltage_power_term`]) at
208    /// the ratio `voltage / nominal`.
209    #[must_use]
210    pub fn calc_power(&self, voltage: f64) -> [(f64, f64); 2] {
211        let ratio = voltage / self.nominal;
212        self.terms.each_ref().map(|terms| {
213            let (value, slope) = powerio_core::electrical::calc_voltage_power_terms(terms, ratio);
214            (value, slope / self.nominal)
215        })
216    }
217
218    /// The constant admittance of a law whose every term has exponent two
219    /// (pure constant impedance), per unit: `conj(Σ P + j Σ Q) / nominal²`
220    /// ([`powerio_dist::calc_load_nominal_admittance`]), so
221    /// the coil current is `Y U` at every voltage, zero included. `None`
222    /// when any term has another exponent.
223    #[must_use]
224    #[allow(clippy::float_cmp)] // the impedance exponent is an exact spelling
225    pub fn calc_impedance_admittance(&self) -> Option<num_complex::Complex64> {
226        if !self.terms.iter().flatten().all(|t| t[1] == 2.0) {
227            return None;
228        }
229        let [active, reactive] = self
230            .terms
231            .each_ref()
232            .map(|terms| terms.iter().map(|t| t[0]).sum::<f64>());
233        Some(powerio_dist::calc_load_nominal_admittance(
234            num_complex::Complex64::new(active, reactive),
235            self.nominal,
236        ))
237    }
238}
239
240/// The softplus width of a prepared droop curve as a share of its mean knot
241/// voltage: `epsilon = MC_OPF_DROOP_SMOOTHING · mean(knots)`, so a knot moved
242/// by `dk` widens every corner by `MC_OPF_DROOP_SMOOTHING · dk / n`. The one
243/// smoothing rule: the preparation sets it and the curve's parameter
244/// sensitivities differentiate it.
245pub const MC_OPF_DROOP_SMOOTHING: f64 = 2e-3;
246
247/// Smooth clipped piecewise-linear controller, with SI-derived per-unit knots.
248#[derive(Clone, Debug, Serialize, Deserialize)]
249#[non_exhaustive]
250pub struct McOpfDroop {
251    /// Voltage-difference terminal pairs; None means physical ground. Multiple pairs use averaged magnitudes.
252    pub monitors: Vec<(usize, Option<usize>)>,
253    /// Strictly increasing voltage knots divided by V_base.
254    pub knots: Vec<f64>,
255    /// Control power at each knot, divided by S_base.
256    pub values: Vec<f64>,
257    /// Positive softplus smoothing width in per-unit voltage.
258    pub epsilon: f64,
259}
260/// The value and slope of a smoothed droop curve, and the response of both
261/// to a parameter direction ([`McOpfDroop::calc_parameter_derivative`]).
262#[derive(Clone, Copy, Debug, PartialEq)]
263#[non_exhaustive]
264pub struct McOpfDroopValue {
265    /// The control power, per unit.
266    pub value: f64,
267    /// Its derivative with respect to the monitored voltage, per unit.
268    pub slope: f64,
269}
270
271/// `[softplus(z), sigmoid(z), sigmoid'(z), softplus(z) − z sigmoid(z)]`,
272/// in the entropy form that neither cancels nor overflows when saturated.
273fn smooth_hinge(z: f64) -> [f64; 4] {
274    let e = (-z.abs()).exp();
275    let sigma = if z >= 0.0 {
276        1.0 / (1.0 + e)
277    } else {
278        e / (1.0 + e)
279    };
280    [
281        z.max(0.0) + e.ln_1p(),
282        sigma,
283        e / (1.0 + e).powi(2),
284        e.ln_1p() + z.abs() * e / (1.0 + e),
285    ]
286}
287
288/// One softplus corner of a droop curve: it adds
289/// `coefficient · width · softplus((v − knot) / width)` to the control power
290/// at the monitored voltage `v` ([`McOpfDroopTerms`]).
291#[derive(Clone, Copy, Debug, PartialEq)]
292#[non_exhaustive]
293pub struct McOpfDroopHinge {
294    /// The signed slope change at the knot, per unit power per unit
295    /// voltage: `+sⱼ` at a segment's lower knot, `−sⱼ` at its upper knot.
296    pub coefficient: f64,
297    /// The knot, per unit voltage.
298    pub knot: f64,
299    /// The softplus width `ε`, per unit voltage.
300    pub width: f64,
301}
302
303/// A droop curve as a sum: `constant + Σ hinges`
304/// ([`McOpfDroop::calc_terms`]). A segment of zero slope adds no hinge.
305#[derive(Clone, Debug, PartialEq)]
306#[non_exhaustive]
307pub struct McOpfDroopTerms {
308    /// The control power at the lowest knot and below, per unit.
309    pub constant: f64,
310    /// The corners, two per segment of nonzero slope, lower knot first.
311    pub hinges: Vec<McOpfDroopHinge>,
312}
313
314impl McOpfDroop {
315    /// The curve's terms, the one statement of the smoothed piecewise linear
316    /// curve: [`calc_control`](Self::calc_control) sums them and a symbolic
317    /// model builds its expression from them.
318    #[must_use]
319    #[allow(clippy::float_cmp)] // a flat segment has an exactly zero slope
320    pub fn calc_terms(&self) -> McOpfDroopTerms {
321        let mut hinges = Vec::new();
322        for j in 0..self.knots.len().saturating_sub(1) {
323            let slope = (self.values[j + 1] - self.values[j]) / (self.knots[j + 1] - self.knots[j]);
324            if slope == 0.0 {
325                continue;
326            }
327            for (k, sign) in [(j, 1.0), (j + 1, -1.0)] {
328                hinges.push(McOpfDroopHinge {
329                    coefficient: sign * slope,
330                    knot: self.knots[k],
331                    width: self.epsilon,
332                });
333            }
334        }
335        McOpfDroopTerms {
336            constant: self.values[0],
337            hinges,
338        }
339    }
340
341    /// The mean monitored voltage magnitude: `|V_p − V_n|` over the monitor
342    /// pairs (`V_n = 0` for ground), averaged, from per unit terminal
343    /// voltages indexed like the preparation's terminals.
344    #[must_use]
345    pub fn calc_monitored_voltage(&self, voltage: &[num_complex::Complex64]) -> f64 {
346        let total: f64 = self
347            .monitors
348            .iter()
349            .map(|&(p, n)| {
350                (voltage[p] - n.map_or(num_complex::Complex64::new(0.0, 0.0), |n| voltage[n]))
351                    .norm()
352            })
353            .sum();
354        total / self.monitors.len() as f64
355    }
356
357    /// The curve's control power at the monitored voltage `voltage` and its
358    /// slope: the piecewise linear curve through `(knots, values)` with each
359    /// corner smoothed by a softplus of width `epsilon`,
360    ///
361    /// ```text
362    /// c(v) = values₀ + Σⱼ sⱼ ε (softplus((v − kⱼ)/ε) − softplus((v − kⱼ₊₁)/ε)),
363    /// sⱼ = (valuesⱼ₊₁ − valuesⱼ) / (kⱼ₊₁ − kⱼ).
364    /// ```
365    ///
366    /// The one droop evaluation: the OPF residual, its validation and its
367    /// parameter sensitivities read it.
368    #[must_use]
369    pub fn calc_control(&self, voltage: f64) -> McOpfDroopValue {
370        let terms = self.calc_terms();
371        let mut value = terms.constant;
372        let mut slope = 0.0;
373        for hinge in &terms.hinges {
374            let [softplus, sigmoid, ..] = smooth_hinge((voltage - hinge.knot) / hinge.width);
375            value += hinge.coefficient * hinge.width * softplus;
376            slope += hinge.coefficient * sigmoid;
377        }
378        McOpfDroopValue { value, slope }
379    }
380
381    /// The directional derivative of [`calc_control`](Self::calc_control)
382    /// along a change `(d_knots, d_values, d_epsilon)` of the curve's
383    /// parameters, at a fixed monitored voltage: the change of the control
384    /// power (`value`) and of its voltage slope (`slope`).
385    ///
386    /// # Panics
387    /// When `d_knots` or `d_values` is shorter than the curve.
388    #[must_use]
389    pub fn calc_parameter_derivative(
390        &self,
391        voltage: f64,
392        d_knots: &[f64],
393        d_values: &[f64],
394        d_epsilon: f64,
395    ) -> McOpfDroopValue {
396        let (knots, values, epsilon) = (&self.knots, &self.values, self.epsilon);
397        let mut value = d_values[0];
398        let mut slope = 0.0;
399        for j in 0..knots.len().saturating_sub(1) {
400            let width = knots[j + 1] - knots[j];
401            let s = (values[j + 1] - values[j]) / width;
402            let ds = (d_values[j + 1] - d_values[j] - s * (d_knots[j + 1] - d_knots[j])) / width;
403            let z = [
404                (voltage - knots[j]) / epsilon,
405                (voltage - knots[j + 1]) / epsilon,
406            ];
407            let [a, b] = z.map(smooth_hinge);
408            let hinge = epsilon * (a[0] - b[0]);
409            let dh = d_epsilon * (a[3] - b[3]) - d_knots[j] * a[1] + d_knots[j + 1] * b[1];
410            let dz = [
411                (-d_knots[j] - z[0] * d_epsilon) / epsilon,
412                (-d_knots[j + 1] - z[1] * d_epsilon) / epsilon,
413            ];
414            value += ds * hinge + s * dh;
415            slope += ds * (a[1] - b[1]) + s * (a[2] * dz[0] - b[2] * dz[1]);
416        }
417        McOpfDroopValue { value, slope }
418    }
419}
420
421/// One two-terminal coil; a missing negative terminal means physical ground.
422#[derive(Clone, Debug, Serialize, Deserialize)]
423#[non_exhaustive]
424pub struct McOpfCoil {
425    /// Positive global terminal index; current points from positive to negative.
426    pub positive: usize,
427    /// Negative global terminal index, or physical ground.
428    pub negative: Option<usize>,
429    /// Fixed `[P,Q]` per-unit power: consumption for loads, injection otherwise.
430    pub prescribed: Option<[f64; 2]>,
431    /// Voltage-dependent demand, normalized to its physical coil voltage.
432    pub load_law: Option<McOpfLoadLaw>,
433    /// Legacy signed Q/P ratio. Prefer `power_factor_coefficients` for assembly.
434    /// None also means the ratio is not representable, when bounded coefficients
435    /// are present. Do not use this field to detect whether PF control is active.
436    pub reactive_slope: Option<f64>,
437    /// Bounded `[a,b]` for fixed PF: `a * P + b * Q = 0`, where
438    /// `a = sqrt((1 - |pf|) * (1 + |pf|))` and `b = -pf`. PF follows OpenDSS
439    /// and BMOPF by sign: `pf > 0` gives `Q/P = +tan(acos |pf|)`, Q with
440    /// the same sign as P; `pf < 0` the opposite sign.
441    /// Coefficients retain tiny nonzero PF without trigonometric cancellation.
442    #[serde(default, skip_serializing_if = "Option::is_none")]
443    pub power_factor_coefficients: Option<[f64; 2]>,
444    /// Reactive injection as a smoothed function of monitored voltage.
445    pub volt_var: Option<McOpfDroop>,
446    /// Active injection as a smoothed function of monitored voltage.
447    pub volt_watt: Option<McOpfDroop>,
448    /// Optional active injection lower bound in per unit.
449    pub p_min: Option<f64>,
450    /// Optional active injection upper bound in per unit.
451    pub p_max: Option<f64>,
452    /// Optional reactive injection lower bound in per unit.
453    pub q_min: Option<f64>,
454    /// Optional reactive injection upper bound in per unit.
455    pub q_max: Option<f64>,
456    /// Optional coil current magnitude cap in per unit.
457    pub current_max: Option<f64>,
458    /// Optional coil apparent-power cap in per unit.
459    pub apparent_max: Option<f64>,
460    /// Currency/hour per per-unit active injection (same sign for sources).
461    pub cost: f64,
462}
463#[derive(Clone, Debug, Serialize, Deserialize)]
464#[non_exhaustive]
465pub struct McOpfDevice {
466    /// Original device name.
467    pub identity: String,
468    /// Source table and injection/consumption convention.
469    pub kind: McOpfDeviceKind,
470    /// Zero-based row in the canonical table identified by kind.
471    pub source_row: usize,
472    /// Original terminal-map order, including neutral, for result projection.
473    pub terminals: Vec<usize>,
474    /// Connection-defined coil order, distinct from terminal order.
475    pub coils: Vec<McOpfCoil>,
476    /// Optional magnitude cap on the return current sum, per unit.
477    pub neutral_current_max: Option<f64>,
478    /// Optional bounds on the sum of coil active injections, per unit, including isolated DC-link balance.
479    pub net_active_bounds: Option<[f64; 2]>,
480}
481/// Canonical IVR coefficients. These contain no optimizer or expression types.
482#[derive(Clone, Debug, Serialize, Deserialize)]
483#[non_exhaustive]
484pub struct McAcOpfPreparation {
485    /// Explicit physical bases used throughout this record.
486    pub bases: McAcOpfAssemblyOptions,
487    /// Global voltage axis in canonical bus and terminal storage order.
488    pub terminals: Vec<McOpfTerminal>,
489    /// Selected magnitude and sequence bounds.
490    pub voltage_limits: Vec<McOpfVoltageLimit>,
491    /// Selected supported angle windows.
492    pub angle_limits: Vec<McOpfAngleLimit>,
493    /// Conductor-current branch descriptors.
494    pub branches: Vec<McOpfBranch>,
495    /// Terminal admittance descriptors.
496    pub shunts: Vec<McOpfShunt>,
497    /// Loads, generators, IBRs and ideal-source injection descriptors.
498    pub devices: Vec<McOpfDevice>,
499    /// Winding-current descriptors with their own local current axes.
500    pub transformers: Vec<McOpfTransformer>,
501    /// Loads whose bounded law was projected to its nominal law under
502    /// [`BoundedLoadLawPolicy::ProjectToNominal`]; empty by default.
503    #[serde(default)]
504    pub load_law_projections: Vec<McOpfLoadLawProjection>,
505}
506/// One load whose voltage-bounded law was replaced by its nominal law.
507#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
508#[non_exhaustive]
509pub struct McOpfLoadLawProjection {
510    /// Source load name.
511    pub load: String,
512    /// Tag of the source law (`bounded_zip`, `bounded_exponential` or `bounded_constant_power`).
513    pub source_model: String,
514    /// Tag of the nominal law the preparation used.
515    pub projected_model: String,
516}
517impl McAcOpfPreparation {
518    /// One warning per load whose bounded law was projected to its nominal law.
519    #[must_use]
520    pub fn diagnostics(&self) -> Vec<Diagnostic> {
521        self.load_law_projections
522            .iter()
523            .map(|projection| {
524                Diagnostic::of(
525                    &codes::BUILD_MC_OPF_LOAD_LAW_PROJECTED,
526                    format!(
527                        "load `{}`: {} law projected to its nominal {} law; low-voltage transitions, high-voltage continuation and dropout are not modeled",
528                        projection.load, projection.source_model, projection.projected_model
529                    ),
530                )
531            })
532            .collect()
533    }
534}
535fn invalid(owner: &str, message: impl std::fmt::Display) -> Error {
536    Error::new(&codes::BUILD_MC_OPF_INVALID, format!("{owner}: {message}"))
537}
538fn unsupported(owner: &str, message: impl std::fmt::Display) -> Error {
539    Error::new(
540        &codes::BUILD_MULTI_PHYSICS_UNSUPPORTED,
541        format!("{owner}: {message}"),
542    )
543}
544fn extras(owner: &str, data: &BTreeMap<String, serde_json::Value>, allowed: &[&str]) -> Result<()> {
545    for key in data.keys() {
546        if !allowed.contains(&key.as_str())
547            && !["meta", "provenance", "description"].contains(&key.as_str())
548        {
549            return Err(unsupported(owner, format!("uninterpreted field `{key}`")));
550        }
551    }
552    Ok(())
553}
554fn finite(owner: &str, values: &[f64]) -> Result<()> {
555    if values.iter().any(|x| !x.is_finite()) {
556        return Err(invalid(owner, "nonfinite coefficient"));
557    }
558    Ok(())
559}
560fn vector(owner: &str, values: &[f64], n: usize) -> Result<()> {
561    if values.len() != n {
562        return Err(invalid(
563            owner,
564            format!("expected {n} entries, got {}", values.len()),
565        ));
566    }
567    finite(owner, values)
568}
569fn matrix(owner: &str, values: &[Vec<f64>], n: usize, scale: f64) -> Result<Vec<Vec<f64>>> {
570    if values.len() != n {
571        return Err(invalid(
572            owner,
573            "matrix row count disagrees with conductor map",
574        ));
575    }
576    values
577        .iter()
578        .map(|row| {
579            vector(owner, row, n)?;
580            let scaled: Vec<_> = row.iter().map(|v| v * scale).collect();
581            finite(owner, &scaled)?;
582            Ok(scaled)
583        })
584        .collect()
585}
586fn caps(owner: &str, values: Option<&Vec<f64>>, n: usize, base: f64) -> Result<Vec<Option<f64>>> {
587    let Some(v) = values else {
588        return Ok(vec![None; n]);
589    };
590    if v.len() != n {
591        return Err(invalid(
592            owner,
593            "limit count disagrees with physical channels",
594        ));
595    }
596    v.iter()
597        .map(|&x| {
598            if x.is_nan() || x < 0.0 {
599                return Err(invalid(owner, "magnitude cap must be nonnegative"));
600            }
601            if x == f64::INFINITY {
602                return Ok(None);
603            }
604            let y = x / base;
605            if !y.is_finite()
606                || (x > 0.0 && (y * y == 0.0 || !(1.0 / (y * y)).is_finite()))
607                || !(y * y).is_finite()
608            {
609                return Err(invalid(
610                    owner,
611                    "magnitude cap cannot be represented on the selected base",
612                ));
613            }
614            Ok(Some(y))
615        })
616        .collect()
617}
618fn bounds(owner: &str, values: Option<&Vec<f64>>, n: usize, base: f64) -> Result<Vec<Option<f64>>> {
619    let Some(v) = values else {
620        return Ok(vec![None; n]);
621    };
622    vector(owner, v, n)?;
623    v.iter()
624        .map(|&x| {
625            let y = x / base;
626            finite(owner, &[y])?;
627            Ok(Some(y))
628        })
629        .collect()
630}
631fn selection(selection: &ConstraintSelection, known: &[String], family: &str) -> Result<()> {
632    match selection {
633        ConstraintSelection::All | ConstraintSelection::None => Ok(()),
634        ConstraintSelection::Only(ids) => {
635            for id in ids {
636                if !known.contains(id) {
637                    return Err(invalid(family, format!("unknown selected identity `{id}`")));
638                }
639            }
640            Ok(())
641        }
642        _ => Err(unsupported(family, "unknown constraint selection")),
643    }
644}
645fn unique(family: &str, names: impl Iterator<Item = String>) -> Result<()> {
646    let mut seen = BTreeSet::new();
647    for name in names {
648        if name.is_empty() || !seen.insert(name.clone()) {
649            return Err(invalid(
650                family,
651                format!("empty or duplicate identity `{name}`"),
652            ));
653        }
654    }
655    Ok(())
656}
657/// Prepare the AC multiconductor IVR profile without creating solver expressions.
658///
659/// Supports coupled lines, shunts, capacitors, ideal switches/sources, WYE and
660/// DELTA loads/generators, voltage-dependent loads, winding-current transformer
661/// descriptors (including supported continuous taps), and supported IBR controls.
662/// SI instance values become coefficients on the explicitly selected bases.
663/// No impedance inverse or neutral reduction is performed.
664///
665/// Voltage selections use bus names; conductor selections use `line:name`,
666/// `switch:name`, and `transformer:name`; capability selections use generator
667/// names and `ibr:name`. Deselection removes bounds, never device physics.
668///
669/// Initial points, unreferenced islands, floating source neutrals, ideal conductor
670/// cycles/paths between fixed references, and angle windows outside (-pi/2,pi/2)
671/// are unsupported by this profile. This is not a claim of infeasibility.
672/// The caller owns expression compilation, differentiation and optimization.
673///
674/// # Examples
675///
676/// ```rust
677/// use powerio_matrix::{McAcOpfAssemblyOptions, build_mc_ac_opf_preparation};
678/// use powerio_prob::McAcOpfInstance;
679/// # fn example(instance: &McAcOpfInstance) -> Result<(), powerio_core::Error> {
680/// let bases = McAcOpfAssemblyOptions::new(230.0, 1000.0);
681/// let prepared = build_mc_ac_opf_preparation(instance, &bases)?;
682/// // Global voltage indices refer to prepared.terminals, not bus rows.
683/// # Ok(())
684/// # }
685/// ```
686///
687/// # Errors
688/// Invalid shapes/units/identities, unsupported semantic fields or equipment,
689/// missing source coverage, and structurally dependent ideal conductor cycles.
690pub fn build_mc_ac_opf_preparation(
691    instance: &McAcOpfInstance,
692    bases: &McAcOpfAssemblyOptions,
693) -> Result<McAcOpfPreparation> {
694    let (vb, sb, ib, zb, cost_weight) = validate_profile(instance, bases)?;
695    let net = instance.network();
696    let (mut terminals, positions) = prepare_terminals(net)?;
697    let ctx = Context {
698        net,
699        positions: &positions,
700    };
701    prepare_sources(&ctx, vb, &mut terminals)?;
702    validate_selections(instance)?;
703    let voltage_limits = prepare_voltage_limits(&ctx, instance, vb)?;
704    let mut branches = prepare_branches(&ctx, instance, ib, sb, zb)?;
705    let mut shunts = prepare_shunts(&ctx, zb)?;
706    let mut load_law_projections = Vec::new();
707    let mut devices = prepare_loads(
708        &ctx,
709        sb,
710        vb,
711        bases.bounded_load_laws,
712        &mut load_law_projections,
713    )?;
714    devices.extend(prepare_generators(&ctx, instance, ib, sb, cost_weight)?);
715    devices.extend(inverter::prepare(&ctx, instance, ib, sb, vb, cost_weight)?);
716    devices.extend(prepare_source_devices(&ctx, &terminals, sb, cost_weight)?);
717    let mut transformers =
718        transformer::prepare(&ctx, bases, &mut branches, &mut shunts, &terminals)?;
719    for transformer in &mut transformers {
720        if !instance
721            .constraints()
722            .conductor_limits
723            .selects(&format!("transformer:{}", transformer.identity))
724        {
725            for port in &mut transformer.ports {
726                port.current_max = None;
727                port.apparent_max = None;
728            }
729        }
730    }
731    check_ideal_topology(&branches, &terminals)?;
732    if transformers.is_empty() {
733        check_topology(&branches, &mut terminals)?;
734    } else {
735        starts::initialize(&branches, &transformers, &mut terminals)?;
736    }
737    Ok(McAcOpfPreparation {
738        bases: *bases,
739        terminals,
740        voltage_limits,
741        angle_limits: prepare_angles(&ctx, instance)?,
742        branches,
743        shunts,
744        devices,
745        transformers,
746        load_law_projections,
747    })
748}
749fn validate_profile(
750    instance: &McAcOpfInstance,
751    bases: &McAcOpfAssemblyOptions,
752) -> Result<(f64, f64, f64, f64, f64)> {
753    let net = instance.network();
754    powerio_dist::require_electrical_readiness(net)?;
755    powerio_dist::readiness::require_earth_referenced_sources(net)?;
756    if !bases.voltage_base_v.is_finite()
757        || !bases.power_base_va.is_finite()
758        || bases.voltage_base_v <= 0.0
759        || bases.power_base_va <= 0.0
760    {
761        return Err(invalid(
762            "bases",
763            "voltage and power bases must be finite and positive",
764        ));
765    }
766    let vb = bases.voltage_base_v;
767    let sb = bases.power_base_va;
768    let ib = sb / vb;
769    let zb = vb / ib;
770    if !ib.is_finite() || !zb.is_finite() || ib <= 0.0 || zb <= 0.0 {
771        return Err(invalid("bases", "derived base is unrepresentable"));
772    }
773    extras(
774        "network",
775        net.extras(),
776        &["bmopf_terminal_conventions", "bmopf_meta"],
777    )?;
778    if !net.untyped_objects().is_empty() || !net.commands().is_empty() || !net.options().is_empty()
779    {
780        return Err(unsupported(
781            "network",
782            "untyped electrical objects, commands, and options require explicit canonical semantics",
783        ));
784    }
785    if instance.initial_point().is_some() {
786        return Err(unsupported(
787            "initial_point",
788            "initial-point projection is not implemented by this profile",
789        ));
790    }
791    let mut cost_weight = 0.0;
792    for term in instance.objective().terms() {
793        match term {
794            ObjectiveTerm::ActivePowerDispatchCost => cost_weight += 1.0,
795            _ => {
796                return Err(unsupported(
797                    "objective",
798                    "only active-power dispatch cost is supported",
799                ));
800            }
801        }
802    }
803    for (kind, names) in [
804        (
805            "transformer",
806            net.transformers()
807                .iter()
808                .map(|x| x.name.clone())
809                .collect::<Vec<_>>(),
810        ),
811        (
812            "capacitor",
813            net.capacitors().iter().map(|x| x.name.clone()).collect(),
814        ),
815        ("ibr", net.ibrs().iter().map(|x| x.name.clone()).collect()),
816        (
817            "control_profile",
818            net.control_profiles()
819                .iter()
820                .map(|x| x.name.clone())
821                .collect(),
822        ),
823        (
824            "bus",
825            net.buses().iter().map(|x| x.id.clone()).collect::<Vec<_>>(),
826        ),
827        (
828            "linecode",
829            net.line_codes().iter().map(|x| x.name.clone()).collect(),
830        ),
831        ("line", net.lines().iter().map(|x| x.name.clone()).collect()),
832        (
833            "switch",
834            net.switches().iter().map(|x| x.name.clone()).collect(),
835        ),
836        (
837            "shunt",
838            net.shunts().iter().map(|x| x.name.clone()).collect(),
839        ),
840        ("load", net.loads().iter().map(|x| x.name.clone()).collect()),
841        (
842            "generator",
843            net.generators().iter().map(|x| x.name.clone()).collect(),
844        ),
845        (
846            "source",
847            net.sources().iter().map(|x| x.name.clone()).collect(),
848        ),
849    ] {
850        unique(kind, names.into_iter())?;
851    }
852    Ok((vb, sb, ib, zb, cost_weight))
853}
854fn prepare_terminals(net: &MulticonductorNetwork) -> Result<(Vec<McOpfTerminal>, Positions)> {
855    let mut terminals = Vec::new();
856    let mut positions = BTreeMap::new();
857    let conventions = net.terminal_conventions();
858    for bus in net.buses() {
859        extras(
860            &bus.id,
861            &bus.extras,
862            &["va_diff_min", "va_diff_max", "va_nom"],
863        )?;
864        if bus.terminals.is_empty() {
865            return Err(invalid(&bus.id, "no terminals"));
866        }
867        unique(&bus.id, bus.terminals.iter().cloned())?;
868        for grounded in &bus.grounded {
869            if !bus.terminals.contains(grounded) {
870                return Err(invalid(&bus.id, "unknown grounded terminal"));
871            }
872        }
873        let phases = bus.phase_indices(conventions);
874        for (k, t) in bus.terminals.iter().enumerate() {
875            // Earth by the one terminal classification, or grounded at the bus.
876            let grounded = bus.terminal_role(t, conventions) == powerio_dist::TerminalRole::Earth
877                || bus.grounded.contains(t);
878            let angle = phases.iter().position(|p| *p == k).map_or(0.0, |p| {
879                powerio_dist::sequence::calc_balanced_phase_angle(p, 3)
880            });
881            let start = if grounded || !phases.contains(&k) {
882                [0.0, 0.0]
883            } else {
884                [angle.cos(), angle.sin()]
885            };
886            positions.insert((bus.id.clone(), t.clone()), terminals.len());
887            terminals.push(McOpfTerminal {
888                bus: bus.id.clone(),
889                terminal: t.clone(),
890                grounded,
891                fixed: grounded.then_some([0.0, 0.0]),
892                start,
893            });
894        }
895    }
896    Ok((terminals, positions))
897}
898struct Context<'a> {
899    net: &'a MulticonductorNetwork,
900    positions: &'a Positions,
901}
902impl Context<'_> {
903    fn resolve(&self, owner: &str, bus: &str, map: &[String]) -> Result<Vec<usize>> {
904        unique(owner, map.iter().cloned())?;
905        if map.is_empty() {
906            return Err(invalid(owner, "empty terminal map"));
907        }
908        map.iter()
909            .map(|t| {
910                self.positions
911                    .get(&(bus.to_owned(), t.clone()))
912                    .copied()
913                    .ok_or_else(|| invalid(owner, format!("unknown terminal {bus}:{t}")))
914            })
915            .collect()
916    }
917    /// A DELTA edge joins phases: grounding a phase does not change its role,
918    /// so the declared terminal conventions decide, not voltage or names.
919    fn require_phase_terminals(&self, name: &str, bus_id: &str, tm: &[String]) -> Result<()> {
920        let bus = self
921            .net
922            .bus(bus_id)
923            .ok_or_else(|| invalid(name, "unknown bus"))?;
924        let phases: Vec<&str> = bus
925            .phase_indices(self.net.terminal_conventions())
926            .into_iter()
927            .map(|i| bus.terminals[i].as_str())
928            .collect();
929        if let Some(t) = tm.iter().find(|t| !phases.contains(&t.as_str())) {
930            return Err(invalid(
931                name,
932                format!("delta requires phase terminals; {bus_id}:{t} is neutral or earth"),
933            ));
934        }
935        Ok(())
936    }
937    /// The coils of a WYE, DELTA or single phase connection over global
938    /// terminals: the one connection rule
939    /// ([`powerio_dist::calc_element_connection`]).
940    fn coils(
941        &self,
942        name: &str,
943        bus_id: &str,
944        tm: &[String],
945        config: Configuration,
946    ) -> Result<(Vec<usize>, CoilPairs)> {
947        let ids = self.resolve(name, bus_id, tm)?;
948        match config {
949            Configuration::Delta => {
950                self.require_phase_terminals(name, bus_id, tm)?;
951                if !matches!(ids.len(), 2 | 3) {
952                    return Err(invalid(name, "delta requires two or three terminals"));
953                }
954            }
955            Configuration::SinglePhase if ids.len() != 2 => {
956                return Err(invalid(name, "single-phase requires two terminals"));
957            }
958            Configuration::Wye | Configuration::SinglePhase => {}
959            _ => return Err(unsupported(name, "unknown configuration")),
960        }
961        let coils: CoilPairs =
962            powerio_dist::calc_element_connection(self.net, bus_id, tm, config, None)
963                .map_err(|reason| invalid(name, reason))?
964                .iter()
965                .map(|coil| (ids[coil.from], coil.to.map(|to| ids[to])))
966                .collect();
967        if coils.is_empty() {
968            return Err(invalid(name, "no coils"));
969        }
970        Ok((ids, coils))
971    }
972}
973fn prepare_sources(ctx: &Context<'_>, vb: f64, terminals: &mut [McOpfTerminal]) -> Result<()> {
974    let net = ctx.net;
975    let resolve = |owner: &str, bus: &str, map: &[String]| ctx.resolve(owner, bus, map);
976    let mut source_owners = BTreeSet::new();
977    for src in net.sources() {
978        extras(&src.name, &src.extras, &[])?;
979        let ids = resolve(&src.name, &src.bus, &src.terminal_map)?;
980        let bus = net
981            .bus(&src.bus)
982            .ok_or_else(|| invalid(&src.name, "unknown source bus"))?;
983        let phases = bus.phase_indices(net.terminal_conventions());
984        for (k, terminal) in bus.terminals.iter().enumerate() {
985            if !phases.contains(&k)
986                && !terminals[ctx.positions[&(bus.id.clone(), terminal.clone())]].grounded
987            {
988                return Err(unsupported(
989                    &src.name,
990                    "source-bus neutral must be explicitly grounded, including when omitted from its map",
991                ));
992            }
993        }
994        vector(&src.name, &src.v_magnitude, ids.len())?;
995        vector(&src.name, &src.v_angle, ids.len())?;
996        for (k, &id) in ids.iter().enumerate() {
997            if src.v_magnitude[k] < 0.0 {
998                return Err(invalid(&src.name, "negative source magnitude"));
999            }
1000            let value = [
1001                src.v_magnitude[k] / vb * src.v_angle[k].cos(),
1002                src.v_magnitude[k] / vb * src.v_angle[k].sin(),
1003            ];
1004            finite(&src.name, &value)?;
1005            if terminals[id].grounded {
1006                if value != [0.0, 0.0] {
1007                    return Err(invalid(&src.name, "nonzero grounded reference"));
1008                }
1009            } else if !source_owners.insert(id) {
1010                return Err(unsupported(
1011                    &src.name,
1012                    "colocated ideal sources have ambiguous current allocation",
1013                ));
1014            }
1015            terminals[id].fixed = Some(value);
1016            terminals[id].start = value;
1017        }
1018    }
1019    Ok(())
1020}
1021fn validate_selections(instance: &McAcOpfInstance) -> Result<()> {
1022    let net = instance.network();
1023    let selected = instance.constraints();
1024    selection(
1025        &selected.terminal_voltage_bounds,
1026        &net.buses().iter().map(|b| b.id.clone()).collect::<Vec<_>>(),
1027        "voltage",
1028    )?;
1029    selection(
1030        &selected.generator_capability,
1031        &net.generators()
1032            .iter()
1033            .map(|g| g.name.clone())
1034            .chain(net.ibrs().iter().map(|i| format!("ibr:{}", i.name)))
1035            .collect::<Vec<_>>(),
1036        "generator",
1037    )?;
1038    let branch_ids: Vec<_> = net
1039        .lines()
1040        .iter()
1041        .map(|l| format!("line:{}", l.name))
1042        .chain(net.switches().iter().map(|s| format!("switch:{}", s.name)))
1043        .chain(
1044            net.transformers()
1045                .iter()
1046                .map(|t| format!("transformer:{}", t.name)),
1047        )
1048        .collect();
1049    selection(&selected.conductor_limits, &branch_ids, "conductor")?;
1050    Ok(())
1051}
1052fn prepare_voltage_limits(
1053    ctx: &Context<'_>,
1054    instance: &McAcOpfInstance,
1055    vb: f64,
1056) -> Result<Vec<McOpfVoltageLimit>> {
1057    let net = ctx.net;
1058    let positions = ctx.positions;
1059    let conventions = net.terminal_conventions();
1060    let selected = instance.constraints();
1061    let mut voltage_limits = Vec::new();
1062    for bus in net.buses() {
1063        let phases = bus.phase_indices(conventions);
1064        let nonph: Vec<_> = (0..bus.terminals.len())
1065            .filter(|i| !phases.contains(i))
1066            .collect();
1067        if nonph.len() > 1 {
1068            return Err(unsupported(&bus.id, "multiple nonphase terminals"));
1069        }
1070        let neutral = nonph
1071            .first()
1072            .map(|i| positions[&(bus.id.clone(), bus.terminals[*i].clone())]);
1073        if !selected.terminal_voltage_bounds.selects(&bus.id) {
1074            continue;
1075        }
1076        let pglo = bus
1077            .v_min
1078            .map(|x| vec![x; phases.len()])
1079            .or_else(|| bus.v_min_phase.clone());
1080        let pghi = bus
1081            .v_max
1082            .map(|x| vec![x; phases.len()])
1083            .or_else(|| bus.v_max_phase.clone());
1084        let pids: Vec<_> = phases
1085            .iter()
1086            .map(|i| positions[&(bus.id.clone(), bus.terminals[*i].clone())])
1087            .collect();
1088        prepare_sequences(bus, &pids, neutral, vb, &mut voltage_limits)?;
1089        let mut add_limits = |family: &str, pairs, lo, hi| {
1090            push_voltage_limits(&mut voltage_limits, &bus.id, family, pairs, lo, hi, vb)
1091        };
1092        add_limits(
1093            "ground",
1094            pids.iter().map(|i| (*i, None)).collect(),
1095            pglo.as_ref(),
1096            pghi.as_ref(),
1097        )?;
1098        if (bus.vpn_min.is_some() || bus.vpn_max.is_some() || bus.vn_max.is_some())
1099            && neutral.is_none()
1100        {
1101            return Err(invalid(
1102                &bus.id,
1103                "neutral-referenced limit without a neutral",
1104            ));
1105        }
1106        add_limits(
1107            "neutral",
1108            pids.iter().map(|i| (*i, neutral)).collect(),
1109            bus.vpn_min.as_ref(),
1110            bus.vpn_max.as_ref(),
1111        )?;
1112        let pairs: Vec<_> = pids
1113            .iter()
1114            .enumerate()
1115            .flat_map(|(i, a)| pids.iter().skip(i + 1).map(move |b| (*a, Some(*b))))
1116            .collect();
1117        add_limits("phase", pairs, bus.vpp_min.as_ref(), bus.vpp_max.as_ref())?;
1118        if let (Some(n), Some(cap)) = (neutral, bus.vn_max) {
1119            add_limits("neutral_ground", vec![(n, None)], None, Some(&vec![cap]))?;
1120        }
1121    }
1122    Ok(voltage_limits)
1123}
1124fn prepare_branches(
1125    ctx: &Context<'_>,
1126    instance: &McAcOpfInstance,
1127    ib: f64,
1128    sb: f64,
1129    zb: f64,
1130) -> Result<Vec<McOpfBranch>> {
1131    let net = ctx.net;
1132    let resolve = |owner: &str, bus: &str, map: &[String]| ctx.resolve(owner, bus, map);
1133    let selected = instance.constraints();
1134    let mut branches = Vec::new();
1135    for line in net.lines() {
1136        extras(&line.name, &line.extras, &["va_diff_min", "va_diff_max"])?;
1137        let lc = net
1138            .linecode(&line.linecode)
1139            .ok_or_else(|| invalid(&line.name, "unknown linecode"))?;
1140        extras(&lc.name, &lc.extras, &[])?;
1141        let from = resolve(&line.name, &line.bus_from, &line.terminal_map_from)?;
1142        let to = resolve(&line.name, &line.bus_to, &line.terminal_map_to)?;
1143        let n = from.len();
1144        if to.len() != n || lc.n_conductors != n || !line.length.is_finite() || line.length < 0.0 {
1145            return Err(invalid(&line.name, "invalid conductor count or length"));
1146        }
1147        let identity = format!("line:{}", line.name);
1148        let active = selected.conductor_limits.selects(&identity);
1149        branches.push(McOpfBranch {
1150            identity,
1151            from,
1152            to,
1153            r: matrix(&line.name, &lc.r_series, n, line.length / zb)?,
1154            x: matrix(&line.name, &lc.x_series, n, line.length / zb)?,
1155            g_from: matrix(&line.name, &lc.g_from, n, line.length * zb)?,
1156            b_from: matrix(&line.name, &lc.b_from, n, line.length * zb)?,
1157            g_to: matrix(&line.name, &lc.g_to, n, line.length * zb)?,
1158            b_to: matrix(&line.name, &lc.b_to, n, line.length * zb)?,
1159            current_max: caps(
1160                &line.name,
1161                if active {
1162                    line.i_max.as_ref().or(lc.i_max.as_ref())
1163                } else {
1164                    None
1165                },
1166                n,
1167                ib,
1168            )?,
1169            apparent_max: caps(
1170                &line.name,
1171                if active {
1172                    line.s_max.as_ref().or(lc.s_max.as_ref())
1173                } else {
1174                    None
1175                },
1176                n,
1177                sb,
1178            )?,
1179            open: false,
1180        });
1181    }
1182    for sw in net.switches() {
1183        extras(&sw.name, &sw.extras, &[])?;
1184        let from = resolve(&sw.name, &sw.bus_from, &sw.terminal_map_from)?;
1185        let to = resolve(&sw.name, &sw.bus_to, &sw.terminal_map_to)?;
1186        let n = from.len();
1187        if to.len() != n {
1188            return Err(invalid(&sw.name, "switch map lengths differ"));
1189        }
1190        let z = vec![vec![0.0; n]; n];
1191        let identity = format!("switch:{}", sw.name);
1192        let active = selected.conductor_limits.selects(&identity);
1193        branches.push(McOpfBranch {
1194            identity,
1195            from,
1196            to,
1197            r: z.clone(),
1198            x: z.clone(),
1199            g_from: z.clone(),
1200            b_from: z.clone(),
1201            g_to: z.clone(),
1202            b_to: z,
1203            current_max: caps(
1204                &sw.name,
1205                if active { sw.i_max.as_ref() } else { None },
1206                n,
1207                ib,
1208            )?,
1209            apparent_max: vec![None; n],
1210            open: sw.open,
1211        });
1212    }
1213    Ok(branches)
1214}
1215fn prepare_shunts(ctx: &Context<'_>, zb: f64) -> Result<Vec<McOpfShunt>> {
1216    let net = ctx.net;
1217    let resolve = |owner: &str, bus: &str, map: &[String]| ctx.resolve(owner, bus, map);
1218    let mut shunts = Vec::new();
1219    for sh in net.shunts() {
1220        extras(&sh.name, &sh.extras, &[])?;
1221        let ids = resolve(&sh.name, &sh.bus, &sh.terminal_map)?;
1222        let n = ids.len();
1223        shunts.push(McOpfShunt {
1224            identity: sh.name.clone(),
1225            terminals: ids,
1226            g: matrix(&sh.name, &sh.g, n, zb)?,
1227            b: matrix(&sh.name, &sh.b, n, zb)?,
1228        });
1229    }
1230    for cap in net.capacitors() {
1231        extras(&cap.name, &cap.extras, &[])?;
1232        let ids = resolve(&cap.name, &cap.bus, &cap.terminal_map)?;
1233        if cap.configuration == Configuration::Delta {
1234            ctx.require_phase_terminals(&cap.name, &cap.bus, &cap.terminal_map)?;
1235        }
1236        finite(&cap.name, &[cap.q_rated, cap.v_nom])?;
1237        if cap.q_rated < 0.0 {
1238            return Err(invalid(
1239                &cap.name,
1240                "capacitor requires positive voltage and nonnegative var",
1241            ));
1242        }
1243        // The one capacitor stamp, siemens, written per unit.
1244        let primitive =
1245            crate::matrix::multiconductor::calc_capacitor_primitive_admittance(net, cap)
1246                .map_err(|error| invalid(&cap.name, error))?
1247                .ok_or_else(|| unsupported(&cap.name, "unknown configuration"))?;
1248        let scaled = |part: fn(&num_complex::Complex64) -> f64| -> Result<Vec<Vec<f64>>> {
1249            primitive
1250                .iter()
1251                .map(|row| {
1252                    let row: Vec<f64> = row.iter().map(|y| part(y) * zb).collect();
1253                    finite(&cap.name, &row)?;
1254                    Ok(row)
1255                })
1256                .collect()
1257        };
1258        shunts.push(McOpfShunt {
1259            identity: format!("capacitor:{}", cap.name),
1260            g: scaled(|y| y.re)?,
1261            b: scaled(|y| y.im)?,
1262            terminals: ids,
1263        });
1264    }
1265    Ok(shunts)
1266}
1267fn prepare_loads(
1268    ctx: &Context<'_>,
1269    sb: f64,
1270    vb: f64,
1271    policy: BoundedLoadLawPolicy,
1272    projections: &mut Vec<McOpfLoadLawProjection>,
1273) -> Result<Vec<McOpfDevice>> {
1274    let net = ctx.net;
1275    let coil_map = |name: &str, bus: &str, tm: &[String], config| ctx.coils(name, bus, tm, config);
1276    let mut devices = Vec::new();
1277    for (row, load) in net.loads().iter().enumerate() {
1278        extras(&load.name, &load.extras, &[])?;
1279        let (ids, pairs) = coil_map(
1280            &load.name,
1281            &load.bus,
1282            &load.terminal_map,
1283            load.configuration,
1284        )?;
1285        let n = pairs.len();
1286        vector(&load.name, &load.p_nom, n)?;
1287        vector(&load.name, &load.q_nom, n)?;
1288        for (&p, &q) in load.p_nom.iter().zip(&load.q_nom) {
1289            finite(&load.name, &[p / sb, q / sb])?;
1290        }
1291        let projected;
1292        let model = if policy == BoundedLoadLawPolicy::ProjectToNominal
1293            && matches!(
1294                load.voltage_model,
1295                DistLoadVoltageModel::BoundedZip { .. }
1296                    | DistLoadVoltageModel::BoundedExponential { .. }
1297                    | DistLoadVoltageModel::BoundedConstantPower { .. }
1298            ) {
1299            projected = load.voltage_model.without_voltage_bounds();
1300            let tag = |model: &DistLoadVoltageModel| {
1301                serde_json::to_value(model)
1302                    .ok()
1303                    .and_then(|value| value["model"].as_str().map(str::to_owned))
1304                    .unwrap_or_default()
1305            };
1306            projections.push(McOpfLoadLawProjection {
1307                load: load.name.clone(),
1308                source_model: tag(&load.voltage_model),
1309                projected_model: tag(&projected),
1310            });
1311            &projected
1312        } else {
1313            &load.voltage_model
1314        };
1315        let laws = prepare_load_laws(load, model, n, sb, vb)?;
1316        let coils = pairs
1317            .into_iter()
1318            .enumerate()
1319            .map(|(k, (positive, negative))| McOpfCoil {
1320                positive,
1321                negative,
1322                prescribed: Some([load.p_nom[k] / sb, load.q_nom[k] / sb]),
1323                load_law: laws[k].clone(),
1324                reactive_slope: None,
1325                power_factor_coefficients: None,
1326                volt_var: None,
1327                volt_watt: None,
1328                p_min: None,
1329                p_max: None,
1330                q_min: None,
1331                q_max: None,
1332                current_max: None,
1333                apparent_max: None,
1334                cost: 0.0,
1335            })
1336            .collect();
1337        devices.push(McOpfDevice {
1338            identity: load.name.clone(),
1339            kind: McOpfDeviceKind::Load,
1340            source_row: row,
1341            terminals: ids,
1342            coils,
1343            neutral_current_max: None,
1344            net_active_bounds: None,
1345        });
1346    }
1347    Ok(devices)
1348}
1349fn prepare_generators(
1350    ctx: &Context<'_>,
1351    instance: &McAcOpfInstance,
1352    ib: f64,
1353    sb: f64,
1354    cost_weight: f64,
1355) -> Result<Vec<McOpfDevice>> {
1356    let net = ctx.net;
1357    let coil_map = |name: &str, bus: &str, tm: &[String], config| ctx.coils(name, bus, tm, config);
1358    let mut devices = Vec::new();
1359    let selected = instance.constraints();
1360    for (row, generator) in net.generators().iter().enumerate() {
1361        extras(&generator.name, &generator.extras, &[])?;
1362        let (ids, pairs) = coil_map(
1363            &generator.name,
1364            &generator.bus,
1365            &generator.terminal_map,
1366            generator.configuration,
1367        )?;
1368        let n = pairs.len();
1369        let active = selected.generator_capability.selects(&generator.name);
1370        let pmin = bounds(
1371            &generator.name,
1372            generator.p_min.as_ref().filter(|_| active),
1373            n,
1374            sb,
1375        )?;
1376        let pmax = bounds(
1377            &generator.name,
1378            generator.p_max.as_ref().filter(|_| active),
1379            n,
1380            sb,
1381        )?;
1382        let qmin = bounds(
1383            &generator.name,
1384            generator.q_min.as_ref().filter(|_| active),
1385            n,
1386            sb,
1387        )?;
1388        let qmax = bounds(
1389            &generator.name,
1390            generator.q_max.as_ref().filter(|_| active),
1391            n,
1392            sb,
1393        )?;
1394        let smax = caps(
1395            &generator.name,
1396            generator.s_max.as_ref().filter(|_| active),
1397            n,
1398            sb,
1399        )?;
1400        let (imax, neutral_current_max) = device_current_caps(
1401            &generator.name,
1402            generator.configuration,
1403            &ids,
1404            &pairs,
1405            generator.i_max.as_ref().filter(|_| active),
1406            ib,
1407        )?;
1408        for nominal in [&generator.p_nom, &generator.q_nom] {
1409            if !nominal.is_empty() {
1410                vector(&generator.name, nominal, n)?;
1411            }
1412        }
1413        let costs = costs(&generator.name, generator.cost.as_ref(), n, sb)?;
1414        let mut coils = Vec::new();
1415        for (k, (positive, negative)) in pairs.into_iter().enumerate() {
1416            if pmin[k].zip(pmax[k]).is_some_and(|(a, b)| a > b)
1417                || qmin[k].zip(qmax[k]).is_some_and(|(a, b)| a > b)
1418            {
1419                return Err(invalid(&generator.name, "reversed capability bounds"));
1420            }
1421            coils.push(McOpfCoil {
1422                positive,
1423                negative,
1424                prescribed: None,
1425                load_law: None,
1426                reactive_slope: None,
1427                power_factor_coefficients: None,
1428                volt_var: None,
1429                volt_watt: None,
1430                p_min: pmin[k],
1431                p_max: pmax[k],
1432                q_min: qmin[k],
1433                q_max: qmax[k],
1434                current_max: imax[k],
1435                apparent_max: smax[k],
1436                cost: costs[k].unwrap_or(0.0) * cost_weight,
1437            });
1438        }
1439        devices.push(McOpfDevice {
1440            identity: generator.name.clone(),
1441            kind: McOpfDeviceKind::Generator,
1442            source_row: row,
1443            terminals: ids,
1444            coils,
1445            neutral_current_max,
1446            net_active_bounds: None,
1447        });
1448    }
1449    Ok(devices)
1450}
1451fn prepare_source_devices(
1452    ctx: &Context<'_>,
1453    terminals: &[McOpfTerminal],
1454    sb: f64,
1455    cost_weight: f64,
1456) -> Result<Vec<McOpfDevice>> {
1457    let net = ctx.net;
1458    let coil_map = |name: &str, bus: &str, tm: &[String], config| ctx.coils(name, bus, tm, config);
1459    let mut devices = Vec::new();
1460    for (row, src) in net.sources().iter().enumerate() {
1461        let (ids, pairs) = coil_map(&src.name, &src.bus, &src.terminal_map, Configuration::Wye)?;
1462        let n = pairs.len();
1463        if pairs
1464            .iter()
1465            .any(|(_, neg)| neg.is_some_and(|i| !terminals[i].grounded))
1466        {
1467            return Err(unsupported(
1468                &src.name,
1469                "source neutral must be explicitly grounded",
1470            ));
1471        }
1472        let costs = costs(&src.name, src.energy_cost_rate.as_ref(), n, sb)?;
1473        let coils = pairs
1474            .into_iter()
1475            .enumerate()
1476            .map(|(k, (positive, negative))| McOpfCoil {
1477                positive,
1478                negative,
1479                prescribed: None,
1480                load_law: None,
1481                reactive_slope: None,
1482                power_factor_coefficients: None,
1483                volt_var: None,
1484                volt_watt: None,
1485                p_min: None,
1486                p_max: None,
1487                q_min: None,
1488                q_max: None,
1489                current_max: None,
1490                apparent_max: None,
1491                cost: costs[k].unwrap_or(0.0) * cost_weight,
1492            })
1493            .collect();
1494        devices.push(McOpfDevice {
1495            identity: src.name.clone(),
1496            kind: McOpfDeviceKind::Source,
1497            source_row: row,
1498            terminals: ids,
1499            coils,
1500            neutral_current_max: None,
1501            net_active_bounds: None,
1502        });
1503    }
1504    Ok(devices)
1505}
1506fn check_ideal_topology(branches: &[McOpfBranch], terminals: &[McOpfTerminal]) -> Result<()> {
1507    // Conservative structural checks. Do not classify numerical near-zero Z as ideal.
1508    let mut ideal = powerio_core::union_find::UnionFind::new(terminals.len());
1509    for br in branches.iter().filter(|b| !b.open) {
1510        for k in 0..br.from.len() {
1511            if br.r[k].iter().chain(&br.x[k]).all(|x| *x == 0.0) {
1512                if terminals[br.from[k]].fixed.is_some() && terminals[br.to[k]].fixed.is_some() {
1513                    return Err(unsupported(
1514                        &br.identity,
1515                        "ideal row between fixed terminals has undetermined current",
1516                    ));
1517                }
1518                if !ideal.union(br.to[k], br.from[k]) {
1519                    return Err(invalid(&br.identity, "dependent ideal-conductor cycle"));
1520                }
1521            }
1522        }
1523    }
1524    let mut ideal_fixed = BTreeSet::new();
1525    for (i, t) in terminals.iter().enumerate() {
1526        if t.fixed.is_some() && !ideal_fixed.insert(ideal.find(i)) {
1527            return Err(unsupported(
1528                &t.bus,
1529                "ideal path joins multiple fixed voltage references",
1530            ));
1531        }
1532    }
1533    Ok(())
1534}
1535fn check_topology(branches: &[McOpfBranch], terminals: &mut [McOpfTerminal]) -> Result<()> {
1536    let connected = powerio_core::union_find::calc_component_labels(
1537        terminals.len(),
1538        branches
1539            .iter()
1540            .filter(|b| !b.open)
1541            .flat_map(|br| br.from.iter().copied().zip(br.to.iter().copied())),
1542    );
1543    let mut anchors = BTreeMap::new();
1544    for (i, t) in terminals.iter().enumerate() {
1545        if let Some(value) = t.fixed {
1546            anchors.entry(connected[i]).or_insert(value);
1547        }
1548    }
1549    for (i, t) in terminals.iter_mut().enumerate() {
1550        let Some(value) = anchors.get(&connected[i]) else {
1551            return Err(unsupported(
1552                &format!("{}:{}", t.bus, t.terminal),
1553                "conductor component has no fixed voltage reference",
1554            ));
1555        };
1556        // Propagate physical source phasors, not an implicit one-per-unit guess.
1557        // This is a start only; no source equality is added to remote terminals.
1558        if t.fixed.is_none() {
1559            t.start = *value;
1560        }
1561    }
1562    Ok(())
1563}
1564fn costs(owner: &str, values: Option<&Vec<f64>>, n: usize, sb: f64) -> Result<Vec<Option<f64>>> {
1565    let expanded = values.filter(|v| v.len() == 1).map(|v| vec![v[0]; n]);
1566    bounds(owner, expanded.as_ref().or(values), n, 1000.0 / sb)
1567}
1568fn push_voltage_limits(
1569    output: &mut Vec<McOpfVoltageLimit>,
1570    bus_id: &str,
1571    family: &str,
1572    pairs: CoilPairs,
1573    lo: Option<&Vec<f64>>,
1574    hi: Option<&Vec<f64>>,
1575    vb: f64,
1576) -> Result<()> {
1577    if let Some(lo) = lo {
1578        finite(bus_id, lo)?;
1579    }
1580    let lows = caps(bus_id, lo, pairs.len(), vb)?;
1581    let highs = caps(bus_id, hi, pairs.len(), vb)?;
1582    for (k, ((positive, negative), (lower, upper))) in pairs
1583        .into_iter()
1584        .zip(lows.into_iter().zip(highs))
1585        .enumerate()
1586    {
1587        if lower.zip(upper).is_some_and(|(l, u)| l > u) {
1588            return Err(invalid(bus_id, "reversed voltage limits"));
1589        }
1590        if lower.is_some() || upper.is_some() {
1591            output.push(McOpfVoltageLimit {
1592                combination: Vec::new(),
1593                identity: format!("{bus_id}:{family}:{k}"),
1594                positive,
1595                negative,
1596                lower,
1597                upper,
1598            });
1599        }
1600    }
1601    Ok(())
1602}
1603
1604fn prepare_load_laws(
1605    load: &powerio_dist::DistLoad,
1606    model: &DistLoadVoltageModel,
1607    n: usize,
1608    sb: f64,
1609    vb: f64,
1610) -> Result<Vec<Option<McOpfLoadLaw>>> {
1611    use DistLoadVoltageModel as Law;
1612    if matches!(model, Law::ConstantPower { .. }) {
1613        return Ok(vec![None; n]);
1614    }
1615    if matches!(
1616        model,
1617        Law::BoundedZip { .. } | Law::BoundedExponential { .. } | Law::BoundedConstantPower { .. }
1618    ) {
1619        return Err(unsupported(
1620            &load.name,
1621            "voltage-bounded load laws require piecewise IVR equations; a nominal-law approximation is not implicit (opt in with BoundedLoadLawPolicy::ProjectToNominal)",
1622        ));
1623    }
1624    let axis_ok = |v: &[f64]| v.is_empty() || v.len() == n;
1625    let axes: Vec<&[f64]> = match model {
1626        Law::Exponential {
1627            gamma_p, gamma_q, ..
1628        } => vec![gamma_p, gamma_q],
1629        Law::Zip {
1630            alpha_z,
1631            alpha_i,
1632            alpha_p,
1633            beta_z,
1634            beta_i,
1635            beta_p,
1636            ..
1637        } => vec![alpha_z, alpha_i, alpha_p, beta_z, beta_i, beta_p],
1638        _ => Vec::new(),
1639    };
1640    if !axis_ok(model.v_nom()) || axes.iter().any(|v| !axis_ok(v)) {
1641        return Err(invalid(
1642            &load.name,
1643            "load law vector must state one entry per coil",
1644        ));
1645    }
1646    (0..n)
1647        .map(|k| {
1648            let nominal = model.nominal_voltage(k).unwrap_or(f64::NAN) / vb;
1649            if !nominal.is_finite() || nominal <= 0.0 {
1650                return Err(invalid(
1651                    &load.name,
1652                    "voltage-dependent load requires positive nominal coil voltage",
1653                ));
1654            }
1655            let p = load.p_nom[k] / sb;
1656            let q = load.q_nom[k] / sb;
1657            // The one term form of the law (`DistLoadVoltageModel::calc_power_terms`),
1658            // scaled to this coil's per unit nominal power.
1659            let fractions = model
1660                .calc_power_terms(k)
1661                .map_err(|error| invalid(&load.name, &error))?
1662                .ok_or_else(|| unsupported(&load.name, "unknown load voltage law"))?;
1663            let terms = [p, q]
1664                .into_iter()
1665                .zip(fractions)
1666                .map(|(power, row)| {
1667                    row.into_iter()
1668                        .map(|[fraction, exponent]| [power * fraction, exponent])
1669                        .filter(|t| t[0] != 0.0)
1670                        .collect::<Vec<_>>()
1671                })
1672                .collect::<Vec<_>>();
1673            let terms: [Vec<[f64; 2]>; 2] = terms.try_into().expect("two components");
1674            for row in &terms {
1675                for t in row {
1676                    finite(&load.name, t)?;
1677                }
1678            }
1679            Ok(Some(McOpfLoadLaw { nominal, terms }))
1680        })
1681        .collect()
1682}
1683
1684fn prepare_angles(ctx: &Context<'_>, instance: &McAcOpfInstance) -> Result<Vec<McOpfAngleLimit>> {
1685    let mut out = Vec::new();
1686    let window =
1687        |name: &str, data: &BTreeMap<String, serde_json::Value>| -> Result<Option<[f64; 2]>> {
1688            if !data.contains_key("va_diff_min") && !data.contains_key("va_diff_max") {
1689                return Ok(None);
1690            }
1691            let lo = data
1692                .get("va_diff_min")
1693                .and_then(serde_json::Value::as_f64)
1694                .ok_or_else(|| invalid(name, "angle needs two scalar bounds"))?;
1695            let hi = data
1696                .get("va_diff_max")
1697                .and_then(serde_json::Value::as_f64)
1698                .ok_or_else(|| invalid(name, "angle needs two scalar bounds"))?;
1699            if !lo.is_finite()
1700                || !hi.is_finite()
1701                || lo > hi
1702                || lo <= -std::f64::consts::FRAC_PI_2
1703                || hi >= std::f64::consts::FRAC_PI_2
1704            {
1705                return Err(invalid(
1706                    name,
1707                    "angle window must lie strictly within +/- pi/2",
1708                ));
1709            }
1710            Ok(Some([lo, hi]))
1711        };
1712    for line in ctx.net.lines() {
1713        if let Some([lower, upper]) = window(&line.name, &line.extras)? {
1714            let from = ctx.resolve(&line.name, &line.bus_from, &line.terminal_map_from)?;
1715            let to = ctx.resolve(&line.name, &line.bus_to, &line.terminal_map_to)?;
1716            for (k, (&first, &second)) in from.iter().zip(&to).enumerate() {
1717                out.push(McOpfAngleLimit {
1718                    identity: format!("line:{}:{k}", line.name),
1719                    first,
1720                    second,
1721                    offset: 0.0,
1722                    lower,
1723                    upper,
1724                });
1725            }
1726        }
1727    }
1728    for bus in ctx.net.buses() {
1729        if !instance
1730            .constraints()
1731            .terminal_voltage_bounds
1732            .selects(&bus.id)
1733        {
1734            continue;
1735        }
1736        if let Some([lower, upper]) = window(&bus.id, &bus.extras)? {
1737            let phase = bus.phase_indices(ctx.net.terminal_conventions());
1738            let nominal: Vec<f64> = bus
1739                .extras
1740                .get("va_nom")
1741                .map(|v| serde_json::from_value(v.clone()))
1742                .transpose()
1743                .map_err(|_| invalid(&bus.id, "invalid nominal angles"))?
1744                .unwrap_or_else(|| vec![0.0; phase.len()]);
1745            vector(&bus.id, &nominal, phase.len())?;
1746            for a in 0..phase.len() {
1747                for b in a + 1..phase.len() {
1748                    out.push(McOpfAngleLimit {
1749                        identity: format!("bus:{}:{a}:{b}", bus.id),
1750                        first: ctx.positions[&(bus.id.clone(), bus.terminals[phase[a]].clone())],
1751                        second: ctx.positions[&(bus.id.clone(), bus.terminals[phase[b]].clone())],
1752                        offset: nominal[a] - nominal[b],
1753                        lower,
1754                        upper,
1755                    });
1756                }
1757            }
1758        }
1759    }
1760    Ok(out)
1761}
1762
1763fn prepare_sequences(
1764    bus: &powerio_dist::DistBus,
1765    pids: &[usize],
1766    neutral: Option<usize>,
1767    vb: f64,
1768    voltage_limits: &mut Vec<McOpfVoltageLimit>,
1769) -> Result<()> {
1770    if [bus.vpos_min, bus.vpos_max, bus.vneg_max, bus.vzero_max]
1771        .iter()
1772        .any(Option::is_some)
1773    {
1774        if pids.len() != 3 {
1775            return Err(invalid(
1776                &bus.id,
1777                "sequence bounds require exactly three phases",
1778            ));
1779        }
1780        // Column `k` of the sequence transform: the zero, positive and
1781        // negative components of a unit phasor on phase `k`.
1782        let columns = [0, 1, 2].map(|k| {
1783            let mut unit = [num_complex::Complex64::default(); 3];
1784            unit[k] = num_complex::Complex64::new(1.0, 0.0);
1785            powerio_dist::sequence::calc_sequence_components(
1786                unit,
1787                powerio_dist::sequence::SequenceRotation::Fortescue,
1788            )
1789        });
1790        for (name, sequence, lower, upper) in [
1791            ("positive", 1, bus.vpos_min, bus.vpos_max),
1792            ("negative", 2, None, bus.vneg_max),
1793            ("zero", 0, None, bus.vzero_max),
1794        ] {
1795            if lower.is_none() && upper.is_none() {
1796                continue;
1797            }
1798            let lo = caps(&bus.id, lower.map(|v| vec![v]).as_ref(), 1, vb)?[0];
1799            let hi = caps(&bus.id, upper.map(|v| vec![v]).as_ref(), 1, vb)?[0];
1800            if lower.is_some_and(|v| !v.is_finite()) || lo.zip(hi).is_some_and(|(l, h)| l > h) {
1801                return Err(invalid(&bus.id, "invalid sequence interval"));
1802            }
1803            let mut combination = Vec::new();
1804            for (column, &id) in columns.iter().zip(pids) {
1805                let entry = column[sequence];
1806                combination.push((id, [entry.re, entry.im]));
1807            }
1808            if sequence == 0
1809                && let Some(n) = neutral
1810            {
1811                combination.push((n, [-1.0, 0.0]));
1812            }
1813            voltage_limits.push(McOpfVoltageLimit {
1814                identity: format!("{}:sequence:{name}", bus.id),
1815                positive: pids[0],
1816                negative: None,
1817                lower: lo,
1818                upper: hi,
1819                combination,
1820            });
1821        }
1822    }
1823    Ok(())
1824}
1825
1826// Star ratings follow terminal_map; delta ratings follow coil order. Resolve
1827// endpoints before removing the neutral from the coil axis.
1828fn device_current_caps(
1829    owner: &str,
1830    configuration: Configuration,
1831    ids: &[usize],
1832    pairs: &CoilPairs,
1833    values: Option<&Vec<f64>>,
1834    base: f64,
1835) -> Result<(Vec<Option<f64>>, Option<f64>)> {
1836    if configuration == Configuration::Delta {
1837        return Ok((caps(owner, values, pairs.len(), base)?, None));
1838    }
1839    let ratings = caps(owner, values, ids.len(), base)?;
1840    let rating = |id| {
1841        ids.iter()
1842            .position(|&terminal| terminal == id)
1843            .map(|row| ratings[row])
1844            .ok_or_else(|| invalid(owner, "coil endpoint missing from terminal map"))
1845    };
1846    let mut coils = pairs
1847        .iter()
1848        .map(|&(positive, _)| rating(positive))
1849        .collect::<Result<Vec<_>>>()?;
1850    let neutral = pairs
1851        .first()
1852        .and_then(|&(_, negative)| negative)
1853        .map(rating)
1854        .transpose()?
1855        .flatten();
1856    if coils.len() == 1 {
1857        // A two-wire device has equal outgoing and return current magnitudes.
1858        coils[0] = match (coils[0], neutral) {
1859            (Some(a), Some(b)) => Some(a.min(b)),
1860            (a, b) => a.or(b),
1861        };
1862        return Ok((coils, None));
1863    }
1864    Ok((coils, neutral))
1865}
1866
1867#[cfg(test)]
1868mod evaluation_tests {
1869    use super::*;
1870
1871    #[test]
1872    fn a_load_law_sums_its_terms_with_their_voltage_slope() {
1873        let law = McOpfLoadLaw {
1874            nominal: 0.5,
1875            terms: [vec![[1.0, 2.0], [0.5, 0.0]], vec![[0.2, 1.0]]],
1876        };
1877        let [(p, dp), (q, dq)] = law.calc_power(0.4);
1878        assert!((p - (0.64 + 0.5)).abs() < 1e-15);
1879        assert!((dp - 2.0 * 0.8 / 0.5).abs() < 1e-15);
1880        assert!((q - 0.16).abs() < 1e-15 && (dq - 0.4).abs() < 1e-15);
1881    }
1882
1883    #[test]
1884    fn a_droop_curve_and_its_derivatives_match_finite_differences() {
1885        let curve = McOpfDroop {
1886            monitors: vec![(0, None)],
1887            knots: vec![0.95, 0.98, 1.02, 1.05],
1888            values: vec![0.4, 0.0, 0.0, -0.4],
1889            epsilon: 0.005,
1890        };
1891        let h = 1e-7;
1892        for v in [0.9, 0.97, 1.0, 1.03, 1.1] {
1893            let c = curve.calc_control(v);
1894            let fd =
1895                (curve.calc_control(v + h).value - curve.calc_control(v - h).value) / (2.0 * h);
1896            assert!((c.slope - fd).abs() < 1e-5, "{v}: {} {fd}", c.slope);
1897        }
1898        assert!((curve.calc_control(0.9).value - 0.4).abs() < 1e-4);
1899        assert!((curve.calc_control(1.1).value + 0.4).abs() < 1e-4);
1900        let (dk, dv, de) = ([0.0, 0.01, 0.0, -0.02], [0.1, 0.0, 0.0, 0.05], 0.001);
1901        let moved = |t: f64| McOpfDroop {
1902            monitors: curve.monitors.clone(),
1903            knots: curve.knots.iter().zip(dk).map(|(k, d)| k + t * d).collect(),
1904            values: curve
1905                .values
1906                .iter()
1907                .zip(dv)
1908                .map(|(k, d)| k + t * d)
1909                .collect(),
1910            epsilon: curve.epsilon + t * de,
1911        };
1912        for v in [0.96, 0.99, 1.04] {
1913            let d = curve.calc_parameter_derivative(v, &dk, &dv, de);
1914            let (plus, minus) = (moved(h).calc_control(v), moved(-h).calc_control(v));
1915            assert!((d.value - (plus.value - minus.value) / (2.0 * h)).abs() < 1e-5);
1916            assert!((d.slope - (plus.slope - minus.slope) / (2.0 * h)).abs() < 1e-3);
1917        }
1918        let voltage = [num_complex::Complex64::new(1.01, 0.0)];
1919        assert!((curve.calc_monitored_voltage(&voltage) - 1.01).abs() < 1e-15);
1920    }
1921}