Skip to main content

powerio_matrix/mcopf/
transformer.rs

1//! Winding-current descriptor; no inverse of a leakage impedance is formed.
2use super::{
3    Context, Deserialize, McAcOpfAssemblyOptions, McOpfBranch, McOpfShunt, McOpfTerminal, Result,
4    Serialize, caps, extras, finite, invalid, unsupported,
5};
6use num_complex::Complex64;
7use powerio_dist::DistWindingConn;
8use powerio_dist::transformer::{
9    TransformerLeakageBase, TransformerMagnetizing, WindingNeutralGrounding,
10    calc_coil_shunt_primitive, calc_coil_voltage, calc_reduced_leakage, calc_regulator_series_ohms,
11    calc_transformer_leakage_impedances, calc_transformer_magnetizing, calc_winding_connection,
12    calc_winding_impedance_base, calc_winding_neutral_grounding, calc_winding_phase_count,
13    is_transformer_regulator, transformer_extra_number,
14};
15
16#[derive(Clone, Debug, Serialize, Deserialize, Default)]
17#[non_exhaustive]
18/// Complex affine expression with no constant term. Coefficients are `[real, imaginary]`.
19/// Voltage indices address preparation.terminals; current indices address the
20/// owning transformer's coils. Rows of equations are constrained to zero.
21pub struct McOpfComplexRow {
22    /// Sparse terminal-voltage coefficients in per unit.
23    pub voltage: Vec<(usize, [f64; 2])>,
24    /// Sparse local winding-current coefficients in per unit.
25    pub current: Vec<(usize, [f64; 2])>,
26}
27#[derive(Clone, Debug, Serialize, Deserialize)]
28#[non_exhaustive]
29/// A winding coil oriented from positive to negative, with a retained current unknown.
30pub struct McOpfTransformerCoil {
31    /// Global positive terminal index.
32    pub positive: usize,
33    /// Global negative terminal index, or physical ground.
34    pub negative: Option<usize>,
35}
36#[derive(Clone, Debug, Serialize, Deserialize)]
37#[non_exhaustive]
38/// A rated physical terminal/coil port reconstructed from winding currents.
39pub struct McOpfTransformerPort {
40    /// Winding/terminal port identity within the transformer.
41    pub name: String,
42    /// Global positive voltage terminal for this port.
43    pub positive: usize,
44    /// Global return voltage terminal, or physical ground.
45    pub negative: Option<usize>,
46    /// Complex per-unit port current reconstructed from local coil currents and terminal voltages.
47    pub current: McOpfComplexRow,
48    /// Optional per-unit current magnitude bound.
49    pub current_max: Option<f64>,
50    /// Optional per-unit apparent-power bound at this port.
51    pub apparent_max: Option<f64>,
52}
53#[derive(Clone, Debug, Serialize, Deserialize)]
54#[non_exhaustive]
55/// Winding-current equations, ports and optional continuous tap parameter.
56/// Each row is `equations[k] + t * tap_equations[k] = 0`, where `t` is a
57/// dimensionless multiplier with nominal value one. The physical tap is
58/// `tap_nominal * t`, or `tap_nominal / t` when `tap_inverse` is true.
59/// An empty tap_equations vector means the descriptor is fixed.
60pub struct McOpfTransformer {
61    /// Canonical transformer name.
62    pub identity: String,
63    /// Local winding-current axis and terminal incidence; these currents enter network KCL.
64    pub coils: Vec<McOpfTransformerCoil>,
65    /// Complex zero-residual rows using global voltages and local winding currents.
66    pub equations: Vec<McOpfComplexRow>,
67    /// Physical rated ports, with axes distinct from the internal coil axis.
68    pub ports: Vec<McOpfTransformerPort>,
69    /// Optional multiplier on the nominal tap coefficient (start = 1).
70    pub tap_bounds: Option<[f64; 2]>,
71    /// Physical nominal tap used to recover a physical tap from the multiplier.
72    pub tap_nominal: f64,
73    /// True for regulators, of either ANSI type, whose tap is the regulated
74    /// over source voltage ratio.
75    pub tap_inverse: bool,
76    /// Rows multiplied by the tap multiplier, aligned with equations; empty for fixed taps.
77    pub tap_equations: Vec<McOpfComplexRow>,
78}
79impl McOpfTransformer {
80    /// The physical tap at a tap multiplier `t`: `tap_nominal * t`, or
81    /// `tap_nominal / t` for a regulator (`tap_inverse`). The one tap
82    /// convention, with its inverse [`Self::calc_tap_multiplier`] and the
83    /// derivatives below.
84    #[must_use]
85    pub fn calc_physical_tap(&self, multiplier: f64) -> f64 {
86        if self.tap_inverse {
87            self.tap_nominal / multiplier
88        } else {
89            self.tap_nominal * multiplier
90        }
91    }
92
93    /// The tap multiplier of a physical tap: `physical / tap_nominal`, or
94    /// `tap_nominal / physical` for a regulator. The preparation maps its
95    /// physical tap bounds through it.
96    #[must_use]
97    pub fn calc_tap_multiplier(&self, physical: f64) -> f64 {
98        if self.tap_inverse {
99            self.tap_nominal / physical
100        } else {
101            physical / self.tap_nominal
102        }
103    }
104
105    /// `d physical / d t` at the multiplier `t`: `tap_nominal`, or
106    /// `-tap_nominal / t²` for a regulator.
107    #[must_use]
108    pub fn calc_physical_tap_derivative(&self, multiplier: f64) -> f64 {
109        if self.tap_inverse {
110            -self.tap_nominal / multiplier.powi(2)
111        } else {
112            self.tap_nominal
113        }
114    }
115
116    /// `d t / d physical` at a physical tap: `1 / tap_nominal`, or
117    /// `-tap_nominal / physical²` for a regulator.
118    #[must_use]
119    pub fn calc_tap_multiplier_derivative(&self, physical: f64) -> f64 {
120        if self.tap_inverse {
121            -self.tap_nominal / physical.powi(2)
122        } else {
123            self.tap_nominal.recip()
124        }
125    }
126}
127fn add_voltage(row: &mut McOpfComplexRow, coil: &McOpfTransformerCoil, value: f64) {
128    row.voltage.push((coil.positive, [value, 0.0]));
129    if let Some(n) = coil.negative {
130        row.voltage.push((n, [-value, 0.0]));
131    }
132}
133fn extra_number(t: &powerio_dist::DistTransformer, key: &str, default: f64) -> Result<f64> {
134    let v = transformer_extra_number(&t.extras, key).unwrap_or(default);
135    if !v.is_finite() {
136        return Err(invalid(&t.name, format!("invalid {key}")));
137    }
138    Ok(v)
139}
140fn extra_vector(t: &powerio_dist::DistTransformer, key: &str) -> Result<Option<Vec<f64>>> {
141    t.extras
142        .get(key)
143        .map(|v| {
144            serde_json::from_value(v.clone())
145                .map_err(|_| invalid(&t.name, format!("invalid {key}")))
146        })
147        .transpose()
148}
149/// A per unit admittance `g + j b` across one coil, as a local shunt
150/// ([`calc_coil_shunt_primitive`]).
151fn stamp_shunt(
152    shunts: &mut Vec<McOpfShunt>,
153    name: String,
154    coil: &McOpfTransformerCoil,
155    g: f64,
156    b: f64,
157) {
158    if g == 0.0 && b == 0.0 {
159        return;
160    }
161    let matrix = calc_coil_shunt_primitive(Complex64::new(g, b), coil.negative.is_none());
162    let terminals = std::iter::once(coil.positive)
163        .chain(coil.negative)
164        .collect();
165    shunts.push(McOpfShunt {
166        identity: name,
167        terminals,
168        g: matrix
169            .iter()
170            .map(|row| row.iter().map(|y| y.re).collect())
171            .collect(),
172        b: matrix
173            .iter()
174            .map(|row| row.iter().map(|y| y.im).collect())
175            .collect(),
176    });
177}
178#[derive(Clone, Copy)]
179struct TransformerProfile<'a> {
180    t: &'a powerio_dist::DistTransformer,
181    subtype: &'a str,
182    nw: bool,
183    regulator: bool,
184    phases: usize,
185    zb: f64,
186    ib: f64,
187    sb: f64,
188    /// The magnetizing branch the unit states, siemens per coil.
189    core: Option<TransformerMagnetizing>,
190}
191type TerminalRatings = (Option<Vec<f64>>, Option<f64>);
192type WindingGeometry = (Vec<super::CoilPairs>, Vec<f64>);
193
194pub(super) fn prepare(
195    ctx: &Context<'_>,
196    bases: &McAcOpfAssemblyOptions,
197    branches: &mut Vec<McOpfBranch>,
198    shunts: &mut Vec<McOpfShunt>,
199    terminals: &[McOpfTerminal],
200) -> Result<Vec<McOpfTransformer>> {
201    let mut out = Vec::new();
202    let sb = bases.power_base_va;
203    let zb = powerio_core::electrical::calc_impedance_base(bases.voltage_base_v, sb)
204        .ok_or_else(|| invalid("assembly", "the voltage and power bases must be positive"))?;
205    let ib = sb / bases.voltage_base_v;
206    for t in ctx.net.transformers() {
207        validate_extras(t)?;
208        for key in ["bmopf_winding_metadata", "bmopf_delta_rolls"] {
209            if let Some(value) = t.extras.get(key)
210                && !value.is_object()
211            {
212                return Err(invalid(&t.name, format!("{key} must be an object")));
213            }
214        }
215        let subtype = t
216            .extras
217            .get("bmopf_subtype")
218            .map(|v| {
219                v.as_str()
220                    .ok_or_else(|| invalid(&t.name, "invalid transformer subtype"))
221            })
222            .transpose()?
223            .unwrap_or("canonical");
224        let regulator = is_transformer_regulator(t);
225        let nw = subtype == "n_winding" || subtype == "canonical";
226        if !matches!(
227            subtype,
228            "canonical"
229                | "n_winding"
230                | "single_phase"
231                | "center_tap"
232                | "wye_delta"
233                | "delta_wye"
234                | "single_phase_autotransformer"
235                | "open_delta_regulator"
236        ) {
237            return Err(unsupported(&t.name, "unknown transformer subtype"));
238        }
239        let m = t.windings.len();
240        if m < 2 || t.xsc_pct.len() != m * (m - 1) / 2 {
241            return Err(invalid(&t.name, "invalid winding/leakage dimensions"));
242        }
243        let (maps, mut noms) = winding_geometry(ctx, t, subtype)?;
244        let phases = maps[0].len();
245        if maps.iter().any(|p| p.len() != phases) {
246            return Err(invalid(&t.name, "all windings must have equal coil count"));
247        }
248        if regulator {
249            prepare_regulator(ctx, t, &maps, &mut noms, branches, terminals)?;
250        }
251        let profile = TransformerProfile {
252            t,
253            subtype,
254            nw,
255            regulator,
256            phases,
257            zb,
258            ib,
259            sb,
260            core: calc_transformer_magnetizing(t).map_err(|error| invalid(&t.name, error))?,
261        };
262        let mut tx = leakage_descriptor(&profile, &maps, &noms)?;
263        prepare_ports(&profile, ctx, &maps, &mut tx, shunts, terminals)?;
264        for row in &tx.equations {
265            for (_, c) in row.voltage.iter().chain(&row.current) {
266                finite(&t.name, c)?;
267            }
268        }
269        core_shunts(&profile, &tx, shunts);
270        prepare_tap(&profile, &noms, &mut tx)?;
271        out.push(tx);
272    }
273    Ok(out)
274}
275/// The magnetizing branch ([`calc_transformer_magnetizing`]) as one per
276/// unit shunt across each coil of its winding.
277fn core_shunts(
278    profile: &TransformerProfile<'_>,
279    tx: &McOpfTransformer,
280    shunts: &mut Vec<McOpfShunt>,
281) {
282    let TransformerProfile {
283        t,
284        phases,
285        zb,
286        core,
287        ..
288    } = *profile;
289    if let Some(core) = core {
290        for k in 0..phases {
291            stamp_shunt(
292                shunts,
293                format!("transformer:{}:core:{k}", t.name),
294                &tx.coils[core.winding * phases + k],
295                core.admittance.re * zb,
296                core.admittance.im * zb,
297            );
298        }
299    }
300}
301
302fn prepare_tap(
303    profile: &TransformerProfile<'_>,
304    noms: &[f64],
305    tx: &mut McOpfTransformer,
306) -> Result<()> {
307    let TransformerProfile {
308        t, nw, regulator, ..
309    } = *profile;
310    if regulator && (t.extras.contains_key("tap_min") || t.extras.contains_key("tap_max")) {
311        return Err(unsupported(
312            &t.name,
313            "regulators require tap_ratio_min/max, not ordinary transformer tap_min/max",
314        ));
315    }
316    let keys = if regulator {
317        ["tap_ratio_min", "tap_ratio_max"]
318    } else {
319        ["tap_min", "tap_max"]
320    };
321    if t.extras.contains_key(keys[0]) || t.extras.contains_key(keys[1]) {
322        if nw {
323            return Err(unsupported(
324                &t.name,
325                "n-winding tap optimization is not supported by the reference engine",
326            ));
327        }
328        let read = |key: &str| -> Result<f64> {
329            let v = t
330                .extras
331                .get(key)
332                .ok_or_else(|| invalid(&t.name, "tap requires both bounds"))?;
333            let v = if let Some(meta) = t.extras.get("bmopf_open_delta") {
334                v.get(
335                    meta["leg"]
336                        .as_u64()
337                        .ok_or_else(|| invalid(&t.name, "missing tap leg"))?
338                        as usize,
339                )
340                .unwrap_or(v)
341            } else {
342                v
343            };
344            let value = v
345                .as_f64()
346                .ok_or_else(|| invalid(&t.name, "invalid tap bound"))?;
347            finite(&t.name, &[value])?;
348            Ok(value)
349        };
350        let lo = read(keys[0])?;
351        let hi = read(keys[1])?;
352        if lo <= 0.0 || lo >= hi {
353            return Err(invalid(
354                &t.name,
355                "tap bounds must be positive and strictly ordered",
356            ));
357        }
358        tx.tap_nominal = if regulator {
359            t.windings[1].tap
360        } else {
361            t.windings[0].tap
362        };
363        // A regulator's `tap_ratio` is the regulated over source voltage ratio
364        // for both ANSI types; `regulator_type` records the hardware only.
365        tx.tap_inverse = regulator;
366        let [a, b] = [tx.calc_tap_multiplier(lo), tx.calc_tap_multiplier(hi)];
367        tx.tap_bounds = Some([a.min(b), a.max(b)]);
368        tap_equations(profile, noms, tx)?;
369    }
370    Ok(())
371}
372
373fn prepare_ports(
374    profile: &TransformerProfile<'_>,
375    ctx: &Context<'_>,
376    maps: &[super::CoilPairs],
377    tx: &mut McOpfTransformer,
378    shunts: &mut Vec<McOpfShunt>,
379    terminals: &[McOpfTerminal],
380) -> Result<()> {
381    let TransformerProfile {
382        t,
383        subtype,
384        nw,
385        phases,
386        zb,
387        ib,
388        sb,
389        core,
390        ..
391    } = *profile;
392    // A rated port on the magnetized winding carries the per unit core
393    // admittance of its coil.
394    let core_on = |winding: usize| -> [f64; 2] {
395        core.filter(|core| core.winding == winding)
396            .map_or([0.0, 0.0], |core| {
397                [core.admittance.re * zb, core.admittance.im * zb]
398            })
399    };
400    for (j, w) in t.windings.iter().enumerate() {
401        let meta = t
402            .extras
403            .get("bmopf_winding_metadata")
404            .and_then(|v| v.get(j.to_string()));
405        if let Some(meta) = meta {
406            let obj = meta
407                .as_object()
408                .ok_or_else(|| invalid(&t.name, "winding metadata must be an object"))?;
409            for key in obj.keys() {
410                if !["i_max", "s_max"].contains(&key.as_str()) {
411                    return Err(unsupported(&t.name, format!("winding field {key}")));
412                }
413            }
414        }
415        let imax = if nw {
416            meta.and_then(|v| v.get("i_max"))
417                .map(|v| {
418                    v.as_f64()
419                        .ok_or_else(|| invalid(&t.name, "invalid winding current cap"))
420                })
421                .transpose()?
422                .map(|v| vec![v; phases])
423        } else {
424            extra_vector(t, if j == 0 { "i_max_from" } else { "i_max_to" })?
425        };
426        // Native Yd/Dy current ratings apply to terminal line currents; n-winding ratings to coils.
427        let (imax, neutral_cap) = terminal_current_ratings(profile, ctx, &maps[j], j, imax)?;
428        if let Some(cap) = neutral_cap {
429            neutral_port(profile, tx, &maps[j], j, core_on(1), cap)?;
430        }
431        let imax = caps(&t.name, imax.as_ref(), phases, ib)?;
432        let rating = if nw {
433            meta.and_then(|v| v.get("s_max"))
434                .map(|v| {
435                    v.as_f64()
436                        .ok_or_else(|| invalid(&t.name, "invalid winding apparent-power rating"))
437                })
438                .transpose()?
439        } else if j == usize::from(subtype == "delta_wye") {
440            Some(w.s_rating)
441        } else {
442            None
443        };
444        let smax = caps(
445            &t.name,
446            rating.map(|v| vec![v / (phases as f64); phases]).as_ref(),
447            phases,
448            sb,
449        )?;
450        let magnetized = usize::from(subtype != "single_phase_autotransformer");
451        phase_ports(profile, tx, j, &imax, &smax, core_on(magnetized));
452        grounding(profile, &maps[j], j, shunts, terminals)?;
453    }
454    Ok(())
455}
456
457/// Each winding's coils over global terminals, from the one winding
458/// connection ([`calc_winding_connection`], which orients DELTA rings), and
459/// its coil turns ([`calc_coil_voltage`] times tap).
460#[allow(clippy::float_cmp)] // Tap=1 is an exact schema sentinel, not a numerical tolerance.
461fn winding_geometry(
462    ctx: &Context<'_>,
463    t: &powerio_dist::DistTransformer,
464    subtype: &str,
465) -> Result<WindingGeometry> {
466    let mut maps = Vec::new();
467    let mut noms = Vec::new();
468    for (j, w) in t.windings.iter().enumerate() {
469        finite(&t.name, &[w.v_ref, w.s_rating, w.r_pct, w.tap])?;
470        if w.v_ref <= 0.0 || w.s_rating <= 0.0 || w.tap <= 0.0 || w.r_pct < 0.0 {
471            return Err(invalid(&t.name, "invalid winding nameplate/tap"));
472        }
473        if subtype == "n_winding" && w.tap != 1.0 {
474            return Err(unsupported(
475                &t.name,
476                "n-winding tap fields are not supported by BMOPFTools",
477            ));
478        }
479        let ids = ctx.resolve(&t.name, &w.bus, &w.terminal_map)?;
480        if w.conn == DistWindingConn::Delta {
481            ctx.require_phase_terminals(&t.name, &w.bus, &w.terminal_map)?;
482        }
483        let pairs: super::CoilPairs = calc_winding_connection(ctx.net, t, j)
484            .map_err(|error| invalid(&t.name, error))?
485            .iter()
486            .map(|coil| (ids[coil.from], coil.to.map(|to| ids[to])))
487            .collect();
488        if pairs.is_empty() {
489            return Err(invalid(&t.name, "no coils"));
490        }
491        noms.push(calc_coil_voltage(t, j) * w.tap);
492        maps.push(pairs);
493    }
494    Ok((maps, noms))
495}
496
497fn prepare_regulator(
498    ctx: &Context<'_>,
499    t: &powerio_dist::DistTransformer,
500    maps: &[super::CoilPairs],
501    noms: &mut Vec<f64>,
502    branches: &mut Vec<McOpfBranch>,
503    terminals: &[McOpfTerminal],
504) -> Result<()> {
505    let m = t.windings.len();
506    let phases = maps[0].len();
507    if m != 2 || phases != 1 {
508        return Err(invalid(&t.name, "regulator must have two single coils"));
509    }
510    let tap = t.windings[1].tap;
511    // `tap_ratio` is V_to/V_from for both ANSI types (BMOPF);
512    // `regulator_type` records the A/B hardware and does not change it.
513    if !matches!(
514        t.extras
515            .get("regulator_type")
516            .and_then(serde_json::Value::as_str)
517            .unwrap_or("B"),
518        "A" | "B"
519    ) {
520        return Err(invalid(&t.name, "unknown regulator type"));
521    }
522    let ratio = 1.0 / tap;
523    if ratio <= 0.0 {
524        return Err(invalid(&t.name, "nonpositive effective regulator ratio"));
525    }
526    *noms = vec![ratio, 1.0];
527    let bond = if let Some(meta) = t.extras.get("bmopf_open_delta") {
528        let k = meta["shared"]
529            .as_u64()
530            .ok_or_else(|| invalid(&t.name, "missing regulator shared phase"))?
531            .checked_sub(1)
532            .and_then(|v| usize::try_from(v).ok())
533            .ok_or_else(|| invalid(&t.name, "invalid shared phase index"))?;
534        let get = |side: &str, j: usize| -> Result<usize> {
535            let label = meta[side]
536                .get(k)
537                .and_then(serde_json::Value::as_str)
538                .ok_or_else(|| invalid(&t.name, "invalid regulator terminal map"))?;
539            Ok(ctx.resolve(&t.name, &t.windings[j].bus, &[label.to_owned()])?[0])
540        };
541        (Some(get("from", 0)?), Some(get("to", 1)?))
542    } else {
543        (maps[0][0].1, maps[1][0].1)
544    };
545    if let (Some(a), Some(b)) = bond
546        && !(terminals[a].grounded && terminals[b].grounded)
547        && !branches.iter().any(|br| {
548            br.from == [a] && br.to == [b] && br.identity.starts_with("transformer-bond:")
549        })
550    {
551        let z = vec![vec![0.0]];
552        branches.push(McOpfBranch {
553            identity: format!("transformer-bond:{}", t.name),
554            from: vec![a],
555            to: vec![b],
556            r: z.clone(),
557            x: z.clone(),
558            g_from: z.clone(),
559            b_from: z.clone(),
560            g_to: z.clone(),
561            b_to: z,
562            current_max: vec![None],
563            apparent_max: vec![None],
564            open: false,
565        });
566    }
567    Ok(())
568}
569
570fn leakage_descriptor(
571    profile: &TransformerProfile<'_>,
572    maps: &[super::CoilPairs],
573    noms: &[f64],
574) -> Result<McOpfTransformer> {
575    let TransformerProfile {
576        t,
577        nw,
578        regulator,
579        phases,
580        zb,
581        ..
582    } = *profile;
583    let m = t.windings.len();
584    let ratios: Vec<_> = noms.iter().map(|n| n / noms[0]).collect();
585    // The first winding's coil impedance base: its coil voltage squared over
586    // its per phase power base, the one winding impedance base.
587    let power_base = extra_number(t, "bmopf_power_base", t.windings[0].s_rating)?;
588    let ref_base = calc_winding_impedance_base(t, 0, power_base)
589        .ok_or_else(|| invalid(&t.name, "nonpositive transformer power base"))?;
590    // The pairwise leakage is the one derivation in
591    // `calc_transformer_leakage_impedances`, referred to the first winding on
592    // the base the unit states it in: OpenDSS nameplate percentages, an
593    // n-winding BMOPF unit's phase bases, or a regulator's stated ohms. A
594    // per unit result scales to the first winding's ohmic base over the bus
595    // base; stated ohms divide by the bus base.
596    let base = if regulator {
597        TransformerLeakageBase::StatedOhms
598    } else if nw {
599        TransformerLeakageBase::WindingPhase {
600            power_base,
601            phases: t
602                .windings
603                .iter()
604                .map(|w| calc_winding_phase_count(w.conn, &w.terminal_map) as f64)
605                .collect(),
606        }
607    } else {
608        TransformerLeakageBase::Nameplate
609    };
610    let leakage =
611        calc_transformer_leakage_impedances(t, &base).map_err(|error| invalid(&t.name, error))?;
612    let scale = ref_base * t.windings[0].tap.powi(2) / zb;
613    let per_unit: Vec<Vec<Complex64>> = leakage
614        .iter()
615        .map(|row| {
616            row.iter()
617                .map(|z| {
618                    if regulator {
619                        Complex64::new(z.re / zb, z.im / zb)
620                    } else {
621                        Complex64::new(z.re * scale, z.im * scale)
622                    }
623                })
624                .collect()
625        })
626        .collect();
627    // The winding difference impedances against the first winding, kept in
628    // impedance form: row `a - 1` is winding `a` less winding one.
629    let reduced = calc_reduced_leakage(&per_unit, 0);
630    let mut tx = McOpfTransformer {
631        identity: t.name.clone(),
632        coils: Vec::new(),
633        equations: Vec::new(),
634        ports: Vec::new(),
635        tap_bounds: None,
636        tap_nominal: 1.0,
637        tap_inverse: false,
638        tap_equations: Vec::new(),
639    };
640    for map in maps {
641        for &(positive, negative) in map {
642            tx.coils.push(McOpfTransformerCoil { positive, negative });
643        }
644    }
645    for k in 0..phases {
646        let mut balance = McOpfComplexRow::default();
647        for (j, &ratio) in ratios.iter().enumerate() {
648            balance.current.push((j * phases + k, [ratio, 0.0]));
649        }
650        tx.equations.push(balance);
651        for a in 1..m {
652            let mut row = McOpfComplexRow::default();
653            add_voltage(&mut row, &tx.coils[k], 1.0);
654            add_voltage(&mut row, &tx.coils[a * phases + k], -1.0 / ratios[a]);
655            for b in 1..m {
656                let z = reduced[a - 1][b - 1];
657                row.current
658                    .push((b * phases + k, [z.re * ratios[b], z.im * ratios[b]]));
659            }
660            tx.equations.push(row);
661        }
662    }
663    Ok(tx)
664}
665
666/// A winding's neutral grounding ([`calc_winding_neutral_grounding`]) at the
667/// neutral its coils return through: a finite impedance is a per unit shunt
668/// to ground, a solid grounding must land on a terminal the network already
669/// grounds (the descriptor states no extra exact zero voltage), and an
670/// unstated or floating neutral adds nothing.
671fn grounding(
672    profile: &TransformerProfile<'_>,
673    map: &super::CoilPairs,
674    j: usize,
675    shunts: &mut Vec<McOpfShunt>,
676    terminals: &[McOpfTerminal],
677) -> Result<()> {
678    let TransformerProfile { t, zb, .. } = *profile;
679    let grounding =
680        calc_winding_neutral_grounding(t, j).map_err(|error| unsupported(&t.name, error))?;
681    let neutral = || {
682        map[0]
683            .1
684            .ok_or_else(|| invalid(&t.name, "neutral impedance without neutral"))
685    };
686    match grounding {
687        WindingNeutralGrounding::Impedance(y) => stamp_shunt(
688            shunts,
689            format!("transformer:{}:neutral:{j}", t.name),
690            &McOpfTransformerCoil {
691                positive: neutral()?,
692                negative: None,
693            },
694            y.re * zb,
695            y.im * zb,
696        ),
697        WindingNeutralGrounding::Solid if !terminals[neutral()?].grounded => {
698            return Err(unsupported(
699                &t.name,
700                "a solidly grounded winding neutral on a terminal the network does not ground needs an exact zero voltage",
701            ));
702        }
703        _ => {}
704    }
705    Ok(())
706}
707
708fn phase_ports(
709    profile: &TransformerProfile<'_>,
710    tx: &mut McOpfTransformer,
711    j: usize,
712    imax: &[Option<f64>],
713    smax: &[Option<f64>],
714    core: [f64; 2],
715) {
716    let TransformerProfile {
717        t,
718        subtype,
719        nw,
720        phases,
721        ..
722    } = *profile;
723    let [g, b] = core;
724    let delta_terminal = !nw && t.windings[j].conn == DistWindingConn::Delta;
725    for k in 0..phases {
726        let coil = &tx.coils[j * phases + k];
727        let mut current = McOpfComplexRow::default();
728        current.current.push((j * phases + k, [1.0, 0.0]));
729        if delta_terminal {
730            current.current.clear();
731            for q in 0..phases {
732                let c = &tx.coils[j * phases + q];
733                if c.positive == coil.positive {
734                    current.current.push((j * phases + q, [1.0, 0.0]));
735                }
736                if c.negative == Some(coil.positive) {
737                    current.current.push((j * phases + q, [-1.0, 0.0]));
738                }
739            }
740        }
741        // Through-power uses bare winding current. YY output and single-phase
742        // regulator input current ratings include the exciting current.
743        let apparent_current = current.clone();
744        let magnetized = (matches!(subtype, "single_phase" | "center_tap") && j == 1)
745            || (subtype == "single_phase_autotransformer" && j == 0);
746        if magnetized {
747            current.voltage.push((coil.positive, [g, b]));
748            if let Some(n) = coil.negative {
749                current.voltage.push((n, [-g, -b]));
750            }
751        }
752        tx.ports.push(McOpfTransformerPort {
753            name: format!("w{j}:{k}"),
754            positive: coil.positive,
755            negative: coil.negative,
756            current,
757            current_max: imax[k],
758            apparent_max: if magnetized { None } else { smax[k] },
759        });
760        if magnetized && smax[k].is_some() {
761            tx.ports.push(McOpfTransformerPort {
762                name: format!("w{j}:{k}:through"),
763                positive: coil.positive,
764                negative: coil.negative,
765                current: apparent_current,
766                current_max: None,
767                apparent_max: smax[k],
768            });
769        }
770    }
771}
772
773fn neutral_port(
774    profile: &TransformerProfile<'_>,
775    tx: &mut McOpfTransformer,
776    map: &super::CoilPairs,
777    j: usize,
778    core: [f64; 2],
779    cap: f64,
780) -> Result<()> {
781    let TransformerProfile {
782        t, subtype, phases, ..
783    } = *profile;
784    let [g, b] = core;
785    let neutral = map[0]
786        .1
787        .ok_or_else(|| invalid(&t.name, "neutral cap without neutral"))?;
788    let mut current = McOpfComplexRow::default();
789    if subtype == "center_tap" {
790        current.current = vec![(1, [-1.0, 0.0]), (2, [1.0, 0.0])];
791        current.voltage.push((tx.coils[1].positive, [-g, -b]));
792        current.voltage.push((neutral, [g, b]));
793    } else {
794        current.current = (0..phases).map(|k| (j * phases + k, [-1.0, 0.0])).collect();
795    }
796    tx.ports.push(McOpfTransformerPort {
797        name: format!("w{j}:neutral"),
798        positive: neutral,
799        negative: None,
800        current,
801        current_max: Some(cap),
802        apparent_max: None,
803    });
804    Ok(())
805}
806
807fn terminal_current_ratings(
808    profile: &TransformerProfile<'_>,
809    ctx: &Context<'_>,
810    map: &super::CoilPairs,
811    j: usize,
812    imax: Option<Vec<f64>>,
813) -> Result<TerminalRatings> {
814    let TransformerProfile {
815        t,
816        subtype,
817        phases,
818        ib,
819        ..
820    } = *profile;
821    let w = &t.windings[j];
822    let imax = if let Some(meta) = t.extras.get("bmopf_open_delta") {
823        let leg = meta["leg"]
824            .as_u64()
825            .ok_or_else(|| invalid(&t.name, "missing regulator leg"))? as usize;
826        imax.map(|v| {
827            v.get(leg)
828                .copied()
829                .map(|x| vec![x])
830                .ok_or_else(|| invalid(&t.name, "regulator current count"))
831        })
832        .transpose()?
833    } else {
834        imax
835    };
836    let mut neutral_cap = None;
837    let imax = if subtype == "center_tap" {
838        imax.map(|v| {
839            if v.iter().any(|x| x.is_nan() || *x < 0.0) {
840                return Err(invalid(&t.name, "invalid center-tap current rating"));
841            }
842            if j == 0 {
843                if v.len() != 1 && v.len() != 2 {
844                    return Err(invalid(
845                        &t.name,
846                        "center-tap primary rating needs one or two currents",
847                    ));
848                }
849                Ok(vec![v.iter().copied().fold(f64::INFINITY, f64::min)])
850            } else {
851                if v.len() != 3 {
852                    return Err(invalid(
853                        &t.name,
854                        "center-tap secondary requires three terminal ratings",
855                    ));
856                }
857                if j == 1 {
858                    neutral_cap = caps(&t.name, Some(&vec![v[1]]), 1, ib)?[0];
859                }
860                Ok(vec![v[if j == 1 { 0 } else { 2 }]])
861            }
862        })
863        .transpose()?
864    } else if matches!(subtype, "wye_delta" | "delta_wye") && w.conn == DistWindingConn::Wye {
865        imax.map(|v| {
866            if v.len() == phases {
867                return Ok(v);
868            }
869            let ids = ctx.resolve(&t.name, &w.bus, &w.terminal_map)?;
870            if v.len() != ids.len() || ids.len() != phases + 1 {
871                return Err(invalid(&t.name, "wye terminal rating shape"));
872            }
873            let neutral = map[0]
874                .1
875                .ok_or_else(|| invalid(&t.name, "missing rated neutral"))?;
876            let n = ids
877                .iter()
878                .position(|id| *id == neutral)
879                .ok_or_else(|| invalid(&t.name, "missing rated neutral"))?;
880            neutral_cap = caps(&t.name, Some(&vec![v[n]]), 1, ib)?[0];
881            map.iter()
882                .map(|(pos, _)| {
883                    ids.iter()
884                        .position(|id| id == pos)
885                        .map(|k| v[k])
886                        .ok_or_else(|| invalid(&t.name, "missing rated phase"))
887                })
888                .collect()
889        })
890        .transpose()?
891    } else {
892        imax
893    };
894    Ok((imax, neutral_cap))
895}
896
897fn tap_equations(
898    profile: &TransformerProfile<'_>,
899    noms: &[f64],
900    tx: &mut McOpfTransformer,
901) -> Result<()> {
902    let TransformerProfile {
903        t, regulator, zb, ..
904    } = *profile;
905    if regulator {
906        let [r_from, x_from, r_to, x_to] =
907            calc_regulator_series_ohms(t).map_err(|error| invalid(&t.name, error))?;
908        let ratio = noms[0] / noms[1];
909        let mut balance = McOpfComplexRow::default();
910        balance.current.push((1, [1.0, 0.0]));
911        let mut dynamic_balance = McOpfComplexRow::default();
912        dynamic_balance.current.push((0, [ratio, 0.0]));
913        let mut drop = McOpfComplexRow::default();
914        add_voltage(&mut drop, &tx.coils[0], 1.0);
915        drop.current.push((0, [-r_from / zb, -x_from / zb]));
916        let mut dynamic_drop = McOpfComplexRow::default();
917        add_voltage(&mut dynamic_drop, &tx.coils[1], -ratio);
918        dynamic_drop
919            .current
920            .push((1, [ratio * r_to / zb, ratio * x_to / zb]));
921        tx.equations = vec![balance, drop];
922        tx.tap_equations = vec![dynamic_balance, dynamic_drop];
923    } else {
924        for row in &mut tx.equations {
925            let mut dynamic = McOpfComplexRow::default();
926            if row.voltage.is_empty() {
927                dynamic.current.push(row.current.remove(0));
928            } else {
929                let count = 1 + usize::from(tx.coils[0].negative.is_some());
930                dynamic.voltage = row.voltage.split_off(count);
931                dynamic.current = std::mem::take(&mut row.current);
932            }
933            tx.tap_equations.push(dynamic);
934        }
935    }
936    Ok(())
937}
938
939/// Transformer extras the preparation interprets.
940pub(super) const INTERPRETED_EXTRAS: &[&str] = &[
941    "tap_min",
942    "tap_max",
943    "tap_ratio_min",
944    "tap_ratio_max",
945    "bmopf_open_delta",
946    "bmopf_subtype",
947    "bmopf_power_base",
948    "bmopf_winding_metadata",
949    "bmopf_delta_rolls",
950    "no_load_shunt",
951    "g_no_load",
952    "b_no_load",
953    "%noloadloss",
954    "%imag",
955    "leadlag",
956    "i_max_from",
957    "i_max_to",
958    "regulator_type",
959    "r_series_from",
960    "r_series_to",
961    "x_series_from",
962    "x_series_to",
963];
964
965fn validate_extras(t: &powerio_dist::DistTransformer) -> Result<()> {
966    extras(&t.name, &t.extras, INTERPRETED_EXTRAS)
967}
968
969// Canonical two-terminal delta nameplates use a single-coil base even though
970// BMOPFTools n-winding incidence retains both directed delta currents.