Skip to main content

powerio_matrix/matrix/
multiconductor.rs

1//! Native multiconductor nodal admittance over [`MulticonductorNetwork`]
2//! (#232): terminal and conductor indexed, in the network's actual units
3//! (volts, amperes, siemens), with no implicit positive sequence
4//! transformation anywhere.
5//!
6//! The voltage unknown rows are the ungrounded bus terminals: terminal `0`
7//! and every explicitly grounded terminal are excluded, and buses joined by
8//! an exact unity connection (a closed switch) merge into one electrical
9//! node rather than receiving an arbitrary small impedance. Every axis
10//! carries the stable [`DistNode`] mapping — bus identity plus terminal — so
11//! mappings remain valid after source row reordering.
12//!
13//! The passive admittance carries lines (series and both shunt halves from
14//! the linecode), shunts, capacitor banks, and every transformer that states
15//! leakage: its terminal primitive
16//! ([`calc_transformer_primitive_admittance`]) carries WYE and DELTA
17//! windings, fixed taps, the magnetizing branch and finite neutral
18//! impedances, for two winding units, the BMOPF centre tap and the BMOPF
19//! single phase autotransformer. A solidly grounded transformer neutral
20//! enters the augmented system as an exact zero voltage row. Ideal equipment
21//! — a two winding transformer stating no leakage and voltage sources —
22//! enters the augmented system as exact constraint rows over the node
23//! voltages with their coupled ideal currents. Ideal WYE windings retain
24//! explicit floating or grounded neutral terminals; an ideal unit with a
25//! non-WYE connection, neutral impedances, a core shunt or tap bounds, and a
26//! leakage unit outside the primitive's shapes, return an unsupported
27//! physics error before assembly. Tap bounds on a leakage unit are decision
28//! data the nodal system does not read: it stamps the stated fixed tap.
29
30mod transformer;
31
32pub use powerio_dist::transformer::{
33    TransformerLeakageBase, TransformerPrimitive, calc_transformer_leakage_impedances,
34    calc_transformer_primitive_admittance, calc_transformer_winding_admittance,
35};
36
37use std::collections::{BTreeMap, BTreeSet};
38
39use crate::diagnostics::Diagnostic;
40use num_complex::Complex64;
41use powerio_dist::{
42    DistCapacitor, DistLine, DistLineCode, DistShunt, DistTransformer, MulticonductorNetwork,
43};
44use sprs::CsMat;
45
46use crate::diagnostics::codes;
47use crate::matrix::triplet::CooBuilder;
48use crate::{Error, Result};
49
50/// One voltage unknown: a bus terminal, by stable identity.
51#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
52pub struct DistNode {
53    pub bus: String,
54    pub terminal: String,
55}
56
57/// Where a bus terminal lands in the nodal system.
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59pub enum NodeRef {
60    /// A voltage unknown at this dense row.
61    Node(usize),
62    /// Ground: terminal `0` or an explicitly grounded terminal.
63    Ground,
64}
65
66/// The dense node indexing of one multiconductor network, over powerio-dist's
67/// flat terminal index (so bus names compare ASCII case insensitively, as
68/// every multiconductor calculation reads them).
69#[derive(Clone, Debug)]
70pub struct MulticonductorNodeIndex {
71    nodes: Vec<DistNode>,
72    terminals: powerio_dist::MulticonductorTerminalIndex,
73    /// Flat terminal position to dense row; `None` for a grounded terminal.
74    dense_of_terminal: Vec<Option<usize>>,
75}
76
77impl MulticonductorNodeIndex {
78    /// Build the index: bus table order, each bus's stated terminal order,
79    /// with earth terminals (terminal `0`, and any terminal the network's
80    /// terminal conventions name as earth: `powerio_dist::calc_terminal_role`)
81    /// and explicitly grounded terminals excluded from the unknowns. Closed switches merge their paired terminals into one
82    /// node — the first spelling encountered names the merged node.
83    ///
84    /// # Errors
85    /// A duplicated bus or terminal identity, or a closed switch naming a
86    /// terminal its buses do not declare.
87    pub fn build(network: &MulticonductorNetwork) -> Result<Self> {
88        let terminals = powerio_dist::MulticonductorTerminalIndex::build(network)
89            .map_err(|error| Error::Mtx(error.to_string()))?;
90        // Components over provisional slots, one per ungrounded terminal.
91        let mut grounded = vec![false; terminals.len()];
92        let mut slot: Vec<Option<usize>> = vec![None; terminals.len()];
93        let mut provisional: Vec<usize> = Vec::new();
94        let conventions = network.terminal_conventions();
95        for bus in network.buses() {
96            for terminal in &bus.terminals {
97                let Some(position) = terminals.resolve(&bus.id, terminal) else {
98                    continue;
99                };
100                // Earth by the one terminal classification, or grounded at
101                // the bus.
102                if bus.terminal_role(terminal, conventions) == powerio_dist::TerminalRole::Earth
103                    || bus.grounded.contains(terminal)
104                {
105                    grounded[position] = true;
106                    continue;
107                }
108                slot[position] = Some(provisional.len());
109                provisional.push(position);
110            }
111        }
112
113        // Every union runs before any group is marked grounded, so a
114        // grounding is a property of the finished group and the index is
115        // identical under any declaration order of closed switches.
116        let mut joined_from: Vec<usize> = Vec::new();
117        let mut joined_to: Vec<usize> = Vec::new();
118        let mut ground_touched: Vec<usize> = Vec::new();
119        for switch in network.switches().iter().filter(|switch| !switch.open) {
120            for (from, to) in switch
121                .terminal_map_from
122                .iter()
123                .zip(switch.terminal_map_to.iter())
124            {
125                let from = terminals.resolve(&switch.bus_from, from);
126                let to = terminals.resolve(&switch.bus_to, to);
127                let slot_of = |position: Option<usize>| position.and_then(|p| slot[p]);
128                let grounded_at = |position: Option<usize>| position.is_some_and(|p| grounded[p]);
129                match (slot_of(from), slot_of(to)) {
130                    (Some(a), Some(b)) => {
131                        joined_from.push(a);
132                        joined_to.push(b);
133                    }
134                    // A closed switch onto ground grounds the other side's
135                    // whole finished group.
136                    (Some(a), None) if grounded_at(to) => ground_touched.push(a),
137                    (None, Some(b)) if grounded_at(from) => ground_touched.push(b),
138                    _ => {
139                        return Err(Error::Mtx(format!(
140                            "switch `{}` names a terminal its buses do not declare",
141                            switch.name
142                        )));
143                    }
144                }
145            }
146        }
147        // Groups are labeled in order of their first slot, so the first
148        // spelling in table order names a merged node; the one component
149        // labeling in powerio-tx joins them.
150        let labels =
151            powerio_tx::calc_dense_island_labels(provisional.len(), &joined_from, &joined_to);
152        let grounded_labels: BTreeSet<usize> = ground_touched
153            .into_iter()
154            .map(|slot| labels[slot])
155            .collect();
156
157        // Dense rows: one per surviving group, in provisional (table) order.
158        let mut dense_of_label: BTreeMap<usize, usize> = BTreeMap::new();
159        let mut nodes = Vec::new();
160        let mut dense_of_terminal = vec![None; terminals.len()];
161        for (index, &label) in labels.iter().enumerate() {
162            // A group that touched ground through a switch is grounded whole.
163            if grounded_labels.contains(&label) {
164                continue;
165            }
166            let position = provisional[index];
167            let dense = *dense_of_label.entry(label).or_insert_with(|| {
168                let (bus, terminal) = terminals.terminals()[position].clone();
169                nodes.push(DistNode { bus, terminal });
170                nodes.len() - 1
171            });
172            dense_of_terminal[position] = Some(dense);
173        }
174        Ok(Self {
175            nodes,
176            terminals,
177            dense_of_terminal,
178        })
179    }
180
181    /// The flat terminal index underneath: every declared terminal, grounded
182    /// or not, at its stable position.
183    #[must_use]
184    pub const fn terminals(&self) -> &powerio_dist::MulticonductorTerminalIndex {
185        &self.terminals
186    }
187
188    /// Where the terminal at a flat position lands: a dense unknown or
189    /// ground. `None` for a position past the terminal index.
190    #[must_use]
191    pub fn resolve_position(&self, position: usize) -> Option<NodeRef> {
192        self.dense_of_terminal
193            .get(position)
194            .map(|dense| dense.map_or(NodeRef::Ground, NodeRef::Node))
195    }
196
197    /// The voltage unknowns, in dense row order.
198    #[must_use]
199    pub fn nodes(&self) -> &[DistNode] {
200        &self.nodes
201    }
202
203    /// The number of voltage unknowns.
204    #[must_use]
205    pub fn len(&self) -> usize {
206        self.nodes.len()
207    }
208
209    #[must_use]
210    pub fn is_empty(&self) -> bool {
211        self.nodes.is_empty()
212    }
213
214    /// Where one bus terminal lands: a dense unknown (closed switch groups
215    /// share one), ground, or `None` for a terminal the network does not
216    /// declare.
217    #[must_use]
218    pub fn resolve(&self, bus: &str, terminal: &str) -> Option<NodeRef> {
219        let position = self.terminals.resolve(bus, terminal)?;
220        Some(self.dense_of_terminal[position].map_or(NodeRef::Ground, NodeRef::Node))
221    }
222}
223
224/// One ideal constraint row of the augmented system: exact relations over
225/// the node voltages, with the row's coupled ideal current entering the
226/// nodal balance through the transpose.
227#[derive(Clone, Debug)]
228pub struct AugmentedSystem {
229    /// Real and imaginary parts of the constraint matrix `A`
230    /// (`rows × nodes`): `A v = rhs`.
231    pub constraint_re: CsMat<f64>,
232    pub constraint_im: CsMat<f64>,
233    pub rhs_re: Vec<f64>,
234    pub rhs_im: Vec<f64>,
235    /// The element behind each constraint row, by stable identity.
236    pub labels: Vec<String>,
237}
238
239/// The assembled multiconductor nodal system.
240#[derive(Clone, Debug)]
241pub struct MulticonductorAdmittance {
242    index: MulticonductorNodeIndex,
243    conductance: CsMat<f64>,
244    susceptance: CsMat<f64>,
245    augmented: AugmentedSystem,
246    diagnostics: Vec<Diagnostic>,
247}
248
249impl MulticonductorAdmittance {
250    /// The node indexing behind every axis.
251    #[must_use]
252    pub const fn index(&self) -> &MulticonductorNodeIndex {
253        &self.index
254    }
255
256    /// The passive nodal conductance `G`, siemens, over the unknowns.
257    #[must_use]
258    pub const fn conductance(&self) -> &CsMat<f64> {
259        &self.conductance
260    }
261
262    /// The passive nodal susceptance `B`, siemens: `Y = G + jB`.
263    #[must_use]
264    pub const fn susceptance(&self) -> &CsMat<f64> {
265        &self.susceptance
266    }
267
268    /// The ideal equipment constraint rows.
269    #[must_use]
270    pub const fn augmented(&self) -> &AugmentedSystem {
271        &self.augmented
272    }
273
274    /// The builder's findings: every stamp it does not support, by element.
275    #[must_use]
276    pub fn diagnostics(&self) -> &[Diagnostic] {
277        &self.diagnostics
278    }
279}
280
281/// The largest elimination pivot, in ohms, a series impedance inverse refuses
282/// as singular.
283const SINGULAR_PIVOT_OHMS: f64 = 1e-14;
284
285/// The dense inverse of a series impedance: `None` when a pivot is
286/// [`SINGULAR_PIVOT_OHMS`] or smaller (or NaN).
287fn invert(matrix: &[Vec<Complex64>]) -> Option<Vec<Vec<Complex64>>> {
288    powerio_dist::dense::invert_dense_matrix(
289        matrix,
290        powerio_dist::dense::DensePivot::Partial,
291        SINGULAR_PIVOT_OHMS,
292        0.0,
293    )
294}
295
296struct Stamper {
297    conductance: CooBuilder,
298    susceptance: CooBuilder,
299}
300
301impl Stamper {
302    fn new(n: usize) -> Self {
303        Self {
304            conductance: CooBuilder::new(n),
305            susceptance: CooBuilder::new(n),
306        }
307    }
308
309    /// Accumulate one admittance between two node references: ground rows
310    /// and columns vanish, which is exactly the grounded reduction.
311    fn add(&mut self, from: NodeRef, to: NodeRef, value: Complex64) {
312        if let (NodeRef::Node(i), NodeRef::Node(j)) = (from, to) {
313            self.conductance.add(i, j, value.re);
314            self.susceptance.add(i, j, value.im);
315        }
316    }
317
318    /// Accumulate an element's primitive admittance over the node references
319    /// of its terminals, in the primitive's terminal order.
320    fn add_primitive(&mut self, terminals: &[NodeRef], primitive: &[Vec<Complex64>]) -> Result<()> {
321        scatter_primitive_admittance(terminals, primitive, |from, to, value| {
322            self.add(from, to, value);
323        })
324    }
325}
326
327/// Scatter an element's primitive admittance onto the system positions of
328/// its terminals: `add(terminals[r], terminals[c], primitive[r][c])` for every
329/// entry, in row major order. The one scatter of a primitive into a nodal
330/// system: [`calc_multiconductor_admittance_matrix`] reads it over its node
331/// references, and a caller indexing terminals its own way reads it over
332/// its positions.
333///
334/// # Errors
335/// A primitive that is not square over `terminals`.
336pub fn scatter_primitive_admittance<T: Copy>(
337    terminals: &[T],
338    primitive: &[Vec<Complex64>],
339    mut add: impl FnMut(T, T, Complex64),
340) -> Result<()> {
341    if primitive.len() != terminals.len()
342        || primitive.iter().any(|row| row.len() != terminals.len())
343    {
344        return Err(Error::Mtx(format!(
345            "a primitive admittance of {} rows does not match its {} terminals",
346            primitive.len(),
347            terminals.len()
348        )));
349    }
350    for (row, &from) in terminals.iter().enumerate() {
351        for (column, &to) in terminals.iter().enumerate() {
352            add(from, to, primitive[row][column]);
353        }
354    }
355    Ok(())
356}
357
358/// The primitive admittance of a line, siemens, over its terminals in the
359/// order `terminal_map_from` then `terminal_map_to`: the inverse of the
360/// linecode's series impedance over the length couples the two ends, and
361/// each end carries its shunt half,
362///
363/// ```text
364/// [ Y + Y_from     -Y      ]      Y = (Z_series · length)⁻¹
365/// [    -Y       Y + Y_to   ]      Y_from = (G_from + j B_from) · length
366/// ```
367///
368/// The one line stamp: [`calc_multiconductor_admittance_matrix`] scatters
369/// it into the nodal system.
370///
371/// # Errors
372/// A line whose terminal maps disagree with the linecode's conductor count,
373/// a linecode matrix of another shape, a length that is not finite and
374/// positive, or a singular series impedance.
375pub fn calc_line_primitive_admittance(
376    line: &DistLine,
377    code: &DistLineCode,
378) -> Result<Vec<Vec<Complex64>>> {
379    let conductors = code.n_conductors;
380    if line.terminal_map_from.len() != conductors || line.terminal_map_to.len() != conductors {
381        return Err(Error::Mtx(format!(
382            "line `{}` maps {}/{} terminals over a {conductors} conductor linecode",
383            line.name,
384            line.terminal_map_from.len(),
385            line.terminal_map_to.len()
386        )));
387    }
388    if !line.length.is_finite() || line.length <= 0.0 {
389        return Err(Error::Mtx(format!(
390            "line `{}` states no usable length",
391            line.name
392        )));
393    }
394    let square = |matrix: &[Vec<f64>]| {
395        matrix.len() == conductors && matrix.iter().all(|row| row.len() == conductors)
396    };
397    if ![
398        &code.r_series,
399        &code.x_series,
400        &code.g_from,
401        &code.b_from,
402        &code.g_to,
403        &code.b_to,
404    ]
405    .into_iter()
406    .all(|matrix| square(matrix))
407    {
408        return Err(Error::Mtx(format!(
409            "linecode `{}` states a matrix that is not {conductors} by {conductors}",
410            code.name
411        )));
412    }
413    let z: Vec<Vec<Complex64>> = (0..conductors)
414        .map(|row| {
415            (0..conductors)
416                .map(|column| {
417                    Complex64::new(code.r_series[row][column], code.x_series[row][column])
418                        * line.length
419                })
420                .collect()
421        })
422        .collect();
423    let Some(y_series) = invert(&z) else {
424        return Err(Error::Mtx(format!(
425            "line `{}` has a singular series impedance matrix",
426            line.name
427        )));
428    };
429    let mut primitive = vec![vec![Complex64::new(0.0, 0.0); 2 * conductors]; 2 * conductors];
430    for row in 0..conductors {
431        for column in 0..conductors {
432            let y = y_series[row][column];
433            let shunt_from =
434                Complex64::new(code.g_from[row][column], code.b_from[row][column]) * line.length;
435            let shunt_to =
436                Complex64::new(code.g_to[row][column], code.b_to[row][column]) * line.length;
437            primitive[row][column] = y + shunt_from;
438            primitive[conductors + row][conductors + column] = y + shunt_to;
439            primitive[row][conductors + column] = -y;
440            primitive[conductors + row][column] = -y;
441        }
442    }
443    Ok(primitive)
444}
445
446/// The primitive admittance of a shunt element, siemens, over its
447/// `terminal_map`: its stated `G + j B`.
448#[must_use]
449pub fn calc_shunt_primitive_admittance(shunt: &DistShunt) -> Vec<Vec<Complex64>> {
450    shunt
451        .g
452        .iter()
453        .zip(&shunt.b)
454        .map(|(g_row, b_row)| {
455            g_row
456                .iter()
457                .zip(b_row)
458                .map(|(&g, &b)| Complex64::new(g, b))
459                .collect()
460        })
461        .collect()
462}
463
464/// A capacitor bank's primitive admittance, siemens, over its terminal map:
465/// `j` times its susceptance ([`powerio_dist::calc_capacitor_susceptance`]).
466///
467/// Each coil of the bank's connection ([`powerio_dist::calc_element_connection`]:
468/// a WYE coil from each phase to its neutral or to ground, a DELTA coil
469/// between consecutive terminals or across a two terminal bank, a single
470/// phase coil across its two terminals) carries an equal share of the rated
471/// reactive power at its coil voltage:
472///
473/// ```text
474/// b = q_rated / coils / V²,   V = v_nom / √3 (WYE with more than one terminal), v_nom otherwise
475/// ```
476///
477/// The WYE nameplate is line to line when the bank has an explicit return
478/// or several phases; a one terminal WYE bank states its coil voltage.
479/// `None` for a configuration with no capacitor connection. The one
480/// capacitor stamp: [`calc_multiconductor_admittance_matrix`] scatters it
481/// into the nodal system and the multiconductor OPF writes it per unit.
482///
483/// # Errors
484/// A nameplate that is not finite with a positive voltage, or a terminal map
485/// its configuration cannot carry (an undeclared bus, an ambiguous WYE
486/// neutral, a single phase bank without two terminals).
487pub fn calc_capacitor_primitive_admittance(
488    network: &MulticonductorNetwork,
489    capacitor: &DistCapacitor,
490) -> Result<Option<Vec<Vec<Complex64>>>> {
491    let susceptance =
492        powerio_dist::calc_capacitor_susceptance(network, capacitor).map_err(Error::Mtx)?;
493    Ok(susceptance.map(|matrix| {
494        matrix
495            .into_iter()
496            .map(|row| row.into_iter().map(|b| Complex64::new(0.0, b)).collect())
497            .collect()
498    }))
499}
500
501/// The passive element family behind a [`PassivePrimitive`].
502#[derive(Clone, Copy, Debug, PartialEq, Eq)]
503#[non_exhaustive]
504pub enum PassiveFamily {
505    Line,
506    Shunt,
507    Capacitor,
508    Transformer,
509}
510
511impl PassiveFamily {
512    /// The family's lowercase name, as messages and element listings print it.
513    #[must_use]
514    pub const fn noun(self) -> &'static str {
515        match self {
516            Self::Line => "line",
517            Self::Shunt => "shunt",
518            Self::Capacitor => "capacitor",
519            Self::Transformer => "transformer",
520        }
521    }
522}
523
524/// A transformer neutral the source grounds solidly: an exact zero voltage
525/// at `(bus, terminal)`, not an admittance.
526#[derive(Clone, Copy, Debug, PartialEq, Eq)]
527#[non_exhaustive]
528pub struct GroundedNeutral<'a> {
529    /// The transformer that grounds it.
530    pub transformer: &'a str,
531    pub bus: &'a str,
532    pub terminal: &'a str,
533}
534
535impl GroundedNeutral<'_> {
536    /// Whether this neutral needs its own zero voltage row, given the voltage
537    /// an ideal source already prescribes on the same node (`None` when none
538    /// does): `true` without a prescription, `false` when the source already
539    /// fixes the node at exactly zero (a second row would make the
540    /// constraint rows rank deficient).
541    ///
542    /// The one rule for a solid neutral meeting a source:
543    /// [`calc_multiconductor_admittance_matrix`] and every caller assembling
544    /// its own prescribed voltages read it.
545    ///
546    /// # Errors
547    /// A nonzero prescribed voltage on the grounded node.
548    pub fn needs_zero_voltage_row(&self, prescribed: Option<Complex64>) -> Result<bool> {
549        match prescribed {
550            None => Ok(true),
551            Some(voltage) if voltage == Complex64::new(0.0, 0.0) => Ok(false),
552            Some(voltage) => Err(Error::Commit(powerio_core::Error::new(
553                &codes::BUILD_MULTI_PHYSICS_UNSUPPORTED,
554                format!(
555                    "transformer `{}` grounds neutral `{}`:{} solidly, but a source prescribes {} V there",
556                    self.transformer,
557                    self.bus,
558                    self.terminal,
559                    voltage.norm()
560                ),
561            ))),
562        }
563    }
564}
565
566/// Every admittance element of a network with the exact constraints it
567/// leaves to the caller: [`calc_passive_primitives`].
568#[derive(Clone, Debug)]
569#[non_exhaustive]
570pub struct NetworkPrimitives<'a> {
571    /// Lines, shunts, capacitor banks, then transformers stating leakage,
572    /// each family in table order.
573    pub elements: Vec<PassivePrimitive<'a>>,
574    /// Solidly grounded transformer neutrals, once per `(bus, terminal)`
575    /// spelling, in transformer order.
576    pub grounded: Vec<GroundedNeutral<'a>>,
577    /// Transformers that state no leakage: ideal couplings with no
578    /// admittance, which need exact voltage constraints.
579    pub ideal_transformers: Vec<&'a DistTransformer>,
580    /// Elements left out because the builders do not stamp them.
581    pub diagnostics: Vec<Diagnostic>,
582}
583
584/// One passive element's primitive admittance, siemens, with the bus
585/// terminal behind each primitive row.
586#[derive(Clone, Debug)]
587#[non_exhaustive]
588pub struct PassivePrimitive<'a> {
589    pub family: PassiveFamily,
590    pub name: &'a str,
591    /// `(bus, terminal)` of each primitive row, in primitive order.
592    pub terminals: Vec<(&'a str, &'a str)>,
593    pub primitive: Vec<Vec<Complex64>>,
594}
595
596/// Every admittance element of the network with its primitive admittance:
597/// lines (series inverse and both shunt halves,
598/// [`calc_line_primitive_admittance`]), then shunts
599/// ([`calc_shunt_primitive_admittance`]), then capacitor banks
600/// ([`calc_capacitor_primitive_admittance`]), then every transformer that
601/// states leakage ([`calc_transformer_primitive_admittance`]), each family
602/// in table order, with the transformers' solidly grounded neutrals and the
603/// ideal transformers left for exact constraints. The one element list:
604/// [`calc_multiconductor_admittance_matrix`] scatters it over its node
605/// references, and a caller indexing terminals its own way scatters it over
606/// its positions with [`scatter_primitive_admittance`].
607///
608/// A line's linecode is found under the network's identifier convention
609/// ([`MulticonductorNetwork::identifier_key`]), the convention readiness
610/// checks. An element the builders do not stamp (a line without a usable
611/// length, a capacitor configuration with no primitive) is left out and
612/// reported in the diagnostics, never stamped approximately.
613///
614/// # Errors
615/// A line naming an undeclared linecode or mapping terminals that disagree
616/// with its linecode, a singular series impedance, a shunt whose matrices
617/// are not square over its terminal map or not finite, a capacitor whose
618/// nameplate is not finite and positive, a capacitor terminal map its
619/// configuration cannot carry, or a leakage transformer the primitive
620/// refuses.
621#[allow(clippy::too_many_lines)] // one block per element family, in stamp order
622pub fn calc_passive_primitives(network: &MulticonductorNetwork) -> Result<NetworkPrimitives<'_>> {
623    let mut linecodes: BTreeMap<String, &DistLineCode> = BTreeMap::new();
624    for code in network.line_codes() {
625        linecodes
626            .entry(network.identifier_key(&code.name))
627            .or_insert(code);
628    }
629    let mut primitives = Vec::with_capacity(
630        network.lines().len() + network.shunts().len() + network.capacitors().len(),
631    );
632    let mut diagnostics = Vec::new();
633
634    for line in network.lines() {
635        let Some(code) = linecodes.get(&network.identifier_key(&line.linecode)) else {
636            return Err(Error::Mtx(format!(
637                "line `{}` names linecode `{}` the network does not declare",
638                line.name, line.linecode
639            )));
640        };
641        let conductors = code.n_conductors;
642        if line.terminal_map_from.len() != conductors || line.terminal_map_to.len() != conductors {
643            return Err(Error::Mtx(format!(
644                "line `{}` maps {}/{} terminals over a {conductors} conductor linecode",
645                line.name,
646                line.terminal_map_from.len(),
647                line.terminal_map_to.len()
648            )));
649        }
650        if !line.length.is_finite() || line.length <= 0.0 {
651            diagnostics.push(Diagnostic::of(
652                &codes::BUILD_MULTI_UNSUPPORTED_STAMP,
653                format!(
654                    "line `{}` states no usable length; its stamp is omitted",
655                    line.name
656                ),
657            ));
658            continue;
659        }
660        primitives.push(PassivePrimitive {
661            family: PassiveFamily::Line,
662            name: &line.name,
663            terminals: line
664                .terminal_map_from
665                .iter()
666                .map(|terminal| (line.bus_from.as_str(), terminal.as_str()))
667                .chain(
668                    line.terminal_map_to
669                        .iter()
670                        .map(|terminal| (line.bus_to.as_str(), terminal.as_str())),
671                )
672                .collect(),
673            primitive: calc_line_primitive_admittance(line, code)?,
674        });
675    }
676
677    for shunt in network.shunts() {
678        let size = shunt.terminal_map.len();
679        let square = |matrix: &[Vec<f64>]| {
680            matrix.len() == size
681                && matrix
682                    .iter()
683                    .all(|row| row.len() == size && row.iter().all(|value| value.is_finite()))
684        };
685        if !square(&shunt.g) || !square(&shunt.b) {
686            return Err(Error::Mtx(format!(
687                "shunt `{}` states a matrix that is not finite and {size} by {size}",
688                shunt.name
689            )));
690        }
691        primitives.push(PassivePrimitive {
692            family: PassiveFamily::Shunt,
693            name: &shunt.name,
694            terminals: shunt
695                .terminal_map
696                .iter()
697                .map(|terminal| (shunt.bus.as_str(), terminal.as_str()))
698                .collect(),
699            primitive: calc_shunt_primitive_admittance(shunt),
700        });
701    }
702
703    for capacitor in network.capacitors() {
704        match calc_capacitor_primitive_admittance(network, capacitor)? {
705            Some(primitive) => primitives.push(PassivePrimitive {
706                family: PassiveFamily::Capacitor,
707                name: &capacitor.name,
708                terminals: capacitor
709                    .terminal_map
710                    .iter()
711                    .map(|terminal| (capacitor.bus.as_str(), terminal.as_str()))
712                    .collect(),
713                primitive,
714            }),
715            None => diagnostics.push(Diagnostic::of(
716                &codes::BUILD_MULTI_UNSUPPORTED_STAMP,
717                format!(
718                    "capacitor `{}` states a configuration this builder does not stamp",
719                    capacitor.name
720                ),
721            )),
722        }
723    }
724
725    let mut grounded: Vec<GroundedNeutral<'_>> = Vec::new();
726    let mut ideal_transformers = Vec::new();
727    for transformer in network.transformers() {
728        if powerio_dist::transformer::transformer_states_no_leakage(transformer) {
729            ideal_transformers.push(transformer);
730            continue;
731        }
732        let element = calc_transformer_primitive_admittance(network, transformer)?;
733        for &(bus, terminal) in &element.grounded {
734            if !grounded
735                .iter()
736                .any(|g| g.bus.eq_ignore_ascii_case(bus) && g.terminal == terminal)
737            {
738                grounded.push(GroundedNeutral {
739                    transformer: element.name,
740                    bus,
741                    terminal,
742                });
743            }
744        }
745        primitives.push(PassivePrimitive {
746            family: PassiveFamily::Transformer,
747            name: element.name,
748            terminals: element.terminals,
749            primitive: element.primitive,
750        });
751    }
752    Ok(NetworkPrimitives {
753        elements: primitives,
754        grounded,
755        ideal_transformers,
756        diagnostics,
757    })
758}
759
760/// Build the passive nodal admittance and the ideal equipment constraints.
761///
762/// # Errors
763/// A structurally broken network: an element naming an undeclared bus or
764/// terminal, or a line whose terminal maps disagree with its linecode shape.
765/// Everything the builder cannot stamp exactly is a structured diagnostic,
766/// never a silent omission or a fabricated impedance.
767pub fn calc_multiconductor_admittance_matrix(
768    network: &MulticonductorNetwork,
769) -> Result<MulticonductorAdmittance> {
770    powerio_dist::require_electrical_readiness(network)?;
771    let primitives = calc_passive_primitives(network)?;
772    assemble_multiconductor_admittance(network, &primitives)
773}
774
775/// [`calc_multiconductor_admittance_matrix`] over element primitives the
776/// caller already holds from [`calc_passive_primitives`] of the same
777/// network: a caller that also reads each element's primitive (for its port
778/// currents) lists them once. The one assembly of the multiconductor nodal
779/// system and its source, ideal transformer and grounded neutral rows.
780///
781/// # Errors
782/// As [`calc_multiconductor_admittance_matrix`], except that the network's
783/// electrical readiness is not checked again.
784#[allow(clippy::too_many_lines)] // one stamp block per element family
785#[allow(clippy::many_single_char_names)] // n and per conductor y/z/b follow the textbook stamps
786pub fn assemble_multiconductor_admittance(
787    network: &MulticonductorNetwork,
788    primitives: &NetworkPrimitives<'_>,
789) -> Result<MulticonductorAdmittance> {
790    let index = MulticonductorNodeIndex::build(network)?;
791    let n = index.len();
792    let mut stamper = Stamper::new(n);
793    let mut diagnostics = Vec::new();
794
795    let resolve = |bus: &str, terminal: &str, element: &str| -> Result<NodeRef> {
796        index.resolve(bus, terminal).ok_or_else(|| {
797            Error::Mtx(format!(
798                "{element} names terminal `{terminal}` bus `{bus}` does not declare"
799            ))
800        })
801    };
802
803    // Lines, shunts, capacitor banks and leakage transformers: the network's
804    // one element list, scattered over the node references of its
805    // terminals.
806    let elements = primitives;
807    let transformer_constraints =
808        transformer::ideal_wye_constraints(network, &elements.ideal_transformers, &index)?;
809    diagnostics.extend(elements.diagnostics.iter().cloned());
810    for element in &elements.elements {
811        let label = format!("{} `{}`", element.family.noun(), element.name);
812        let terminals: Vec<NodeRef> = element
813            .terminals
814            .iter()
815            .map(|&(bus, terminal)| resolve(bus, terminal, &label))
816            .collect::<Result<_>>()?;
817        stamper.add_primitive(&terminals, &element.primitive)?;
818    }
819
820    // Ideal equipment: constraint rows over the node voltages, collected as
821    // triplets until the row count is known.
822    let mut constraint_re: Vec<(usize, usize, f64)> = Vec::new();
823    let constraint_im: Vec<(usize, usize, f64)> = Vec::new();
824    let mut rhs_re = Vec::new();
825    let mut rhs_im = Vec::new();
826    let mut labels = Vec::new();
827    let mut rows = 0usize;
828
829    // Each source specifies a voltage difference. The transpose of the
830    // incidence rows supplies equal opposite reference-terminal currents.
831    for source in network.sources() {
832        let reference =
833            source
834                .reference_terminal
835                .as_ref()
836                .map_or(Ok(NodeRef::Ground), |terminal| {
837                    resolve(
838                        &source.bus,
839                        terminal,
840                        &format!("source `{}` reference", source.name),
841                    )
842                })?;
843        for (position, terminal) in source.terminal_map.iter().enumerate() {
844            let node = resolve(&source.bus, terminal, &format!("source `{}`", source.name))?;
845            let magnitude = source.v_magnitude.get(position).copied().unwrap_or(0.0);
846            let angle = source.v_angle.get(position).copied().unwrap_or(0.0);
847            // A terminal that is its own reference (ground, or the stated
848            // reference terminal) has no voltage to prescribe: zero is
849            // already true there, anything else contradicts it.
850            if node == reference {
851                if magnitude != 0.0 {
852                    return Err(Error::Mtx(format!(
853                        "source `{}` has a nonzero voltage across electrically identical terminals",
854                        source.name
855                    )));
856                }
857                continue;
858            }
859            if let NodeRef::Node(dense) = node {
860                constraint_re.push((rows, dense, 1.0));
861            }
862            if let NodeRef::Node(dense) = reference {
863                constraint_re.push((rows, dense, -1.0));
864            }
865            rhs_re.push(magnitude * angle.cos());
866            rhs_im.push(magnitude * angle.sin());
867            labels.push(format!("source:{}:{terminal}", source.name));
868            rows += 1;
869        }
870    }
871
872    // WYE constraints use phase-to-neutral voltages on each side. The
873    // transpose carries each winding's neutral current into nodal balance.
874    for constraint in transformer_constraints {
875        for (column, coefficient) in constraint.coefficients {
876            constraint_re.push((rows, column, coefficient));
877        }
878        rhs_re.push(0.0);
879        rhs_im.push(0.0);
880        labels.push(constraint.label);
881        rows += 1;
882    }
883
884    // A solidly grounded transformer neutral: v = 0, its transpose the
885    // neutral's ground current, once per node. A source row that already
886    // fixes the node alone settles it (`GroundedNeutral::needs_zero_voltage_row`).
887    let mut fixed_by_source: BTreeMap<usize, Complex64> = BTreeMap::new();
888    for row in 0..rows {
889        let entries: Vec<&(usize, usize, f64)> =
890            constraint_re.iter().filter(|(r, _, _)| *r == row).collect();
891        // A one entry source row is `±v = rhs` (the node, or a reference
892        // terminal against ground).
893        if let [(_, dense, coefficient)] = entries.as_slice()
894            && labels[row].starts_with("source:")
895        {
896            fixed_by_source.insert(
897                *dense,
898                Complex64::new(rhs_re[row], rhs_im[row]) / *coefficient,
899            );
900        }
901    }
902    let mut grounded_nodes: BTreeSet<usize> = BTreeSet::new();
903    for neutral in &elements.grounded {
904        let label = format!("transformer `{}`", neutral.transformer);
905        let NodeRef::Node(dense) = resolve(neutral.bus, neutral.terminal, &label)? else {
906            continue;
907        };
908        if !grounded_nodes.insert(dense)
909            || !neutral.needs_zero_voltage_row(fixed_by_source.get(&dense).copied())?
910        {
911            continue;
912        }
913        constraint_re.push((rows, dense, 1.0));
914        rhs_re.push(0.0);
915        rhs_im.push(0.0);
916        labels.push(format!(
917            "transformer:{}:neutral:{}.{}",
918            neutral.transformer, neutral.bus, neutral.terminal
919        ));
920        rows += 1;
921    }
922
923    // Injections (loads, generators) are boundary data, never admittance;
924    // families with no exact stamp are reported.
925    for ibr in network.ibrs() {
926        diagnostics.push(
927            Diagnostic::of(
928                &codes::BUILD_MULTI_UNSUPPORTED_STAMP,
929                format!(
930                    "inverter based resource `{}` has no passive admittance stamp; it is an injection, not an admittance",
931                    ibr.name
932                ),
933            )
934            ,
935        );
936    }
937
938    let build_constraints = |triplets: &[(usize, usize, f64)]| {
939        let mut builder = CooBuilder::new_rect(rows.max(1), n.max(1));
940        for &(row, column, value) in triplets {
941            builder.add(row, column, value);
942        }
943        let mut matrix = builder.finish_csr();
944        if rows == 0 || n == 0 {
945            matrix = CooBuilder::new_rect(rows.max(1), n.max(1)).finish_csr();
946        }
947        matrix
948    };
949    let augmented = AugmentedSystem {
950        constraint_re: build_constraints(&constraint_re),
951        constraint_im: build_constraints(&constraint_im),
952        rhs_re,
953        rhs_im,
954        labels,
955    };
956    Ok(MulticonductorAdmittance {
957        index,
958        conductance: stamper.conductance.finish_csr(),
959        susceptance: stamper.susceptance.finish_csr(),
960        augmented,
961        diagnostics,
962    })
963}