Skip to main content

powerio_dist/
transformer.rs

1//! Transformer winding physics: the pairwise leakage and its reduction, each
2//! winding's coil voltage, connection and delta orientation, the neutral
3//! grounding and magnetizing branch a unit states, and the finite leakage
4//! primitive admittance over its physical terminals.
5//!
6//! Every multiconductor calculation reads its transformer quantities here:
7//! the nodal admittance and its ideal constraints, the multiconductor OPF
8//! descriptor, the multiconductor to balanced lowering and the SINCAL
9//! writer's expected primitive.
10
11use std::collections::BTreeMap;
12
13use num_complex::Complex64;
14
15use crate::diagnostics::codes;
16use crate::{
17    Configuration, ConnectionChannel, DistTransformer, DistWinding, DistWindingConn,
18    MulticonductorNetwork, calc_element_connection, orient_delta_ring,
19};
20
21type Result<T> = std::result::Result<T, powerio_core::Error>;
22
23fn unsupported(name: &str, reason: impl std::fmt::Display) -> powerio_core::Error {
24    powerio_core::Error::new(
25        &codes::BUILD_DIST_TRANSFORMER_UNSUPPORTED,
26        format!("transformer `{name}` is unsupported: {reason}"),
27    )
28}
29
30fn invalid(
31    name: &str,
32    field: impl std::fmt::Display,
33    reason: impl std::fmt::Display,
34) -> powerio_core::Error {
35    powerio_core::Error::new(
36        &codes::BUILD_DIST_TRANSFORMER_INVALID,
37        format!("transformer `{name}` has invalid {field}: {reason}"),
38    )
39}
40
41fn invalid_leakage(transformer: &DistTransformer, reason: &str) -> powerio_core::Error {
42    invalid(&transformer.name, "leakage data", reason)
43}
44
45/// A transformer extra as a number: typed producers write numbers and the
46/// DSS reader keeps written extras as text. A present value that is neither
47/// reads as NaN, so it reaches the caller's finite value checks rather than
48/// becoming an omitted zero. The one reader of a transformer's numeric
49/// extras.
50#[must_use]
51pub fn transformer_extra_number(
52    extras: &BTreeMap<String, serde_json::Value>,
53    key: &str,
54) -> Option<f64> {
55    extras.get(key).map(|value| {
56        value
57            .as_f64()
58            .or_else(|| value.as_str()?.trim().parse().ok())
59            .unwrap_or(f64::NAN)
60    })
61}
62
63fn subtype(transformer: &DistTransformer) -> Option<&str> {
64    transformer
65        .extras
66        .get("bmopf_subtype")
67        .and_then(serde_json::Value::as_str)
68}
69
70// DSS regulator classification keeps nameplate percentage leakage. The BMOPF
71// subtype alone does not convert that data to its separate stated-ohm model.
72// Present malformed ohm fields still choose that model and reach its checks.
73fn uses_autotransformer_impedance(transformer: &DistTransformer) -> bool {
74    subtype(transformer) == Some("single_phase_autotransformer")
75        && (transformer.xsc_pct.is_empty()
76            || [
77                "r_series_from",
78                "x_series_from",
79                "r_series_to",
80                "x_series_to",
81            ]
82            .iter()
83            .any(|key| transformer.extras.contains_key(*key)))
84}
85
86/// Whether the unit is a BMOPF regulator (a single phase autotransformer or
87/// an open delta regulator leg), whose tap is the regulated over source
88/// voltage ratio.
89#[must_use]
90pub fn is_transformer_regulator(transformer: &DistTransformer) -> bool {
91    matches!(
92        subtype(transformer),
93        Some("single_phase_autotransformer" | "open_delta_regulator")
94    )
95}
96
97/// The unit system a transformer states its leakage in, which
98/// [`calc_transformer_leakage_impedances`] reads.
99///
100/// The physical quantity is the same in every case: for windings `a` and
101/// `b`, the series impedance of the pair referred to the first winding,
102/// each winding's own resistance referred through its base and the pair's
103/// short circuit reactance. Only the base each value is stated on differs.
104#[derive(Clone, Debug, PartialEq)]
105#[non_exhaustive]
106pub enum TransformerLeakageBase {
107    /// OpenDSS nameplate data: each winding's `r_pct` on its own rating
108    /// `S_a`, and `xsc_pct` on the first winding's rating. The result is per
109    /// unit on `S_1`.
110    Nameplate,
111    /// BMOPF n-winding data: each winding's `r_pct` on its phase base
112    /// `S_a / phases[a]`, and `xsc_pct` on `power_base / phases[0]`. The
113    /// result is per unit on `power_base / phases[0]`.
114    WindingPhase {
115        /// The pair reactance's power base, volt amperes (`bmopf_power_base`,
116        /// the first winding's rating when the source states none).
117        power_base: f64,
118        /// Each winding's phase count, in winding order.
119        phases: Vec<f64>,
120    },
121    /// A two winding regulator stating its series impedance in ohms on each
122    /// side (`r_series_from`, `x_series_from`, `r_series_to`, `x_series_to`
123    /// in the extras), with the second winding's `tap` its regulated over
124    /// source voltage ratio. The second side is referred through
125    /// `n = 1 / tap`, and the result is ohms on the first side:
126    /// `z = (r_from + n² r_to) + j (x_from + n² x_to)`.
127    StatedOhms,
128}
129
130/// The pairwise leakage impedances of a multiwinding transformer, referred
131/// to the first winding: for windings `a` and `b`, on a per winding base
132/// `B_a` and a reference base `B_ref`,
133///
134/// ```text
135/// z[a][b] = (r_a · B_ref / B_a + r_b · B_ref / B_b) / 100 + j · xsc_ab / 100
136/// ```
137///
138/// with `xsc_pct` in pair order `(1,2), (1,3), …, (2,3), …`. The
139/// [`TransformerLeakageBase`] states `B_a` and `B_ref` (the winding rating
140/// and the first winding's rating for [`TransformerLeakageBase::Nameplate`],
141/// the phase bases for [`TransformerLeakageBase::WindingPhase`]), or reads a
142/// regulator's stated ohms ([`TransformerLeakageBase::StatedOhms`]). The
143/// diagonal is zero. The one leakage derivation: the multiconductor OPF
144/// transformer descriptor scales it to its ohmic base,
145/// [`calc_transformer_winding_admittance`] inverts it,
146/// [`calc_transformer_primitive_admittance`] stamps it, and the
147/// multiconductor to balanced lowering reads a two winding unit's pair.
148///
149/// # Errors
150/// Fewer than two windings, a winding rating that is not finite and
151/// positive, a resistance that is not finite, or an `xsc_pct` whose length is
152/// not one value per winding pair. For a phase base, a power base that is not
153/// finite and positive or a phase count per winding that is missing or not
154/// finite and positive. For stated ohms, a transformer without exactly two
155/// windings, a second winding tap that is not finite and positive, or a
156/// stated value that is not a finite nonnegative number.
157pub fn calc_transformer_leakage_impedances(
158    transformer: &DistTransformer,
159    base: &TransformerLeakageBase,
160) -> Result<Vec<Vec<Complex64>>> {
161    let windings = &transformer.windings;
162    let count = windings.len();
163    if count < 2 {
164        return Err(invalid_leakage(transformer, "fewer than two windings"));
165    }
166    if let TransformerLeakageBase::StatedOhms = base {
167        return stated_ohms_leakage(transformer);
168    }
169    if windings
170        .iter()
171        .any(|w| !w.s_rating.is_finite() || w.s_rating <= 0.0 || !w.r_pct.is_finite())
172    {
173        return Err(invalid_leakage(
174            transformer,
175            "a winding rating is not finite and positive or a resistance is not finite",
176        ));
177    }
178    if transformer.xsc_pct.len() != count * (count - 1) / 2 {
179        return Err(invalid_leakage(
180            transformer,
181            "xsc_pct does not state one reactance per winding pair",
182        ));
183    }
184    let (reference_rating, winding_base): (f64, Vec<f64>) = match base {
185        TransformerLeakageBase::WindingPhase { power_base, phases } => {
186            if !power_base.is_finite() || *power_base <= 0.0 {
187                return Err(invalid_leakage(
188                    transformer,
189                    "the power base is not finite and positive",
190                ));
191            }
192            if phases.len() != count || phases.iter().any(|p| !p.is_finite() || *p <= 0.0) {
193                return Err(invalid_leakage(
194                    transformer,
195                    "a winding phase count is missing or not finite and positive",
196                ));
197            }
198            (
199                power_base / phases[0],
200                windings
201                    .iter()
202                    .zip(phases)
203                    .map(|(w, p)| w.s_rating / p)
204                    .collect(),
205            )
206        }
207        _ => (
208            windings[0].s_rating,
209            windings.iter().map(|w| w.s_rating).collect(),
210        ),
211    };
212    let resistance: Vec<f64> = windings
213        .iter()
214        .zip(&winding_base)
215        .map(|(w, base)| w.r_pct / 100.0 * reference_rating / base)
216        .collect();
217    let mut impedance = vec![vec![Complex64::new(0.0, 0.0); count]; count];
218    let mut pair = 0;
219    for a in 0..count {
220        for b in a + 1..count {
221            let z = Complex64::new(
222                resistance[a] + resistance[b],
223                transformer.xsc_pct[pair] / 100.0,
224            );
225            impedance[a][b] = z;
226            impedance[b][a] = z;
227            pair += 1;
228        }
229    }
230    Ok(impedance)
231}
232
233/// [`TransformerLeakageBase::StatedOhms`]: a regulator's series impedance,
234/// ohms on the first side.
235fn stated_ohms_leakage(transformer: &DistTransformer) -> Result<Vec<Vec<Complex64>>> {
236    if transformer.windings.len() != 2 {
237        return Err(invalid_leakage(
238            transformer,
239            "a stated ohmic impedance needs exactly two windings",
240        ));
241    }
242    let tap = transformer.windings[1].tap;
243    if !tap.is_finite() || tap <= 0.0 {
244        return Err(invalid_leakage(
245            transformer,
246            "the regulated winding tap is not finite and positive",
247        ));
248    }
249    let n = 1.0 / tap;
250    let [r_from, x_from, r_to, x_to] = calc_regulator_series_ohms(transformer)?;
251    let z = Complex64::new(r_from + n.powi(2) * r_to, x_from + n.powi(2) * x_to);
252    let zero = Complex64::new(0.0, 0.0);
253    Ok(vec![vec![zero, z], vec![z, zero]])
254}
255
256/// A regulator's stated series impedance, ohms on each side:
257/// `[r_series_from, x_series_from, r_series_to, x_series_to]`, each zero
258/// when omitted. The one reading of these extras: the stated ohm leakage
259/// ([`TransformerLeakageBase::StatedOhms`]) and the multiconductor OPF tap
260/// rows read it.
261///
262/// # Errors
263/// A stated value that is not a finite nonnegative number.
264pub fn calc_regulator_series_ohms(transformer: &DistTransformer) -> Result<[f64; 4]> {
265    let read = |key: &str| -> Result<f64> {
266        let value = transformer_extra_number(&transformer.extras, key).unwrap_or(0.0);
267        if !value.is_finite() || value < 0.0 {
268            return Err(invalid_leakage(
269                transformer,
270                &format!("{key} must be finite and nonnegative"),
271            ));
272        }
273        Ok(value)
274    };
275    Ok([
276        read("r_series_from")?,
277        read("x_series_from")?,
278        read("r_series_to")?,
279        read("x_series_to")?,
280    ])
281}
282
283/// The pairwise leakage of [`calc_transformer_leakage_impedances`] reduced
284/// against the `reference` winding to the winding difference impedance
285/// matrix, over every other winding in winding order:
286///
287/// ```text
288/// ZB[i][j] = z[i][r]                          (i = j)
289///          = (z[i][r] + z[j][r] - z[i][j]) / 2  (i ≠ j)
290/// ```
291///
292/// Row `i` is the voltage of winding `i` less the reference winding's. The
293/// one reduction: [`calc_transformer_winding_admittance`] inverts it against
294/// the last winding, and the multiconductor OPF descriptor keeps it in
295/// impedance form against the first.
296///
297/// # Panics
298/// A `reference` outside the matrix.
299#[must_use]
300pub fn calc_reduced_leakage(leakage: &[Vec<Complex64>], reference: usize) -> Vec<Vec<Complex64>> {
301    assert!(reference < leakage.len(), "reference winding out of range");
302    let others: Vec<usize> = (0..leakage.len()).filter(|&w| w != reference).collect();
303    others
304        .iter()
305        .map(|&i| {
306            others
307                .iter()
308                .map(|&j| {
309                    if i == j {
310                        leakage[i][reference]
311                    } else {
312                        (leakage[i][reference] + leakage[j][reference] - leakage[i][j]) / 2.0
313                    }
314                })
315                .collect()
316        })
317        .collect()
318}
319
320/// The winding domain admittance `Y_1Volt` of a multiwinding transformer,
321/// siemens at a one volt winding base (OpenDSS `CalcY_Terminal`): the
322/// pairwise nameplate leakage impedances of
323/// [`calc_transformer_leakage_impedances`] scaled by `phases / S_1`, reduced
324/// against the last winding ([`calc_reduced_leakage`]), inverted, and lifted
325/// back through the winding difference incidence `A` (row `i` is
326/// `u_i - u_n`): `Y_1Volt = Aᵀ ZB⁻¹ A`. A two winding unit reduces to
327/// `y · [[1, -1], [-1, 1]]`. `None` when the reduced matrix is exactly
328/// singular or not finite: one volt base impedances of high rating units sit
329/// far below any fixed pivot threshold, so only exact singularity is
330/// refused.
331///
332/// # Errors
333/// The leakage data [`calc_transformer_leakage_impedances`] refuses, or a
334/// phase count of zero.
335pub fn calc_transformer_winding_admittance(
336    transformer: &DistTransformer,
337) -> Result<Option<Vec<Vec<Complex64>>>> {
338    let leakage =
339        calc_transformer_leakage_impedances(transformer, &TransformerLeakageBase::Nameplate)?;
340    if transformer.phases == 0 {
341        return Err(invalid_leakage(transformer, "zero phases"));
342    }
343    let count = leakage.len();
344    let reference = count - 1;
345    let base = transformer.phases as f64 / transformer.windings[0].s_rating;
346    let scaled: Vec<Vec<Complex64>> = leakage
347        .iter()
348        .map(|row| row.iter().map(|z| z * base).collect())
349        .collect();
350    let reduced = calc_reduced_leakage(&scaled, reference);
351    let finite = |value: &Complex64| value.re.is_finite() && value.im.is_finite();
352    if reduced.iter().flatten().any(|value| !finite(value)) {
353        return Ok(None);
354    }
355    let Some(inverse) =
356        crate::dense::invert_dense_matrix(&reduced, crate::dense::DensePivot::Partial, 0.0, 0.0)
357    else {
358        return Ok(None);
359    };
360    if inverse.iter().flatten().any(|value| !finite(value)) {
361        return Ok(None);
362    }
363    let mut admittance = vec![vec![Complex64::new(0.0, 0.0); count]; count];
364    for i in 0..reference {
365        for j in 0..reference {
366            let value = inverse[i][j];
367            admittance[i][j] += value;
368            admittance[i][reference] -= value;
369            admittance[reference][j] -= value;
370            admittance[reference][reference] += value;
371        }
372    }
373    Ok(Some(admittance))
374}
375
376/// The ratio of a winding's rated voltage (`v_ref`) to its coil voltage:
377/// `√3` for a WYE winding of a two or three phase unit (a line to line
378/// rating over a line to neutral coil), one otherwise. The BMOPF reader
379/// forms `v_ref` from a coil voltage `v_nom` with it, and
380/// [`calc_coil_voltage`] divides by it.
381#[must_use]
382pub fn calc_coil_voltage_ratio(conn: DistWindingConn, phases: usize) -> f64 {
383    if conn == DistWindingConn::Wye && matches!(phases, 2 | 3) {
384        crate::electrical::SQRT_3
385    } else {
386        1.0
387    }
388}
389
390/// A winding's coil voltage, volts: line to neutral (`v_ref / √3`) for a
391/// polyphase WYE winding, the rated voltage otherwise
392/// ([`calc_coil_voltage_ratio`] over the unit's phases). Times the winding's
393/// tap, it is the coil's turns in volts, the quantity every turns ratio of
394/// the unit is formed from, and the `v_nom` a BMOPF n-winding unit states.
395#[must_use]
396pub fn calc_coil_voltage(transformer: &DistTransformer, winding: usize) -> f64 {
397    let w = &transformer.windings[winding];
398    w.v_ref / calc_coil_voltage_ratio(w.conn, transformer.phases)
399}
400
401/// The number of phases a winding's per phase power base divides over: a
402/// WYE winding's terminals less its neutral (mapped last, as the BMOPF and
403/// OpenDSS readers state it), at least one; one for a two terminal DELTA
404/// winding (a single coil); one per terminal of a DELTA ring.
405#[must_use]
406pub fn calc_winding_phase_count(conn: DistWindingConn, terminal_map: &[String]) -> usize {
407    match conn {
408        DistWindingConn::Wye => terminal_map.len().saturating_sub(1).max(1),
409        DistWindingConn::Delta => {
410            if terminal_map.len() == 2 {
411                1
412            } else {
413                terminal_map.len().max(1)
414            }
415        }
416    }
417}
418
419/// A winding's impedance base, ohms: its coil voltage
420/// ([`calc_coil_voltage`]) squared over its per phase power
421/// `power / phases` ([`calc_winding_phase_count`]),
422/// [`powerio_core::electrical::calc_impedance_base`]. The base a BMOPF
423/// n-winding unit states its winding resistances (on the winding's rating)
424/// and pair reactances (on the unit's power base) on, and the multiconductor
425/// OPF descriptor's reference base. `None` for an unusable voltage or power.
426#[must_use]
427pub fn calc_winding_impedance_base(
428    transformer: &DistTransformer,
429    winding: usize,
430    power: f64,
431) -> Option<f64> {
432    let w = &transformer.windings[winding];
433    let phases = calc_winding_phase_count(w.conn, &w.terminal_map);
434    powerio_core::electrical::calc_impedance_base(
435        calc_coil_voltage(transformer, winding),
436        power / phases as f64,
437    )
438}
439
440/// Whether the source states the European convention (`leadlag` `lead` or
441/// `euro`, OpenDSS's `LeadLag`): the low voltage winding leads the high
442/// voltage winding (Dy11). The default, `lag` or `ansi`, has the high
443/// voltage winding leading (Dy1).
444fn low_voltage_leads(transformer: &DistTransformer) -> Result<bool> {
445    let Some(value) = transformer.extras.get("leadlag") else {
446        return Ok(false);
447    };
448    match value.as_str().map(str::to_ascii_lowercase).as_deref() {
449        Some("lead" | "euro") => Ok(true),
450        Some("lag" | "ansi") => Ok(false),
451        _ => Err(invalid(
452            &transformer.name,
453            "leadlag",
454            "expected lead, lag, ansi or euro",
455        )),
456    }
457}
458
459/// The orientation of a DELTA winding's coil ring, `+1` (phase `k` to phase
460/// `k + 1`) or `-1` (phase `k` to phase `k - 1`):
461///
462/// - a stated BMOPF roll (`bmopf_delta_rolls`, one based winding keys);
463/// - otherwise `+1` for a BMOPF n-winding unit (BMOPFTools' schema
464///   default), `+1` for `wye_delta` and `-1` for `delta_wye`;
465/// - otherwise OpenDSS's rule over the first two windings: `+1` when they
466///   share a connection, else `-1` exactly when the high voltage winding is
467///   DELTA with the high voltage winding leading (the default) or WYE with
468///   the low voltage winding leading (`leadlag` `lead` or `euro`).
469///
470/// The one delta orientation: the transformer primitive, the multiconductor
471/// OPF descriptor, the connection phase shift
472/// ([`calc_transformer_phase_shift`]) and the SINCAL writer read it.
473///
474/// # Errors
475/// A stated roll that is not `+1` or `-1`, a `bmopf_delta_rolls` that is
476/// not an object, or an unknown `leadlag` convention.
477pub fn calc_delta_direction(transformer: &DistTransformer, winding: usize) -> Result<i8> {
478    if let Some(rolls) = transformer.extras.get("bmopf_delta_rolls") {
479        let rolls = rolls
480            .as_object()
481            .ok_or_else(|| invalid(&transformer.name, "bmopf_delta_rolls", "must be an object"))?;
482        if let Some(roll) = rolls.get(&(winding + 1).to_string()) {
483            return match roll.as_i64() {
484                Some(1) => Ok(1),
485                Some(-1) => Ok(-1),
486                _ => Err(invalid(
487                    &transformer.name,
488                    "bmopf_delta_rolls",
489                    "a delta roll must be +1 or -1",
490                )),
491            };
492        }
493    }
494    match subtype(transformer) {
495        Some("n_winding" | "wye_delta") => return Ok(1),
496        Some("delta_wye") => return Ok(-1),
497        _ => {}
498    }
499    let lv_leads = low_voltage_leads(transformer)?;
500    let [a, b, ..] = transformer.windings.as_slice() else {
501        return Ok(1);
502    };
503    if a.conn == b.conn {
504        return Ok(1);
505    }
506    let hv = if a.v_ref >= b.v_ref { a } else { b };
507    Ok(match (hv.conn, lv_leads) {
508        (DistWindingConn::Delta, false) | (DistWindingConn::Wye, true) => -1,
509        _ => 1,
510    })
511}
512
513/// The positive sequence phase shift of a two winding unit, degrees: the
514/// angle by which the first winding's voltage leads the second's
515/// (`calc_winding_phase_shift` of winding 1).
516///
517/// # Errors
518/// Fewer than two windings, or what [`calc_delta_direction`] refuses.
519pub fn calc_transformer_phase_shift(transformer: &DistTransformer) -> Result<f64> {
520    if transformer.windings.len() < 2 {
521        return Err(unsupported(
522            &transformer.name,
523            "a phase shift needs two windings",
524        ));
525    }
526    calc_winding_phase_shift(transformer, 1)
527}
528
529/// The positive sequence phase shift of winding `winding` against the first
530/// winding, degrees: the angle by which the first winding's voltage leads
531/// it. Zero when both share a connection; otherwise thirty degrees, signed
532/// by the DELTA winding's orientation ([`calc_delta_direction`]): `-30 d`
533/// when the first winding is the DELTA, `+30 d` when `winding` is. The one
534/// vector group shift: [`calc_transformer_phase_shift`] and the CIM and
535/// MG-RAVENS phase clocks read it.
536///
537/// # Errors
538/// A winding outside the unit, or what [`calc_delta_direction`] refuses.
539pub(crate) fn calc_winding_phase_shift(
540    transformer: &DistTransformer,
541    winding: usize,
542) -> Result<f64> {
543    let (Some(a), Some(b)) = (
544        transformer.windings.first(),
545        transformer.windings.get(winding),
546    ) else {
547        return Err(unsupported(
548            &transformer.name,
549            format!("winding {} is outside the unit", winding + 1),
550        ));
551    };
552    if a.conn == b.conn {
553        return Ok(0.0);
554    }
555    if a.conn == DistWindingConn::Delta {
556        Ok(-30.0 * f64::from(calc_delta_direction(transformer, 0)?))
557    } else {
558        Ok(30.0 * f64::from(calc_delta_direction(transformer, winding)?))
559    }
560}
561
562/// The number of terminals of a winding its coils span: two for a single
563/// phase unit (one for an implicitly grounded coil), the phases and neutral
564/// of a polyphase WYE winding, the phases of a DELTA winding.
565fn terminal_count(w: &DistWinding, phases: usize) -> usize {
566    if phases == 1 {
567        2.min(w.terminal_map.len())
568    } else if w.conn == DistWindingConn::Wye {
569        (phases + 1).min(w.terminal_map.len())
570    } else {
571        phases
572    }
573}
574
575/// The coils of one winding as channels over its terminal map, in phase
576/// order ([`calc_element_connection`] with the unit's phase count): each
577/// polyphase WYE coil from its phase terminal to the neutral (to ground when
578/// the map states no neutral), each DELTA coil around the ring in the
579/// orientation of [`calc_delta_direction`], and a single phase coil across
580/// its two terminals (to ground for one).
581///
582/// # Errors
583/// A winding outside the unit, a terminal map shorter than its coils need,
584/// an undeclared bus or ambiguous neutral, or what [`calc_delta_direction`]
585/// refuses.
586pub fn calc_winding_connection(
587    network: &MulticonductorNetwork,
588    transformer: &DistTransformer,
589    winding: usize,
590) -> Result<Vec<ConnectionChannel>> {
591    let name = transformer.name.as_str();
592    let w = transformer
593        .windings
594        .get(winding)
595        .ok_or_else(|| invalid(name, format!("windings[{winding}]"), "is not stated"))?;
596    let phases = transformer.phases;
597    let configuration = if phases == 1 {
598        Configuration::SinglePhase
599    } else if w.conn == DistWindingConn::Wye {
600        Configuration::Wye
601    } else {
602        Configuration::Delta
603    };
604    let count = terminal_count(w, phases);
605    let map = w.terminal_map.get(..count).ok_or_else(|| {
606        invalid(
607            name,
608            format!("windings[{winding}].terminal_map"),
609            format!("expected {count} terminals"),
610        )
611    })?;
612    let mut channels =
613        calc_element_connection(network, &w.bus, map, configuration, Some(phases))
614            .map_err(|reason| invalid(name, format!("windings[{winding}].terminal_map"), reason))?;
615    if configuration == Configuration::Delta {
616        orient_delta_ring(&mut channels, calc_delta_direction(transformer, winding)?);
617    }
618    Ok(channels)
619}
620
621/// A transformer's magnetizing branch: the per coil admittance, siemens,
622/// stamped across each coil of one winding.
623#[derive(Clone, Copy, Debug, PartialEq)]
624#[non_exhaustive]
625pub struct TransformerMagnetizing {
626    /// The winding whose coils carry the branch, zero based.
627    pub winding: usize,
628    /// Conductance plus susceptance per coil, siemens.
629    pub admittance: Complex64,
630}
631
632/// The magnetizing branch a transformer states, in one of three spellings:
633///
634/// - `no_load_shunt` `{winding, g, b}`: per coil siemens on the stated one
635///   based winding;
636/// - `g_no_load` and `b_no_load` (BMOPF): siemens on the second winding, or
637///   the first winding of a regulator, divided across the phases of a
638///   `single_phase`, `wye_delta` or `delta_wye` unit, which state a total;
639/// - OpenDSS `%noloadloss` and `%imag`: percent of the first winding's
640///   rating over the second winding's coil voltage
641///   ([`calc_coil_voltage`] times tap), on the second winding, the
642///   susceptance inductive.
643///
644/// `None` when none is stated. The one magnetizing branch: the transformer
645/// primitive stamps it and the multiconductor OPF descriptor writes it as
646/// coil shunts.
647///
648/// # Errors
649/// `no_load_shunt` beside `g_no_load` or `b_no_load`, a `no_load_shunt`
650/// that is not an object of a winding, `g` and `b` alone, a winding outside
651/// the unit, a negative or nonfinite conductance, a nonfinite susceptance,
652/// or OpenDSS percentages that are negative or nonfinite.
653#[allow(clippy::too_many_lines)] // three spellings, each validated in full
654pub fn calc_transformer_magnetizing(
655    transformer: &DistTransformer,
656) -> Result<Option<TransformerMagnetizing>> {
657    let name = transformer.name.as_str();
658    let windings = transformer.windings.len();
659    let explicit = transformer.extras.get("no_load_shunt");
660    let legacy = transformer_extra_number(&transformer.extras, "g_no_load")
661        .or_else(|| transformer_extra_number(&transformer.extras, "b_no_load"))
662        .is_some();
663    if explicit.is_some() && legacy {
664        return Err(invalid(
665            name,
666            "no_load_shunt",
667            "cannot coexist with g_no_load or b_no_load",
668        ));
669    }
670    let checked = |field: &str, g: f64, b: f64| -> Result<Complex64> {
671        if !g.is_finite() || g < 0.0 || !b.is_finite() {
672            return Err(invalid(name, field, "requires finite g >= 0 and finite b"));
673        }
674        Ok(Complex64::new(g, b))
675    };
676    if let Some(shunt) = explicit {
677        let object = shunt.as_object().ok_or_else(|| {
678            invalid(
679                name,
680                "no_load_shunt",
681                "expected an object containing winding, g, and b",
682            )
683        })?;
684        if let Some(key) = object
685            .keys()
686            .find(|key| !["winding", "g", "b"].contains(&key.as_str()))
687        {
688            return Err(invalid(
689                name,
690                "no_load_shunt",
691                format!("unknown field `{key}`"),
692            ));
693        }
694        let winding = object
695            .get("winding")
696            .and_then(serde_json::Value::as_u64)
697            .and_then(|w| usize::try_from(w).ok())
698            .filter(|w| *w >= 1 && *w <= windings)
699            .ok_or_else(|| {
700                invalid(
701                    name,
702                    "no_load_shunt.winding",
703                    format!("must be a one based winding between 1 and {windings}"),
704                )
705            })?;
706        let component = |key: &str| {
707            object
708                .get(key)
709                .and_then(serde_json::Value::as_f64)
710                .ok_or_else(|| invalid(name, format!("no_load_shunt.{key}"), "expected siemens"))
711        };
712        return Ok(Some(TransformerMagnetizing {
713            winding: winding - 1,
714            admittance: checked("no_load_shunt", component("g")?, component("b")?)?,
715        }));
716    }
717    if legacy {
718        let g = transformer_extra_number(&transformer.extras, "g_no_load").unwrap_or(0.0);
719        let b = transformer_extra_number(&transformer.extras, "b_no_load").unwrap_or(0.0);
720        let admittance = checked("g_no_load/b_no_load", g, b)?;
721        let winding = usize::from(!is_transformer_regulator(transformer));
722        if winding >= windings {
723            return Err(invalid(
724                name,
725                "g_no_load/b_no_load",
726                "has no winding to sit on",
727            ));
728        }
729        let divisor = if matches!(
730            subtype(transformer),
731            Some("single_phase" | "wye_delta" | "delta_wye")
732        ) {
733            transformer.phases.max(1) as f64
734        } else {
735            1.0
736        };
737        return Ok(Some(TransformerMagnetizing {
738            winding,
739            admittance: admittance / divisor,
740        }));
741    }
742    let loss = transformer_extra_number(&transformer.extras, "%noloadloss");
743    let imag = transformer_extra_number(&transformer.extras, "%imag");
744    if loss.is_none() && imag.is_none() {
745        return Ok(None);
746    }
747    let loss = loss.unwrap_or(0.0);
748    let imag = imag.unwrap_or(0.0);
749    if !loss.is_finite() || loss < 0.0 || !imag.is_finite() || imag < 0.0 {
750        return Err(invalid(
751            name,
752            "%noloadloss/%imag",
753            "requires finite nonnegative percentages",
754        ));
755    }
756    if windings < 2 || transformer.phases == 0 {
757        return Err(invalid(
758            name,
759            "%noloadloss/%imag",
760            "needs a second winding and a phase",
761        ));
762    }
763    let v = calc_coil_voltage(transformer, 1) * transformer.windings[1].tap;
764    let ybase = crate::electrical::calc_squared_voltage_admittance(
765        transformer.windings[0].s_rating,
766        transformer.phases as f64 * v * v,
767    );
768    Ok(Some(TransformerMagnetizing {
769        winding: 1,
770        admittance: Complex64::new(loss / 100.0 * ybase, -imag / 100.0 * ybase),
771    }))
772}
773
774/// How a winding's neutral is grounded, as the source states it.
775#[derive(Clone, Copy, Debug, PartialEq)]
776#[non_exhaustive]
777pub enum WindingNeutralGrounding {
778    /// No neutral impedance is stated: the neutral terminal connects as its
779    /// bus declares it.
780    Unstated,
781    /// A negative `r_neutral`, OpenDSS's floating neutral: no grounding
782    /// branch.
783    Floating,
784    /// `r_neutral` and `x_neutral` both zero (one may be omitted): the
785    /// neutral is solidly grounded, an exact zero voltage.
786    Solid,
787    /// A finite neutral to ground admittance, siemens:
788    /// `1 / (r_neutral + j x_neutral)`.
789    Impedance(Complex64),
790}
791
792/// The neutral grounding a winding's `r_neutral` and `x_neutral` state,
793/// OpenDSS's reading: unstated when both are omitted, floating for a
794/// negative resistance, solid when both are zero (an omitted one reads
795/// zero), else the admittance of the stated impedance (`NaN` parts for a
796/// nonfinite one). The one neutral grounding rule:
797/// [`calc_winding_neutral_grounding`] checks it, and the MG-RAVENS and BMOPF
798/// writers and the multiconductor ideal transformer profile read it as
799/// stated.
800#[must_use]
801pub fn calc_stated_neutral_grounding(winding: &DistWinding) -> WindingNeutralGrounding {
802    if winding.r_neutral.is_none() && winding.x_neutral.is_none() {
803        return WindingNeutralGrounding::Unstated;
804    }
805    let r = winding.r_neutral.unwrap_or(0.0);
806    let x = winding.x_neutral.unwrap_or(0.0);
807    if r < 0.0 {
808        WindingNeutralGrounding::Floating
809    } else if r == 0.0 && x == 0.0 {
810        WindingNeutralGrounding::Solid
811    } else {
812        WindingNeutralGrounding::Impedance(Complex64::new(1.0, 0.0) / Complex64::new(r, x))
813    }
814}
815
816/// A winding's neutral grounding, [`calc_stated_neutral_grounding`] checked
817/// for the transformer primitive and the multiconductor OPF descriptor.
818///
819/// # Errors
820/// A nonfinite neutral impedance, or a DELTA winding that states a solid or
821/// finite neutral grounding (it has no neutral terminal).
822pub fn calc_winding_neutral_grounding(
823    transformer: &DistTransformer,
824    winding: usize,
825) -> Result<WindingNeutralGrounding> {
826    let name = transformer.name.as_str();
827    let w = &transformer.windings[winding];
828    let stated = [w.r_neutral, w.x_neutral];
829    if stated.iter().any(Option::is_some) && !stated.iter().flatten().all(|v| v.is_finite()) {
830        return Err(invalid(
831            name,
832            format!("windings[{winding}].neutral impedance"),
833            "expected finite resistance and reactance",
834        ));
835    }
836    let grounding = calc_stated_neutral_grounding(w);
837    if w.conn == DistWindingConn::Delta
838        && !matches!(
839            grounding,
840            WindingNeutralGrounding::Floating | WindingNeutralGrounding::Unstated
841        )
842    {
843        return Err(unsupported(
844            name,
845            "neutral impedance on a delta winding has no physical neutral terminal",
846        ));
847    }
848    Ok(grounding)
849}
850
851/// The primitive of an admittance `y` across one coil: `y · [[1, -1], [-1,
852/// 1]]` over its two terminals, or `[[y]]` when the coil returns through
853/// ground. The one coil shunt stamp: the transformer primitive's magnetizing
854/// branch and the multiconductor OPF's core and neutral shunts read it.
855#[must_use]
856pub fn calc_coil_shunt_primitive(
857    y: Complex64,
858    returns_through_ground: bool,
859) -> Vec<Vec<Complex64>> {
860    if returns_through_ground {
861        vec![vec![y]]
862    } else {
863        vec![vec![y, -y], vec![-y, y]]
864    }
865}
866
867/// A finite leakage transformer's primitive admittance, siemens, over its
868/// physical terminals.
869///
870/// A terminal shared by several coils (a common WYE neutral, a centre tap)
871/// appears once in `terminals`, in the order the windings first name it.
872#[derive(Clone, Debug)]
873#[non_exhaustive]
874pub struct TransformerPrimitive<'a> {
875    pub name: &'a str,
876    /// `(bus, terminal)` of each primitive row, in primitive order.
877    pub terminals: Vec<(&'a str, &'a str)>,
878    /// Leakage and winding neutral impedance contributions.
879    pub series: Vec<Vec<Complex64>>,
880    /// Magnetizing, core loss and stated small grounding admittance contributions.
881    pub shunt: Vec<Vec<Complex64>>,
882    /// `series + shunt`, the element's primitive admittance.
883    pub primitive: Vec<Vec<Complex64>>,
884    /// WYE neutral terminals the source grounds solidly
885    /// ([`WindingNeutralGrounding::Solid`]): exact zero voltage constraints,
886    /// not an admittance.
887    pub grounded: Vec<(&'a str, &'a str)>,
888    /// The coil ring orientation of the first DELTA winding
889    /// ([`calc_delta_direction`]), `+1` when the unit has none.
890    pub delta_direction: i8,
891    /// The winding domain admittance `Y_1Volt` behind `series`
892    /// ([`calc_transformer_winding_admittance`]), or the referred winding
893    /// primitive of a single phase autotransformer.
894    pub winding_admittance: Vec<Vec<Complex64>>,
895}
896
897/// Whether [`calc_transformer_primitive_admittance`] refuses this
898/// transformer for stating no leakage at all: no short circuit reactance and
899/// no winding resistance, or, for a single phase autotransformer, no stated
900/// series impedance. Such a unit is an ideal coupling, which needs exact
901/// voltage constraints rather than an admittance.
902#[must_use]
903pub fn transformer_states_no_leakage(transformer: &DistTransformer) -> bool {
904    if uses_autotransformer_impedance(transformer) {
905        return [
906            "r_series_from",
907            "x_series_from",
908            "r_series_to",
909            "x_series_to",
910        ]
911        .iter()
912        .all(|key| {
913            transformer_extra_number(&transformer.extras, key).is_none_or(|value| value == 0.0)
914        });
915    }
916    transformer.xsc_pct.iter().all(|value| *value == 0.0)
917        && transformer.windings.iter().all(|w| w.r_pct == 0.0)
918}
919
920fn terminal_index(terminals: &[(&str, &str)], bus: &str, terminal: &str) -> Option<usize> {
921    terminals
922        .iter()
923        .position(|(b, t)| b.eq_ignore_ascii_case(bus) && *t == terminal)
924}
925
926/// One winding's coils as positions in the primitive's terminal list:
927/// each coil's first terminal and its return (`None` through ground).
928fn coil_positions(
929    network: &MulticonductorNetwork,
930    transformer: &DistTransformer,
931    winding: usize,
932    terminals: &[(&str, &str)],
933) -> Result<Vec<(Option<usize>, Option<usize>)>> {
934    let w = &transformer.windings[winding];
935    let position = |terminal: usize| terminal_index(terminals, &w.bus, &w.terminal_map[terminal]);
936    Ok(calc_winding_connection(network, transformer, winding)?
937        .iter()
938        .map(|channel| (position(channel.from), channel.to.and_then(position)))
939        .collect())
940}
941
942fn add_coil_shunt(
943    y: &mut [Vec<Complex64>],
944    (from, to): (Option<usize>, Option<usize>),
945    value: Complex64,
946) {
947    let stamp = calc_coil_shunt_primitive(value, to.is_none());
948    let rows = [from, to];
949    for (i, row) in stamp.iter().enumerate() {
950        for (j, entry) in row.iter().enumerate() {
951            if let (Some(a), Some(b)) = (rows[i], rows[j]) {
952                y[a][b] += entry;
953            }
954        }
955    }
956}
957
958fn checked_tap(w: &DistWinding, name: &str) -> Result<f64> {
959    if !w.tap.is_finite() || w.tap <= 0.0 {
960        return Err(invalid(name, "winding.tap", "must be positive and finite"));
961    }
962    Ok(w.tap)
963}
964
965fn sum_matrices(a: &[Vec<Complex64>], b: &[Vec<Complex64>]) -> Vec<Vec<Complex64>> {
966    let mut sum = a.to_vec();
967    for (row, other) in sum.iter_mut().zip(b) {
968        for (value, add) in row.iter_mut().zip(other) {
969            *value += add;
970        }
971    }
972    sum
973}
974
975/// The primitive admittance of a finite leakage transformer, siemens, over
976/// its physical terminals, following the OpenDSS `CalcY_Terminal` path: the
977/// winding domain `Y_1Volt` ([`calc_transformer_winding_admittance`], the
978/// inverse of the reduced pairwise leakage of
979/// [`calc_transformer_leakage_impedances`]) is referred to each phase's
980/// coils through the turns and base factors,
981///
982/// ```text
983/// Y_series = Σ_phase Bᵀ Y_1Volt B,   B[w][a] = ±1 / (V_coil,w · tap_w)
984/// ```
985///
986/// with `B` the incidence of winding `w`'s coil on terminal `a`
987/// ([`calc_winding_connection`]) and `V_coil` its coil voltage
988/// ([`calc_coil_voltage`]). A finite WYE neutral impedance stamps once from
989/// the neutral terminal to ground, a solid one is returned in `grounded`,
990/// and a floating one has no physical grounding branch ([`calc_winding_neutral_grounding`]).
991/// The magnetizing branch ([`calc_transformer_magnetizing`]) stamps across
992/// each coil of its winding.
993///
994/// Two and three winding units of one to three phases and the BMOPF
995/// `center_tap` unit are supported. The BMOPF `single_phase_autotransformer`
996/// states its impedance in ohms
997/// ([`TransformerLeakageBase::StatedOhms`]); its primitive is
998/// `y · w wᵀ`, with `w` the from winding incidence minus `n = 1 / tap` times
999/// the to winding incidence, over the order from phase, to phase, from
1000/// reference, to reference. The one transformer primitive: the
1001/// multiconductor nodal admittance stamps it and the SINCAL writer checks its
1002/// candidate against it.
1003///
1004/// # Errors
1005/// A transformer stating no leakage (an ideal coupling, which needs voltage
1006/// constraints), another winding count or phase count, a raw OpenDSS
1007/// property the typed model does not carry (`xrconst`, `core`, a
1008/// malformed `ppm_antifloat`), nameplate, tap, terminal map, connection,
1009/// neutral impedance or magnetizing data that is not usable, or a singular
1010/// leakage impedance.
1011#[allow(clippy::too_many_lines)] // the coil referral, then the neutral and magnetizing stamps
1012pub fn calc_transformer_primitive_admittance<'a>(
1013    network: &MulticonductorNetwork,
1014    transformer: &'a DistTransformer,
1015) -> Result<TransformerPrimitive<'a>> {
1016    // These raw DSS settings are not represented by the typed winding model.
1017    for key in ["xrconst", "core"] {
1018        if transformer.extras.contains_key(key) {
1019            return Err(unsupported(
1020                &transformer.name,
1021                format!("raw OpenDSS property `{key}` requires normalization"),
1022            ));
1023        }
1024    }
1025    let anti_float = transformer_extra_number(&transformer.extras, "ppm_antifloat").unwrap_or(
1026        if *network.source_format() == Some(crate::model::DistSourceFormat::Dss) {
1027            1.0
1028        } else {
1029            0.0
1030        },
1031    );
1032    if !anti_float.is_finite() {
1033        return Err(invalid(
1034            &transformer.name,
1035            "ppm_antifloat",
1036            "must be finite",
1037        ));
1038    }
1039    if uses_autotransformer_impedance(transformer) {
1040        if anti_float != 0.0 {
1041            return Err(unsupported(
1042                &transformer.name,
1043                "ppm_antifloat is not supported for BMOPF autotransformers",
1044            ));
1045        }
1046        return autotransformer_primitive(transformer);
1047    }
1048    validate_primitive_shape(transformer)?;
1049    let phases = transformer.phases;
1050    let name = transformer.name.as_str();
1051    let windings = transformer.windings.len();
1052
1053    let turns: Vec<f64> = (0..windings)
1054        .map(|index| {
1055            Ok(calc_coil_voltage(transformer, index)
1056                * checked_tap(&transformer.windings[index], name)?)
1057        })
1058        .collect::<Result<_>>()?;
1059    let y_1volt = calc_transformer_winding_admittance(transformer)
1060        .map_err(|error| unsupported(name, error))?
1061        .ok_or_else(|| invalid(name, "leakage impedance", "is singular"))?;
1062
1063    let mut terminals: Vec<(&str, &str)> = Vec::new();
1064    // The unique terminal list, once. Coils from all phases then stamp
1065    // through the same physical neutral column when a neutral is explicit.
1066    for winding in &transformer.windings {
1067        for terminal in winding
1068            .terminal_map
1069            .iter()
1070            .take(terminal_count(winding, phases))
1071        {
1072            if terminal_index(&terminals, &winding.bus, terminal).is_none() {
1073                terminals.push((winding.bus.as_str(), terminal.as_str()));
1074            }
1075        }
1076    }
1077    let nterm = terminals.len();
1078    if nterm == 0 {
1079        return Err(invalid(name, "terminal_map", "no physical terminals"));
1080    }
1081    let coils: Vec<Vec<(Option<usize>, Option<usize>)>> = (0..windings)
1082        .map(|index| coil_positions(network, transformer, index, &terminals))
1083        .collect::<Result<_>>()?;
1084    if coils.iter().any(|winding| winding.len() != phases) {
1085        return Err(invalid(
1086            name,
1087            "terminal_map",
1088            "every winding needs one coil per phase",
1089        ));
1090    }
1091    let mut y_series = vec![vec![Complex64::new(0.0, 0.0); nterm]; nterm];
1092    let mut y_shunt = vec![vec![Complex64::new(0.0, 0.0); nterm]; nterm];
1093
1094    // The physical terminal matrix is the sum over independent phase copies
1095    // of Bᵀ Y_1Volt B, where B contains the turns and base factors.
1096    for phase in 0..phases {
1097        let mut b = vec![vec![Complex64::new(0.0, 0.0); nterm]; windings];
1098        for (index, winding_coils) in coils.iter().enumerate() {
1099            let (a, z) = winding_coils[phase];
1100            let k = Complex64::new(1.0 / turns[index], 0.0);
1101            if let Some(i) = a {
1102                b[index][i] += k;
1103            }
1104            if let Some(i) = z {
1105                b[index][i] -= k;
1106            }
1107        }
1108        for i in 0..nterm {
1109            for j in 0..nterm {
1110                let mut value = Complex64::new(0.0, 0.0);
1111                for p in 0..windings {
1112                    for q in 0..windings {
1113                        value += b[p][i] * y_1volt[p][q] * b[q][j];
1114                    }
1115                }
1116                y_series[i][j] += value;
1117            }
1118        }
1119    }
1120
1121    // A neutral grounding is one branch from the physical WYE neutral
1122    // conductor to ground, shared by all phase coils.
1123    let mut grounded = Vec::new();
1124    for (index, winding) in transformer.windings.iter().enumerate() {
1125        let grounding = calc_winding_neutral_grounding(transformer, index)?;
1126        if matches!(
1127            grounding,
1128            WindingNeutralGrounding::Unstated | WindingNeutralGrounding::Floating
1129        ) {
1130            continue;
1131        }
1132        let neutral = calc_winding_connection(network, transformer, index)?
1133            .first()
1134            .and_then(|coil| coil.to)
1135            .ok_or_else(|| {
1136                unsupported(
1137                    name,
1138                    "neutral impedance is declared but the WYE neutral is implicit ground",
1139                )
1140            })?;
1141        match grounding {
1142            WindingNeutralGrounding::Solid => {
1143                grounded.push((winding.bus.as_str(), winding.terminal_map[neutral].as_str()));
1144            }
1145            WindingNeutralGrounding::Impedance(y) => {
1146                if let Some(i) =
1147                    terminal_index(&terminals, &winding.bus, &winding.terminal_map[neutral])
1148                {
1149                    y_series[i][i] += y;
1150                }
1151            }
1152            _ => {}
1153        }
1154    }
1155
1156    if let Some(core) = calc_transformer_magnetizing(transformer)? {
1157        for &coil in &coils[core.winding] {
1158            add_coil_shunt(&mut y_shunt, coil, core.admittance);
1159        }
1160    }
1161    // OpenDSS places half the winding's small grounding admittance at each
1162    // coil endpoint. It uses untapped coil voltage and the first winding rating.
1163    for (index, winding_coils) in coils.iter().enumerate() {
1164        let voltage = calc_coil_voltage(transformer, index);
1165        let admittance = Complex64::new(
1166            0.0,
1167            -anti_float * 1e-6 * transformer.windings[0].s_rating
1168                / phases as f64
1169                / voltage.powi(2)
1170                / 2.0,
1171        );
1172        if !admittance.im.is_finite() {
1173            return Err(invalid(
1174                name,
1175                "ppm_antifloat",
1176                "grounding admittance is not finite",
1177            ));
1178        }
1179        for &(a, z) in winding_coils {
1180            for terminal in [a, z].into_iter().flatten() {
1181                y_shunt[terminal][terminal] += admittance;
1182            }
1183        }
1184        if transformer.windings[index].conn == DistWindingConn::Wye
1185            && matches!(
1186                calc_winding_neutral_grounding(transformer, index)?,
1187                WindingNeutralGrounding::Floating | WindingNeutralGrounding::Unstated
1188            )
1189            && let Some(neutral) = winding_coils.first().and_then(|coil| coil.1)
1190        {
1191            y_shunt[neutral][neutral] += admittance;
1192        }
1193    }
1194    let y_prim = sum_matrices(&y_series, &y_shunt);
1195    let delta_direction = match transformer
1196        .windings
1197        .iter()
1198        .position(|w| w.conn == DistWindingConn::Delta)
1199    {
1200        Some(index) => calc_delta_direction(transformer, index)?,
1201        None => 1,
1202    };
1203    Ok(TransformerPrimitive {
1204        name,
1205        terminals,
1206        series: y_series,
1207        shunt: y_shunt,
1208        primitive: y_prim,
1209        grounded,
1210        delta_direction,
1211        winding_admittance: y_1volt,
1212    })
1213}
1214
1215/// The fixed ratio BMOPF single phase autotransformer or regulator: its
1216/// impedance in referred ohms and its ratio the regulated over source
1217/// voltage, for both ANSI types (`regulator_type` records the hardware
1218/// only), as the BMOPF schema reads it. For Type B this is the BMOPFTools
1219/// calculation and the equivalent fixed tap OpenDSS two winding regulator.
1220#[allow(clippy::too_many_lines)] // the BMOPFTools primitive order, then its stamps
1221fn autotransformer_primitive(transformer: &DistTransformer) -> Result<TransformerPrimitive<'_>> {
1222    let name = transformer.name.as_str();
1223    if transformer.phases != 1 || transformer.windings.len() != 2 {
1224        return Err(unsupported(
1225            name,
1226            format!(
1227                "single_phase_autotransformer requires one phase and two windings; got {} phases and {} windings",
1228                transformer.phases,
1229                transformer.windings.len()
1230            ),
1231        ));
1232    }
1233    let from = &transformer.windings[0];
1234    let to = &transformer.windings[1];
1235    for (idx, winding) in [from, to].iter().enumerate() {
1236        if winding.conn != DistWindingConn::Wye || winding.terminal_map.len() != 2 {
1237            return Err(invalid(
1238                name,
1239                format!("windings[{idx}].terminal_map"),
1240                "autotransformer winding requires phase and reference terminals",
1241            ));
1242        }
1243    }
1244    let tap_ratio = checked_tap(to, name)?;
1245    let regulator_type = transformer
1246        .extras
1247        .get("regulator_type")
1248        .and_then(serde_json::Value::as_str)
1249        .unwrap_or("B")
1250        .trim()
1251        .to_ascii_uppercase();
1252    if !matches!(regulator_type.as_str(), "A" | "B") {
1253        return Err(invalid(
1254            name,
1255            "regulator_type",
1256            format!("expected A or B, got `{regulator_type}`"),
1257        ));
1258    }
1259    let n_eff = 1.0 / tap_ratio;
1260    let z = calc_transformer_leakage_impedances(transformer, &TransformerLeakageBase::StatedOhms)?
1261        [0][1];
1262    if z.norm() == 0.0 {
1263        return Err(unsupported(
1264            name,
1265            "zero series impedance requires an ideal regulator voltage constraint",
1266        ));
1267    }
1268    let y = z.finv();
1269    let y_1volt = vec![vec![y, -n_eff * y], vec![-n_eff * y, n_eff.powi(2) * y]];
1270
1271    // The BMOPFTools primitive order: from phase, to phase, from reference,
1272    // to reference. Repeated physical terminals are coalesced.
1273    let mut terminals: Vec<(&str, &str)> = Vec::new();
1274    for (winding, terminal) in [
1275        (from, &from.terminal_map[0]),
1276        (to, &to.terminal_map[0]),
1277        (from, &from.terminal_map[1]),
1278        (to, &to.terminal_map[1]),
1279    ] {
1280        if terminal_index(&terminals, &winding.bus, terminal).is_none() {
1281            terminals.push((winding.bus.as_str(), terminal.as_str()));
1282        }
1283    }
1284    let nterm = terminals.len();
1285    let position = |winding: &DistWinding, terminal: usize| {
1286        terminal_index(&terminals, &winding.bus, &winding.terminal_map[terminal])
1287            .expect("every winding terminal is listed")
1288    };
1289    let mut from_incidence = vec![0.0; nterm];
1290    let mut to_incidence = vec![0.0; nterm];
1291    for (incidence, winding) in [(&mut from_incidence, from), (&mut to_incidence, to)] {
1292        incidence[position(winding, 0)] += 1.0;
1293        incidence[position(winding, 1)] -= 1.0;
1294    }
1295    let winding_difference: Vec<f64> = from_incidence
1296        .iter()
1297        .zip(&to_incidence)
1298        .map(|(from, to)| from - n_eff * to)
1299        .collect();
1300    let mut y_series = vec![vec![Complex64::default(); nterm]; nterm];
1301    for i in 0..nterm {
1302        for j in 0..nterm {
1303            y_series[i][j] = y * winding_difference[i] * winding_difference[j];
1304        }
1305    }
1306    let mut y_shunt = vec![vec![Complex64::default(); nterm]; nterm];
1307    if let Some(core) = calc_transformer_magnetizing(transformer)? {
1308        let winding = &transformer.windings[core.winding];
1309        add_coil_shunt(
1310            &mut y_shunt,
1311            (Some(position(winding, 0)), Some(position(winding, 1))),
1312            core.admittance,
1313        );
1314    }
1315    let y_prim = sum_matrices(&y_series, &y_shunt);
1316    Ok(TransformerPrimitive {
1317        name,
1318        terminals,
1319        series: y_series,
1320        shunt: y_shunt,
1321        primitive: y_prim,
1322        grounded: Vec::new(),
1323        delta_direction: 1,
1324        winding_admittance: y_1volt,
1325    })
1326}
1327
1328#[allow(clippy::too_many_lines)] // one check per nameplate field, each with its own message
1329fn validate_primitive_shape(t: &DistTransformer) -> Result<()> {
1330    let name = t.name.as_str();
1331    let center_tap = subtype(t) == Some("center_tap");
1332    let winding_count = t.windings.len();
1333    if !(2..=3).contains(&winding_count) || (center_tap && winding_count != 3) {
1334        return Err(unsupported(
1335            name,
1336            "finite primitives require two or three windings",
1337        ));
1338    }
1339    if center_tap && t.phases != 1 {
1340        return Err(unsupported(
1341            name,
1342            format!(
1343                "BMOPF centre-tap primitives require one phase; got {}",
1344                t.phases
1345            ),
1346        ));
1347    }
1348    if t.phases == 0 || t.phases > 3 {
1349        return Err(unsupported(
1350            name,
1351            format!(
1352                "{} phases are outside the supported 1, 2, and 3 phase shapes",
1353                t.phases
1354            ),
1355        ));
1356    }
1357    let expected_xsc = winding_count * (winding_count - 1) / 2;
1358    if t.xsc_pct.len() != expected_xsc {
1359        return Err(invalid(
1360            name,
1361            "xsc_pct",
1362            format!(
1363                "{} requires exactly {expected_xsc} pairwise short-circuit values",
1364                if center_tap {
1365                    "a centre-tap transformer"
1366                } else {
1367                    "a finite transformer"
1368                }
1369            ),
1370        ));
1371    }
1372    if t.xsc_pct
1373        .iter()
1374        .any(|value| !value.is_finite() || *value < 0.0)
1375    {
1376        return Err(invalid(name, "xsc_pct", "must be finite and nonnegative"));
1377    }
1378    for (idx, w) in t.windings.iter().enumerate() {
1379        if !w.v_ref.is_finite() || w.v_ref <= 0.0 {
1380            return Err(invalid(
1381                name,
1382                format!("windings[{idx}].v_ref"),
1383                "must be positive and finite",
1384            ));
1385        }
1386        if !w.s_rating.is_finite() || w.s_rating <= 0.0 {
1387            return Err(invalid(
1388                name,
1389                format!("windings[{idx}].s_rating"),
1390                "must be positive and finite",
1391            ));
1392        }
1393        if !w.r_pct.is_finite() || w.r_pct < 0.0 {
1394            return Err(invalid(
1395                name,
1396                format!("windings[{idx}].r_pct"),
1397                "must be finite and nonnegative",
1398            ));
1399        }
1400        checked_tap(w, name)?;
1401        let expected = terminal_count(w, t.phases);
1402        if t.phases == 1 && w.conn == DistWindingConn::Delta && w.terminal_map.len() < 2 {
1403            return Err(invalid(
1404                name,
1405                format!("windings[{idx}].terminal_map"),
1406                "a one-phase DELTA winding requires two coil endpoints",
1407            ));
1408        }
1409        let stated = w.terminal_map.len();
1410        let wye_expected = if t.phases == 1 { 2 } else { t.phases + 1 };
1411        let accepted = if w.conn == DistWindingConn::Wye {
1412            stated == wye_expected || stated == t.phases
1413        } else {
1414            stated == expected
1415        };
1416        if !accepted {
1417            return Err(invalid(
1418                name,
1419                format!("windings[{idx}].terminal_map"),
1420                format!(
1421                    "expected {} terminals (or {} phase terminals with an implicit WYE ground), got {stated}",
1422                    if w.conn == DistWindingConn::Wye {
1423                        wye_expected
1424                    } else {
1425                        expected
1426                    },
1427                    t.phases,
1428                ),
1429            ));
1430        }
1431    }
1432    if transformer_states_no_leakage(t) {
1433        return Err(unsupported(
1434            name,
1435            "zero leakage requires ideal voltage constraints and cannot be represented by an admittance primitive",
1436        ));
1437    }
1438    Ok(())
1439}
1440
1441#[cfg(test)]
1442mod tests {
1443    use super::*;
1444
1445    fn unit(conn: [DistWindingConn; 2], v: [f64; 2]) -> DistTransformer {
1446        let windings = conn
1447            .iter()
1448            .zip(v)
1449            .map(|(&conn, v_ref)| DistWinding::new("b", vec![], conn, v_ref, 1.0))
1450            .collect();
1451        DistTransformer::new("t", windings, vec![1.0], 3)
1452    }
1453
1454    #[test]
1455    fn opendss_dy_orientation_and_shift_follow_leadlag() {
1456        let mut dy = unit(
1457            [DistWindingConn::Delta, DistWindingConn::Wye],
1458            [12.47e3, 0.48e3],
1459        );
1460        assert_eq!(calc_delta_direction(&dy, 0).unwrap(), -1);
1461        assert_eq!(calc_transformer_phase_shift(&dy).unwrap(), 30.0);
1462        dy.extras
1463            .insert("leadlag".into(), serde_json::json!("Euro"));
1464        assert_eq!(calc_delta_direction(&dy, 0).unwrap(), 1);
1465        assert_eq!(calc_transformer_phase_shift(&dy).unwrap(), -30.0);
1466        let yd = unit(
1467            [DistWindingConn::Wye, DistWindingConn::Delta],
1468            [12.47e3, 0.48e3],
1469        );
1470        assert_eq!(calc_delta_direction(&yd, 1).unwrap(), 1);
1471        assert_eq!(calc_transformer_phase_shift(&yd).unwrap(), 30.0);
1472        let mut bmopf = unit(
1473            [DistWindingConn::Delta, DistWindingConn::Wye],
1474            [12.47e3, 0.48e3],
1475        );
1476        bmopf
1477            .extras
1478            .insert("bmopf_subtype".into(), serde_json::json!("delta_wye"));
1479        assert_eq!(calc_delta_direction(&bmopf, 0).unwrap(), -1);
1480        bmopf
1481            .extras
1482            .insert("bmopf_delta_rolls".into(), serde_json::json!({"1": 2}));
1483        assert!(calc_delta_direction(&bmopf, 0).is_err());
1484    }
1485
1486    #[test]
1487    fn reduced_leakage_against_either_reference() {
1488        let z = |re: f64| Complex64::new(re, 0.0);
1489        let leakage = vec![
1490            vec![z(0.0), z(1.0), z(2.0)],
1491            vec![z(1.0), z(0.0), z(4.0)],
1492            vec![z(2.0), z(4.0), z(0.0)],
1493        ];
1494        assert_eq!(
1495            calc_reduced_leakage(&leakage, 0),
1496            vec![vec![z(1.0), z(-0.5)], vec![z(-0.5), z(2.0)]]
1497        );
1498        assert_eq!(
1499            calc_reduced_leakage(&leakage, 2),
1500            vec![vec![z(2.0), z(2.5)], vec![z(2.5), z(4.0)]]
1501        );
1502    }
1503
1504    #[test]
1505    fn neutral_grounding_reads_opendss_conventions() {
1506        let mut t = unit([DistWindingConn::Wye, DistWindingConn::Delta], [1.0, 1.0]);
1507        assert_eq!(
1508            calc_winding_neutral_grounding(&t, 0).unwrap(),
1509            WindingNeutralGrounding::Unstated
1510        );
1511        t.windings[0].r_neutral = Some(0.0);
1512        assert_eq!(
1513            calc_winding_neutral_grounding(&t, 0).unwrap(),
1514            WindingNeutralGrounding::Solid
1515        );
1516        t.windings[0].r_neutral = Some(-1.0);
1517        assert_eq!(
1518            calc_winding_neutral_grounding(&t, 0).unwrap(),
1519            WindingNeutralGrounding::Floating
1520        );
1521        t.windings[1].r_neutral = Some(2.0);
1522        assert!(calc_winding_neutral_grounding(&t, 1).is_err());
1523        t.windings[1].r_neutral = Some(-1.0);
1524        assert_eq!(
1525            calc_winding_neutral_grounding(&t, 1).unwrap(),
1526            WindingNeutralGrounding::Floating
1527        );
1528    }
1529
1530    #[test]
1531    fn legacy_core_sits_on_the_bmopf_winding() {
1532        let mut t = unit([DistWindingConn::Wye, DistWindingConn::Delta], [1.0, 1.0]);
1533        t.extras
1534            .insert("bmopf_subtype".into(), serde_json::json!("wye_delta"));
1535        t.extras.insert("g_no_load".into(), serde_json::json!(3.0));
1536        let core = calc_transformer_magnetizing(&t).unwrap().unwrap();
1537        assert_eq!(core.winding, 1);
1538        assert_eq!(core.admittance, Complex64::new(1.0, 0.0));
1539        t.extras.insert(
1540            "no_load_shunt".into(),
1541            serde_json::json!({"winding": 1, "g": 1.0, "b": 0.0}),
1542        );
1543        assert!(calc_transformer_magnetizing(&t).is_err());
1544    }
1545}