Skip to main content

powerio_dist/
model.rs

1//! The canonical multiconductor network model.
2//!
3//! Wire coordinates with BMOPF semantics: string bus ids, ordered string
4//! terminal names per bus, explicit grounding on buses, terminal maps on
5//! every element, SI units (V, W, var, ohm, S, meters) and radians. Terminal
6//! names are the OpenDSS node numbers as strings; implicit ground
7//! connections become an explicit perfectly grounded neutral
8//! terminal on the bus (named 4 on a three phase bus), the convention
9//! PowerModelsDistribution and the public BMOPF examples share.
10//!
11//! Transformer impedances stay in the per unit form the source formats use
12//! (`r_pct`, `xsc_pct` as percent of the winding base); the BMOPF writer
13//! converts to ohms on the wye side at emission. Everything an element
14//! carries beyond the typed fields lives in its `extras` map.
15
16use std::collections::BTreeMap;
17
18use serde::{Deserialize, Serialize};
19
20use crate::geo::{DistGeoMeta, DistLocation};
21
22mod bus_index;
23mod located_network;
24
25pub type Extras = BTreeMap<String, serde_json::Value>;
26
27/// A square matrix in conductor order, row major.
28pub type ConductorMatrix = Vec<Vec<f64>>;
29
30/// Where the network came from; fixes the echo tier target.
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
32#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
33#[serde(rename_all = "kebab-case")]
34#[non_exhaustive]
35pub enum DistSourceFormat {
36    Dss,
37    BmopfJson,
38    PmdJson,
39    CimDist,
40    Sincal,
41    // Keep variant comments out of the schema: IR 2 represents this as a
42    // string enum, rather than a union of documented constants.
43    // MG-RAVENS JSON, the multiconductor (distribution) profile.
44    RavensJson,
45    // PowerModelsDistribution MATHEMATICAL model JSON.
46    PmdMathJson,
47    // pandapower JSON of a three-phase (runpp_3ph) network.
48    PandapowerJson,
49}
50
51impl DistSourceFormat {
52    /// The canonical source format name. A read-only format need not have a
53    /// corresponding [`crate::DistTargetFormat`].
54    pub fn name(self) -> &'static str {
55        match self {
56            DistSourceFormat::Sincal => "sincal",
57            DistSourceFormat::Dss => "dss",
58            DistSourceFormat::PmdJson => "pmd-json",
59            DistSourceFormat::BmopfJson => "bmopf-json",
60            DistSourceFormat::CimDist => "cim-dist",
61            DistSourceFormat::RavensJson => "ravens-json",
62            DistSourceFormat::PmdMathJson => "pmd-math-json",
63            DistSourceFormat::PandapowerJson => "pandapower-json",
64        }
65    }
66}
67
68#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
69#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
70#[non_exhaustive]
71pub struct DistBus {
72    pub id: String,
73    /// Ordered terminal names; OpenDSS node numbers as strings.
74    pub terminals: Vec<String>,
75    /// Terminals tied to ground with zero impedance.
76    pub grounded: Vec<String>,
77    /// Voltage magnitude bounds, volts: the scalar pair plus the phase to
78    /// neutral and phase to phase families, and the per-sequence scalars
79    /// (as in BMOPF: positive sequence has both bounds, negative and
80    /// zero sequence and neutral to ground are magnitude caps whose lower
81    /// bound is always 0).
82    pub v_min: Option<f64>,
83    pub v_max: Option<f64>,
84    /// Nonuniform phase-to-ground bounds in phase-terminal order, volts.
85    /// A scalar bound, when present, takes precedence over this vector.
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub v_min_phase: Option<Vec<f64>>,
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub v_max_phase: Option<Vec<f64>>,
90    pub vpn_min: Option<Vec<f64>>,
91    pub vpn_max: Option<Vec<f64>>,
92    pub vpp_min: Option<Vec<f64>>,
93    pub vpp_max: Option<Vec<f64>>,
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub vpos_min: Option<f64>,
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub vpos_max: Option<f64>,
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub vneg_max: Option<f64>,
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub vzero_max: Option<f64>,
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub vn_max: Option<f64>,
104    /// Optional bus coordinates in the network coordinate space.
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub location: Option<DistLocation>,
107    pub extras: Extras,
108}
109
110impl DistBus {
111    /// The role of one of this bus's terminals ([`calc_terminal_role`] over
112    /// the bus's terminal names).
113    #[must_use]
114    pub fn terminal_role(
115        &self,
116        terminal: &str,
117        conventions: Option<&serde_json::Value>,
118    ) -> TerminalRole {
119        calc_terminal_role(&self.terminals, terminal, conventions)
120    }
121
122    /// Phase positions in terminal order: the terminals whose
123    /// [`calc_terminal_role`] is [`TerminalRole::Phase`], using explicit BMOPF
124    /// roles when supplied.
125    #[must_use]
126    pub fn phase_indices(&self, conventions: Option<&serde_json::Value>) -> Vec<usize> {
127        self.role_indices(TerminalRole::Phase, conventions)
128    }
129
130    /// Neutral positions in terminal order: the terminals whose
131    /// [`calc_terminal_role`] is [`TerminalRole::Neutral`].
132    #[must_use]
133    pub fn neutral_indices(&self, conventions: Option<&serde_json::Value>) -> Vec<usize> {
134        self.role_indices(TerminalRole::Neutral, conventions)
135    }
136
137    fn role_indices(
138        &self,
139        role: TerminalRole,
140        conventions: Option<&serde_json::Value>,
141    ) -> Vec<usize> {
142        self.terminals
143            .iter()
144            .enumerate()
145            .filter(|(_, terminal)| self.terminal_role(terminal, conventions) == role)
146            .map(|(index, _)| index)
147            .collect()
148    }
149
150    #[must_use]
151    pub fn new(id: impl Into<String>, terminals: Vec<String>) -> Self {
152        Self {
153            id: id.into(),
154            terminals,
155            grounded: Vec::new(),
156            v_min: None,
157            v_max: None,
158            v_min_phase: None,
159            v_max_phase: None,
160            vpn_min: None,
161            vpn_max: None,
162            vpp_min: None,
163            vpp_max: None,
164            vpos_min: None,
165            vpos_max: None,
166            vneg_max: None,
167            vzero_max: None,
168            vn_max: None,
169            location: None,
170            extras: Extras::new(),
171        }
172    }
173}
174
175/// The role a terminal plays on its bus ([`calc_terminal_role`]).
176#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
177#[non_exhaustive]
178pub enum TerminalRole {
179    /// A phase conductor.
180    Phase,
181    /// A neutral conductor.
182    Neutral,
183    /// Earth: ground terminal `0`, or a terminal the conventions call earth.
184    Earth,
185}
186
187/// The role of `terminal` among a bus's `terminals`. With BMOPF terminal
188/// conventions (the `terminal_conventions` block, whose `neutral` and
189/// `earth` lists name terminals) a named terminal takes the role it is
190/// named in and every other terminal is a phase. Without conventions `n` or
191/// `N` is neutral, and so is `4` when the terminals are exactly `1` to `4`
192/// (the four wire spelling OpenDSS and PowerModelsDistribution share), and
193/// every other terminal is a phase. Ground terminal `0` is earth either way.
194///
195/// The one terminal classification: [`DistBus::phase_indices`],
196/// [`DistBus::neutral_indices`], the WYE neutral of a connection
197/// ([`crate::calc_wye_neutral_position`]), the BMOPF reader, validator and
198/// writer, the PMD MATHEMATICAL writer, the multiconductor to balanced
199/// lowering, and the CIM and MG-RAVENS readers and writers (over the CIM
200/// wire convention, which those readers state for their networks:
201/// [`MulticonductorNetwork::terminal_conventions`]) read it.
202#[must_use]
203pub fn calc_terminal_role<S: AsRef<str>>(
204    terminals: &[S],
205    terminal: &str,
206    conventions: Option<&serde_json::Value>,
207) -> TerminalRole {
208    if terminal == "0" {
209        return TerminalRole::Earth;
210    }
211    if let Some(roles) = conventions {
212        let named = |role: &str| {
213            roles
214                .get(role)
215                .and_then(serde_json::Value::as_array)
216                .is_some_and(|names| names.iter().any(|name| name.as_str() == Some(terminal)))
217        };
218        return if named("neutral") {
219            TerminalRole::Neutral
220        } else if named("earth") {
221            TerminalRole::Earth
222        } else {
223            TerminalRole::Phase
224        };
225    }
226    let numeric_four = terminals.len() == 4
227        && ["1", "2", "3", "4"]
228            .iter()
229            .all(|t| terminals.iter().any(|v| v.as_ref() == *t));
230    if terminal.eq_ignore_ascii_case("n") || (numeric_four && terminal == "4") {
231        TerminalRole::Neutral
232    } else {
233        TerminalRole::Phase
234    }
235}
236
237#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
238#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
239#[non_exhaustive]
240pub struct DistLineCode {
241    pub name: String,
242    pub n_conductors: usize,
243    /// Series impedance, ohm per meter.
244    pub r_series: ConductorMatrix,
245    pub x_series: ConductorMatrix,
246    /// Shunt admittance halves at each end, S per meter.
247    pub g_from: ConductorMatrix,
248    pub b_from: ConductorMatrix,
249    pub g_to: ConductorMatrix,
250    pub b_to: ConductorMatrix,
251    /// Ampacity per conductor.
252    #[serde(default)]
253    pub i_max: Option<Vec<f64>>,
254    #[serde(default)]
255    pub s_max: Option<Vec<f64>>,
256    /// Origin of the impedance matrices (BMOPF `source`, e.g. "fem",
257    /// "datasheet", "import").
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub source: Option<String>,
260    pub extras: Extras,
261}
262
263impl DistLineCode {
264    #[must_use]
265    pub fn new(
266        name: impl Into<String>,
267        r_series: ConductorMatrix,
268        x_series: ConductorMatrix,
269    ) -> Self {
270        let n_conductors = matrix_extent(&r_series).max(matrix_extent(&x_series));
271        Self {
272            name: name.into(),
273            n_conductors,
274            r_series,
275            x_series,
276            g_from: zero_mat(n_conductors),
277            b_from: zero_mat(n_conductors),
278            g_to: zero_mat(n_conductors),
279            b_to: zero_mat(n_conductors),
280            i_max: None,
281            s_max: None,
282            source: None,
283            extras: Extras::new(),
284        }
285    }
286}
287
288#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
289#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
290#[non_exhaustive]
291pub struct DistLine {
292    pub name: String,
293    pub bus_from: String,
294    pub bus_to: String,
295    pub terminal_map_from: Vec<String>,
296    pub terminal_map_to: Vec<String>,
297    pub linecode: String,
298    /// Meters.
299    pub length: f64,
300    /// Polyline route in the network's coordinate space (`MulticonductorNetwork.geo`),
301    /// present only when a source provides intermediate geometry.
302    /// `#[serde(default)]` so JSON written before the field existed still
303    /// deserializes.
304    #[serde(default, skip_serializing_if = "Option::is_none")]
305    pub route: Option<Vec<DistLocation>>,
306    /// Per-conductor ampacity and apparent power limits, amps and VA
307    /// (BMOPF line fields, alongside the linecode's own).
308    #[serde(default, skip_serializing_if = "Option::is_none")]
309    pub i_max: Option<Vec<f64>>,
310    #[serde(default, skip_serializing_if = "Option::is_none")]
311    pub s_max: Option<Vec<f64>>,
312    pub extras: Extras,
313}
314
315impl DistLine {
316    #[must_use]
317    pub fn new(
318        name: impl Into<String>,
319        bus_from: impl Into<String>,
320        bus_to: impl Into<String>,
321        terminal_map_from: Vec<String>,
322        terminal_map_to: Vec<String>,
323        linecode: impl Into<String>,
324        length: f64,
325    ) -> Self {
326        Self {
327            name: name.into(),
328            bus_from: bus_from.into(),
329            bus_to: bus_to.into(),
330            terminal_map_from,
331            terminal_map_to,
332            linecode: linecode.into(),
333            length,
334            route: None,
335            i_max: None,
336            s_max: None,
337            extras: Extras::new(),
338        }
339    }
340}
341
342/// A rated capacitor bank (the BMOPF `capacitor`): `q_rated` vars
343/// delivered at `v_nom` volts across the element terminals, distinct from the
344/// raw admittance [`DistShunt`]. The DSS converter still lowers OpenDSS
345/// capacitors to shunt B matrices; this element carries capacitors that arrive
346/// as BMOPF input.
347#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
348#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
349#[non_exhaustive]
350pub struct DistCapacitor {
351    pub name: String,
352    pub bus: String,
353    pub terminal_map: Vec<String>,
354    pub configuration: Configuration,
355    /// Nameplate rated reactive power of the whole bank, vars.
356    pub q_rated: f64,
357    /// Nameplate nominal voltage, volts: line to line for the three phase
358    /// configurations, across the terminals for SINGLE_PHASE.
359    pub v_nom: f64,
360    pub extras: Extras,
361}
362
363impl DistCapacitor {
364    #[must_use]
365    pub fn new(
366        name: impl Into<String>,
367        bus: impl Into<String>,
368        terminal_map: Vec<String>,
369        configuration: Configuration,
370        q_rated: f64,
371        v_nom: f64,
372    ) -> Self {
373        Self {
374            name: name.into(),
375            bus: bus.into(),
376            terminal_map,
377            configuration,
378            q_rated,
379            v_nom,
380            extras: Extras::new(),
381        }
382    }
383}
384
385#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
386#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
387#[non_exhaustive]
388pub struct DistSwitch {
389    pub name: String,
390    pub bus_from: String,
391    pub bus_to: String,
392    pub terminal_map_from: Vec<String>,
393    pub terminal_map_to: Vec<String>,
394    pub open: bool,
395    /// Ampacity per conductor.
396    #[serde(default)]
397    pub i_max: Option<Vec<f64>>,
398    pub extras: Extras,
399}
400
401impl DistSwitch {
402    #[must_use]
403    pub fn new(
404        name: impl Into<String>,
405        bus_from: impl Into<String>,
406        bus_to: impl Into<String>,
407        terminal_map_from: Vec<String>,
408        terminal_map_to: Vec<String>,
409        open: bool,
410    ) -> Self {
411        Self {
412            name: name.into(),
413            bus_from: bus_from.into(),
414            bus_to: bus_to.into(),
415            terminal_map_from,
416            terminal_map_to,
417            open,
418            i_max: None,
419            extras: Extras::new(),
420        }
421    }
422}
423
424#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
425#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
426#[serde(rename_all = "snake_case")]
427#[non_exhaustive]
428pub enum Configuration {
429    Wye,
430    Delta,
431    SinglePhase,
432}
433
434#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
435#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
436#[non_exhaustive]
437pub struct DistLoad {
438    pub name: String,
439    pub bus: String,
440    pub terminal_map: Vec<String>,
441    pub configuration: Configuration,
442    /// Watts per phase.
443    pub p_nom: Vec<f64>,
444    /// Vars per phase.
445    pub q_nom: Vec<f64>,
446    pub voltage_model: DistLoadVoltageModel,
447    pub extras: Extras,
448}
449
450impl DistLoad {
451    #[must_use]
452    pub fn new(
453        name: impl Into<String>,
454        bus: impl Into<String>,
455        terminal_map: Vec<String>,
456        configuration: Configuration,
457        p_nom: Vec<f64>,
458        q_nom: Vec<f64>,
459    ) -> Self {
460        Self {
461            name: name.into(),
462            bus: bus.into(),
463            terminal_map,
464            configuration,
465            p_nom,
466            q_nom,
467            voltage_model: DistLoadVoltageModel::default(),
468            extras: Extras::new(),
469        }
470    }
471}
472
473#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
474#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
475#[serde(tag = "model", rename_all = "snake_case")]
476#[non_exhaustive]
477pub enum DistLoadVoltageModel {
478    /// Constant power load. `v_nom` is volts per active phase when the source
479    /// states it.
480    ConstantPower { v_nom: Vec<f64> },
481    /// Constant current load. `v_nom` is volts per active phase.
482    ConstantCurrent { v_nom: Vec<f64> },
483    /// Constant impedance load. `v_nom` is volts per active phase.
484    ConstantImpedance { v_nom: Vec<f64> },
485    /// ZIP load coefficients by active phase. `v_nom` is volts per active
486    /// phase; alpha terms apply to active power and beta terms to reactive
487    /// power.
488    Zip {
489        v_nom: Vec<f64>,
490        alpha_z: Vec<f64>,
491        alpha_i: Vec<f64>,
492        alpha_p: Vec<f64>,
493        beta_z: Vec<f64>,
494        beta_i: Vec<f64>,
495        beta_p: Vec<f64>,
496    },
497    /// Exponential voltage model by active phase. `v_nom` is volts per active
498    /// phase.
499    Exponential {
500        v_nom: Vec<f64>,
501        gamma_p: Vec<f64>,
502        gamma_q: Vec<f64>,
503    },
504    /// ZIP law with low-voltage current interpolation and high-voltage
505    /// impedance continuation. See [`Self::power_scale`] for the equations.
506    /// Below `v_low_pu` the entire nominal load is constant impedance;
507    /// the dropout curve applies only above that threshold.
508    BoundedZip {
509        v_nom: Vec<f64>,
510        alpha_z: Vec<f64>,
511        alpha_i: Vec<f64>,
512        alpha_p: Vec<f64>,
513        beta_z: Vec<f64>,
514        beta_i: Vec<f64>,
515        beta_p: Vec<f64>,
516        v_low_pu: f64,
517        v_min_pu: f64,
518        v_max_pu: f64,
519        cutoff_pu: f64,
520    },
521    /// Exponential law inside a voltage band, with nominal-impedance
522    /// continuation below `v_low_pu`, current interpolation up to `v_min_pu`,
523    /// and impedance continuation above `v_max_pu`. The continuations apply
524    /// equally to P and Q, independently of their middle-band exponents.
525    /// See [`Self::power_scale`] for the equations. Arrays follow active branches.
526    BoundedExponential {
527        v_nom: Vec<f64>,
528        gamma_p: Vec<f64>,
529        gamma_q: Vec<f64>,
530        v_low_pu: f64,
531        v_min_pu: f64,
532        v_max_pu: f64,
533    },
534    /// Constant power between positive voltage bounds, with impedance
535    /// continuation outside them and an optional current-magnitude limit.
536    /// `v_nom` is volts per active branch. `current_limit_pu` is a multiple
537    /// of that branch's nominal apparent power divided by nominal voltage.
538    /// P and Q share one scale, preserving power factor. See [`Self::power_scale`].
539    BoundedConstantPower {
540        v_nom: Vec<f64>,
541        v_min_pu: f64,
542        v_max_pu: f64,
543        current_limit_pu: Option<f64>,
544    },
545}
546
547impl Default for DistLoadVoltageModel {
548    fn default() -> Self {
549        Self::ConstantPower { v_nom: Vec::new() }
550    }
551}
552
553impl DistLoadVoltageModel {
554    #[must_use]
555    pub fn v_nom(&self) -> &[f64] {
556        match self {
557            Self::ConstantPower { v_nom }
558            | Self::ConstantCurrent { v_nom }
559            | Self::ConstantImpedance { v_nom }
560            | Self::Zip { v_nom, .. }
561            | Self::Exponential { v_nom, .. }
562            | Self::BoundedZip { v_nom, .. }
563            | Self::BoundedConstantPower { v_nom, .. }
564            | Self::BoundedExponential { v_nom, .. } => v_nom,
565        }
566    }
567}
568
569#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
570#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
571#[non_exhaustive]
572pub struct DistGenerator {
573    pub name: String,
574    pub bus: String,
575    pub terminal_map: Vec<String>,
576    pub configuration: Configuration,
577    /// Setpoint, watts per phase.
578    pub p_nom: Vec<f64>,
579    pub q_nom: Vec<f64>,
580    /// Bounds per phase.
581    #[serde(default)]
582    pub p_min: Option<Vec<f64>>,
583    #[serde(default)]
584    pub p_max: Option<Vec<f64>>,
585    #[serde(default)]
586    pub q_min: Option<Vec<f64>>,
587    #[serde(default)]
588    pub q_max: Option<Vec<f64>>,
589    /// Generation cost, $/kWh per phase conductor, exactly as the source
590    /// states it: one entry per phase, or a single entry for a scalar
591    /// statement. No OpenDSS equivalent, so it is None until a format
592    /// supplies it.
593    pub cost: Option<Vec<f64>>,
594    /// Per-conductor apparent power and current limits, VA and amps (BMOPF
595    /// generator fields, alongside the p/q bounds).
596    #[serde(default, skip_serializing_if = "Option::is_none")]
597    pub s_max: Option<Vec<f64>>,
598    #[serde(default, skip_serializing_if = "Option::is_none")]
599    pub i_max: Option<Vec<f64>>,
600    pub extras: Extras,
601}
602
603impl DistGenerator {
604    #[must_use]
605    pub fn new(
606        name: impl Into<String>,
607        bus: impl Into<String>,
608        terminal_map: Vec<String>,
609        configuration: Configuration,
610        p_nom: Vec<f64>,
611        q_nom: Vec<f64>,
612    ) -> Self {
613        Self {
614            name: name.into(),
615            bus: bus.into(),
616            terminal_map,
617            configuration,
618            p_nom,
619            q_nom,
620            p_min: None,
621            p_max: None,
622            q_min: None,
623            q_max: None,
624            cost: None,
625            s_max: None,
626            i_max: None,
627            extras: Extras::new(),
628        }
629    }
630}
631
632#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
633#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
634#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
635#[non_exhaustive]
636pub enum IbrTopology {
637    SinglePhase,
638    ThreeLeg,
639    FourLeg,
640}
641
642#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
643#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
644#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
645#[non_exhaustive]
646pub enum IbrPrimeMover {
647    Pv,
648    Battery,
649    Generic,
650    Statcom,
651    Dstatcom,
652}
653
654#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
655#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
656#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
657#[non_exhaustive]
658pub enum IbrVoltageAggregation {
659    PerPhase,
660    Average,
661}
662
663#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
664#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
665#[non_exhaustive]
666pub struct DistIbr {
667    pub name: String,
668    pub bus: String,
669    pub terminal_map: Vec<String>,
670    pub topology: IbrTopology,
671    pub prime_mover: IbrPrimeMover,
672    /// Per phase apparent power nameplate ratings, volt amperes.
673    pub s_max: Vec<f64>,
674    /// Per conductor current limits, amperes.
675    #[serde(default)]
676    pub i_max: Option<Vec<f64>>,
677    /// Available active power, watts.
678    pub p_avail: Option<f64>,
679    #[serde(default)]
680    pub p_min: Option<Vec<f64>>,
681    #[serde(default)]
682    pub p_max: Option<Vec<f64>>,
683    #[serde(default)]
684    pub q_min: Option<Vec<f64>>,
685    #[serde(default)]
686    pub q_max: Option<Vec<f64>>,
687    pub control_profile: Option<String>,
688    pub voltage_aggregation: Option<IbrVoltageAggregation>,
689    pub extras: Extras,
690}
691
692impl DistIbr {
693    #[must_use]
694    pub fn new(
695        name: impl Into<String>,
696        bus: impl Into<String>,
697        terminal_map: Vec<String>,
698        topology: IbrTopology,
699        prime_mover: IbrPrimeMover,
700        s_max: Vec<f64>,
701    ) -> Self {
702        Self {
703            name: name.into(),
704            bus: bus.into(),
705            terminal_map,
706            topology,
707            prime_mover,
708            s_max,
709            i_max: None,
710            p_avail: None,
711            p_min: None,
712            p_max: None,
713            q_min: None,
714            q_max: None,
715            control_profile: None,
716            voltage_aggregation: None,
717            extras: Extras::new(),
718        }
719    }
720}
721
722#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
723#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
724#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
725#[non_exhaustive]
726pub enum ControlVoltageReference {
727    PnPerPhase,
728    PpPerPhase,
729    PpAveraged,
730    PgAveraged,
731    PnAveraged,
732    PgPerPhase,
733}
734
735#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
736#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
737#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
738#[non_exhaustive]
739pub enum ReactivePowerUnit {
740    VaFraction,
741    Var,
742}
743
744#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
745#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
746#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
747#[non_exhaustive]
748pub enum ActivePowerUnit {
749    VaFraction,
750    W,
751}
752
753#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
754#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
755#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
756#[non_exhaustive]
757pub enum ReactivePowerReference {
758    VarMax,
759    VarAvailable,
760}
761
762#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
763#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
764#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
765#[non_exhaustive]
766pub enum ActivePowerReference {
767    PAvailable,
768    PMax,
769    SMax,
770}
771
772#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
773#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
774#[non_exhaustive]
775pub struct PowerFactorControl {
776    pub pf: f64,
777}
778
779#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
780#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
781#[non_exhaustive]
782pub struct VoltVarControl {
783    pub voltage_reference: Option<ControlVoltageReference>,
784    pub breakpoints: Vec<f64>,
785    pub q_limits: Vec<f64>,
786    pub q_unit: Option<ReactivePowerUnit>,
787    pub q_ref: Option<ReactivePowerReference>,
788    pub p_min_for_q: Option<f64>,
789    pub p_min_for_q_max: Option<f64>,
790}
791
792#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
793#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
794#[non_exhaustive]
795pub struct VoltWattControl {
796    pub voltage_reference: Option<ControlVoltageReference>,
797    pub breakpoints: Vec<f64>,
798    pub p_limits: Vec<f64>,
799    pub p_unit: Option<ActivePowerUnit>,
800    pub p_ref: Option<ActivePowerReference>,
801}
802
803#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
804#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
805#[non_exhaustive]
806pub struct DistControlProfile {
807    pub name: String,
808    pub power_factor: Option<PowerFactorControl>,
809    pub volt_var: Option<VoltVarControl>,
810    pub volt_watt: Option<VoltWattControl>,
811    pub extras: Extras,
812}
813
814impl DistControlProfile {
815    #[must_use]
816    pub fn new(name: impl Into<String>) -> Self {
817        Self {
818            name: name.into(),
819            power_factor: None,
820            volt_var: None,
821            volt_watt: None,
822            extras: Extras::new(),
823        }
824    }
825}
826
827#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
828#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
829#[non_exhaustive]
830pub struct DistShunt {
831    pub name: String,
832    pub bus: String,
833    pub terminal_map: Vec<String>,
834    /// Total siemens in conductor order.
835    pub g: ConductorMatrix,
836    pub b: ConductorMatrix,
837    pub extras: Extras,
838}
839
840impl DistShunt {
841    #[must_use]
842    pub fn new(
843        name: impl Into<String>,
844        bus: impl Into<String>,
845        terminal_map: Vec<String>,
846        g: ConductorMatrix,
847        b: ConductorMatrix,
848    ) -> Self {
849        Self {
850            name: name.into(),
851            bus: bus.into(),
852            terminal_map,
853            g,
854            b,
855            extras: Extras::new(),
856        }
857    }
858}
859
860#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
861#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
862#[serde(rename_all = "snake_case")]
863#[non_exhaustive]
864pub enum DistWindingConn {
865    Wye,
866    Delta,
867}
868
869#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
870#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
871#[non_exhaustive]
872pub struct DistWinding {
873    pub bus: String,
874    pub terminal_map: Vec<String>,
875    pub conn: DistWindingConn,
876    /// Rated winding voltage, volts (line to line for 2 and 3 phase).
877    pub v_ref: f64,
878    /// Volt amperes.
879    pub s_rating: f64,
880    /// Winding resistance, percent of the winding base.
881    pub r_pct: f64,
882    pub tap: f64,
883    #[serde(default, skip_serializing_if = "Option::is_none")]
884    pub r_neutral: Option<f64>,
885    #[serde(default, skip_serializing_if = "Option::is_none")]
886    pub x_neutral: Option<f64>,
887}
888
889impl DistWinding {
890    #[must_use]
891    pub fn new(
892        bus: impl Into<String>,
893        terminal_map: Vec<String>,
894        conn: DistWindingConn,
895        v_ref: f64,
896        s_rating: f64,
897    ) -> Self {
898        Self {
899            bus: bus.into(),
900            terminal_map,
901            conn,
902            v_ref,
903            s_rating,
904            r_pct: 0.0,
905            tap: 1.0,
906            r_neutral: None,
907            x_neutral: None,
908        }
909    }
910}
911
912#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
913#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
914#[non_exhaustive]
915pub struct DistTransformer {
916    pub name: String,
917    pub windings: Vec<DistWinding>,
918    /// Short circuit reactances between winding pairs, percent:
919    /// Upper-triangular order `12, 13, ..., 1n, 23, ..., (n-1)n`,
920    /// on winding 1's power base, matching OpenDSS `Xscarray`.
921    pub xsc_pct: Vec<f64>,
922    pub phases: usize,
923    pub extras: Extras,
924}
925
926impl DistTransformer {
927    #[must_use]
928    pub fn new(
929        name: impl Into<String>,
930        windings: Vec<DistWinding>,
931        xsc_pct: Vec<f64>,
932        phases: usize,
933    ) -> Self {
934        Self {
935            name: name.into(),
936            windings,
937            xsc_pct,
938            phases,
939            extras: Extras::new(),
940        }
941    }
942}
943
944mod voltage_source;
945pub use voltage_source::VoltageSource;
946
947/// An object the reader recognized but does not type: preserved by class,
948/// name, and raw property text so conversions can warn precisely.
949#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
950#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
951#[non_exhaustive]
952pub struct UntypedObject {
953    pub class: String,
954    pub name: String,
955    pub props: Vec<(Option<String>, String)>,
956}
957
958impl UntypedObject {
959    #[must_use]
960    pub fn new(
961        class: impl Into<String>,
962        name: impl Into<String>,
963        props: Vec<(Option<String>, String)>,
964    ) -> Self {
965        Self {
966            class: class.into(),
967            name: name.into(),
968            props,
969        }
970    }
971}
972
973/// A multiconductor distribution network: an immutable cheap to clone owning
974/// handle over private shared tables.
975///
976/// Cloning the handle bumps one reference count and clones no table
977/// allocation. Reads go through the per field accessors; the `*_mut`
978/// accessors copy the shared tables once on first write to a shared handle
979/// (copy on write), so no other handle ever observes a mutation. Per element
980/// (`"class.name"` key), the tables also record which fields the reader
981/// materialized from a format default rather than the source text. The
982/// original source text for the byte exact echo tier is not carried here; it
983/// lives on the [`PioModule`](powerio_core::PioModule) a parse returns,
984/// alongside this network.
985#[derive(Clone)]
986pub struct MulticonductorNetwork {
987    tables: std::sync::Arc<MulticonductorNetworkTables>,
988    /// Bus positions by name for [`MulticonductorNetwork::bus`], derived
989    /// from `tables` on demand and shared by the handles that share them.
990    bus_index: std::sync::Arc<bus_index::BusIndex>,
991}
992
993// The derived text of the tables alone: the index is derived data.
994#[allow(clippy::missing_fields_in_debug)]
995impl std::fmt::Debug for MulticonductorNetwork {
996    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
997        f.debug_struct("MulticonductorNetwork")
998            .field("tables", &self.tables)
999            .finish()
1000    }
1001}
1002
1003impl MulticonductorNetwork {
1004    pub(crate) fn from_tables(tables: MulticonductorNetworkTables) -> Self {
1005        Self {
1006            tables: std::sync::Arc::new(tables),
1007            bus_index: std::sync::Arc::default(),
1008        }
1009    }
1010
1011    /// The one mutation door: copies the shared tables on first write to a
1012    /// shared handle, so no other handle observes the change. This handle
1013    /// leaves here with an empty bus index no other handle holds, before the
1014    /// caller can change a bus; a handle that shared the old index keeps it
1015    /// with the tables it was built from. Handles share an index only by
1016    /// `Clone`, which shares the tables with it.
1017    pub(crate) fn tables_mut(&mut self) -> &mut MulticonductorNetworkTables {
1018        match std::sync::Arc::get_mut(&mut self.bus_index) {
1019            Some(index) => index.clear(),
1020            None => self.bus_index = std::sync::Arc::default(),
1021        }
1022        std::sync::Arc::make_mut(&mut self.tables)
1023    }
1024}
1025
1026/// A multiconductor distribution network.
1027///
1028/// `source` retains the original text for the byte exact echo tier;
1029/// `defaulted` records, per element (`"class.name"` key), the fields the
1030/// reader materialized from format defaults rather than the source text.
1031// The one owned table store behind the `MulticonductorNetwork` handle.
1032#[derive(Clone, Debug, Serialize, Deserialize)]
1033#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1034#[cfg_attr(feature = "schema", schemars(rename = "MulticonductorNetwork"))]
1035#[serde(remote = "Self")]
1036pub(crate) struct MulticonductorNetworkTables {
1037    pub name: Option<String>,
1038    /// Hz.
1039    pub base_frequency: f64,
1040    #[serde(default, skip_serializing_if = "Option::is_none")]
1041    pub geo: Option<DistGeoMeta>,
1042    /// Component geography uses a distinct stored network wrapper. The legacy
1043    /// network body and its schema remain unchanged when this table is empty.
1044    #[serde(skip)]
1045    pub component_locations: Vec<crate::DistComponentLocation>,
1046    pub buses: Vec<DistBus>,
1047    #[serde(rename = "linecodes")]
1048    pub line_codes: Vec<DistLineCode>,
1049    pub lines: Vec<DistLine>,
1050    pub switches: Vec<DistSwitch>,
1051    pub transformers: Vec<DistTransformer>,
1052    pub loads: Vec<DistLoad>,
1053    pub generators: Vec<DistGenerator>,
1054    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1055    pub ibrs: Vec<DistIbr>,
1056    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1057    pub control_profiles: Vec<DistControlProfile>,
1058    pub shunts: Vec<DistShunt>,
1059    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1060    pub capacitors: Vec<DistCapacitor>,
1061    /// BMOPF allows exactly one; the model allows any number and the BMOPF
1062    /// writer warns beyond the first.
1063    pub sources: Vec<VoltageSource>,
1064    #[serde(rename = "untyped")]
1065    pub untyped_objects: Vec<UntypedObject>,
1066    /// Source commands and options the typed model does not interpret
1067    /// (`solve`, `set mode=...`), in order, as (verb, args).
1068    pub commands: Vec<(String, String)>,
1069    pub options: Vec<(String, String)>,
1070    /// Per-element record of which fields were materialized from a format
1071    /// default. Skipped in the `.pio.json` payload: the field holds
1072    /// `&'static str` (no `Deserialize`), and these defaulted fields belong in
1073    /// the module source map with `mapping_kind = defaulted`, not in the
1074    /// network value. See
1075    /// <https://eigenergy.github.io/powerio/guide/pio-json-schema.html>.
1076    #[serde(skip)]
1077    pub defaulted: BTreeMap<String, Vec<&'static str>>,
1078    pub source_format: Option<DistSourceFormat>,
1079    pub extras: Extras,
1080}
1081
1082// `remote = "Self"` turns the derived serde impls into inherent functions;
1083// routing them through `powerio_core::nonfinite` spells a nonfinite float as
1084// `"Infinity"`/`"-Infinity"`/`"NaN"` on every JSON route, the same convention
1085// as the balanced model.
1086impl serde::Serialize for MulticonductorNetwork {
1087    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1088        located_network::serialize(self, serializer)
1089    }
1090}
1091
1092impl<'de> serde::Deserialize<'de> for MulticonductorNetwork {
1093    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1094        located_network::deserialize(deserializer)
1095    }
1096}
1097
1098#[cfg(feature = "schema")]
1099impl schemars::JsonSchema for MulticonductorNetwork {
1100    fn schema_name() -> std::borrow::Cow<'static, str> {
1101        <MulticonductorNetworkTables as schemars::JsonSchema>::schema_name()
1102    }
1103
1104    fn schema_id() -> std::borrow::Cow<'static, str> {
1105        <MulticonductorNetworkTables as schemars::JsonSchema>::schema_id()
1106    }
1107
1108    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
1109        located_network::json_schema(generator)
1110    }
1111}
1112
1113macro_rules! dist_table_accessors {
1114    ($($field:ident, $field_mut:ident: $ty:ty;)+) => {
1115        impl MulticonductorNetwork {
1116            $(
1117                #[must_use]
1118                pub fn $field(&self) -> &$ty {
1119                    &self.tables.$field
1120                }
1121
1122                /// Mutable access to the same table; a shared handle copies
1123                /// its tables once here, so no other handle observes the
1124                /// change.
1125                #[must_use]
1126                pub fn $field_mut(&mut self) -> &mut $ty {
1127                    &mut self.tables_mut().$field
1128                }
1129            )+
1130        }
1131    };
1132}
1133
1134dist_table_accessors! {
1135    name, name_mut: Option<String>;
1136    geo, geo_mut: Option<DistGeoMeta>;
1137    component_locations, component_locations_mut: Vec<crate::DistComponentLocation>;
1138    buses, buses_mut: Vec<DistBus>;
1139    line_codes, line_codes_mut: Vec<DistLineCode>;
1140    lines, lines_mut: Vec<DistLine>;
1141    switches, switches_mut: Vec<DistSwitch>;
1142    transformers, transformers_mut: Vec<DistTransformer>;
1143    loads, loads_mut: Vec<DistLoad>;
1144    generators, generators_mut: Vec<DistGenerator>;
1145    ibrs, ibrs_mut: Vec<DistIbr>;
1146    control_profiles, control_profiles_mut: Vec<DistControlProfile>;
1147    shunts, shunts_mut: Vec<DistShunt>;
1148    capacitors, capacitors_mut: Vec<DistCapacitor>;
1149    sources, sources_mut: Vec<VoltageSource>;
1150    untyped_objects, untyped_objects_mut: Vec<UntypedObject>;
1151    commands, commands_mut: Vec<(String, String)>;
1152    options, options_mut: Vec<(String, String)>;
1153    defaulted, defaulted_mut: BTreeMap<String, Vec<&'static str>>;
1154    source_format, source_format_mut: Option<DistSourceFormat>;
1155    extras, extras_mut: Extras;
1156}
1157
1158impl MulticonductorNetwork {
1159    /// The network's terminal conventions, which [`calc_terminal_role`]
1160    /// reads: the BMOPF `terminal_conventions` its source stated (the
1161    /// `bmopf_terminal_conventions` extra), else, for a network read from
1162    /// distribution CIM or MG-RAVENS, the CIM wire convention those readers
1163    /// state (`4`, `n` or `N` is the neutral on every bus, so a single phase
1164    /// bus `[1, 4]` has a neutral); `None` otherwise.
1165    #[must_use]
1166    pub fn terminal_conventions(&self) -> Option<&serde_json::Value> {
1167        self.tables
1168            .extras
1169            .get("bmopf_terminal_conventions")
1170            .or_else(|| match self.tables.source_format {
1171                Some(DistSourceFormat::CimDist | DistSourceFormat::RavensJson) => {
1172                    Some(crate::cim::wire_conventions())
1173                }
1174                _ => None,
1175            })
1176    }
1177
1178    /// Hz.
1179    #[must_use]
1180    pub fn base_frequency(&self) -> f64 {
1181        self.tables.base_frequency
1182    }
1183
1184    #[must_use]
1185    pub fn base_frequency_mut(&mut self) -> &mut f64 {
1186        &mut self.tables_mut().base_frequency
1187    }
1188
1189    /// The key under which this network's source identifies an element by
1190    /// name: ASCII lowercase for an OpenDSS source, whose names are case
1191    /// insensitive, the name itself otherwise. Readiness and every name
1192    /// lookup over the tables (a line's linecode, say) compare these keys.
1193    #[must_use]
1194    pub fn identifier_key(&self, name: &str) -> String {
1195        if self.tables.source_format == Some(crate::model::DistSourceFormat::Dss) {
1196            name.to_ascii_lowercase()
1197        } else {
1198            name.to_owned()
1199        }
1200    }
1201}
1202
1203impl Default for MulticonductorNetwork {
1204    fn default() -> Self {
1205        MulticonductorNetwork::from_tables(MulticonductorNetworkTables::default())
1206    }
1207}
1208
1209impl Default for MulticonductorNetworkTables {
1210    /// An empty network at the OpenDSS default frequency. A derived 0 Hz
1211    /// default would put NaN into every capacitance the dss writer converts
1212    /// through omega.
1213    fn default() -> Self {
1214        MulticonductorNetworkTables {
1215            name: None,
1216            base_frequency: crate::dss::defaults::BASE_FREQUENCY,
1217            geo: None,
1218            component_locations: Vec::new(),
1219            buses: Vec::new(),
1220            line_codes: Vec::new(),
1221            lines: Vec::new(),
1222            switches: Vec::new(),
1223            transformers: Vec::new(),
1224            loads: Vec::new(),
1225            generators: Vec::new(),
1226            ibrs: Vec::new(),
1227            control_profiles: Vec::new(),
1228            shunts: Vec::new(),
1229            capacitors: Vec::new(),
1230            sources: Vec::new(),
1231            untyped_objects: Vec::new(),
1232            commands: Vec::new(),
1233            options: Vec::new(),
1234            defaulted: BTreeMap::new(),
1235            source_format: None,
1236            extras: Extras::new(),
1237        }
1238    }
1239}
1240
1241impl MulticonductorNetwork {
1242    #[must_use]
1243    pub fn new() -> Self {
1244        Self::default()
1245    }
1246
1247    #[must_use]
1248    pub fn named(name: impl Into<String>) -> Self {
1249        MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
1250            name: Some(name.into()),
1251            ..MulticonductorNetworkTables::default()
1252        })
1253    }
1254
1255    /// Case insensitive, matching the source formats' name semantics.
1256    pub fn bus(&self, id: &str) -> Option<&DistBus> {
1257        self.bus_index.find(self.buses(), id)
1258    }
1259
1260    /// Case insensitive, matching the source formats' name semantics.
1261    pub fn linecode(&self, name: &str) -> Option<&DistLineCode> {
1262        self.line_codes()
1263            .iter()
1264            .find(|c| c.name.eq_ignore_ascii_case(name))
1265    }
1266}
1267
1268/// Susceptance converts to a dss `cmatrix` at the network frequency, so a
1269/// 50 Hz feeder read at the 60 Hz default loses a fifth of its line charging,
1270/// and a stated 60 Hz is indistinguishable from a defaulted one downstream.
1271/// Only a network carrying susceptance can lose anything, so a document that
1272/// states no frequency and no charging stays quiet.
1273pub(crate) fn warn_defaulted_frequency(
1274    net: &MulticonductorNetwork,
1275    field: &str,
1276    diags: &mut crate::collect::Diagnostics,
1277) {
1278    let charging = net.line_codes().iter().any(|c| {
1279        [&c.b_from, &c.b_to]
1280            .iter()
1281            .flat_map(|m| m.iter())
1282            .flatten()
1283            .any(|v| v.is_finite() && v.abs() > 0.0)
1284    });
1285    if charging {
1286        diags.push(
1287            &crate::diagnostics::codes::READ_MULTICONDUCTOR_VALUE_DEFAULTED,
1288            format!(
1289                "document states no {field} and carries line susceptance; read at {} Hz",
1290                net.base_frequency()
1291            ),
1292        );
1293    }
1294}
1295
1296/// Push a warning for every dangling or empty cross-reference. Bus and
1297/// linecode references are bare strings, a reader leaves an empty string
1298/// where the field is missing, and the graph projection synthesizes a
1299/// phantom bus for any unresolved id (the empty string included) — so a
1300/// typo or an absent field would otherwise parse cleanly into a
1301/// topologically wrong network. Comparison is ASCII case insensitive,
1302/// matching [`MulticonductorNetwork::bus`] and [`MulticonductorNetwork::linecode`].
1303/// The unresolved bus and linecode references of a network, as one message
1304/// per finding: the same walk the reader's warning pass runs, exposed so a
1305/// decoder can refuse a document whose network fails it.
1306#[must_use]
1307pub fn find_unresolved_references(net: &MulticonductorNetwork) -> Vec<String> {
1308    let mut diags = crate::collect::Diagnostics::new();
1309    warn_unresolved_references(net, &mut diags);
1310    diags
1311        .into_records()
1312        .into_iter()
1313        .map(|record| record.message().to_owned())
1314        .collect()
1315}
1316
1317pub(crate) fn warn_unresolved_references(
1318    net: &MulticonductorNetwork,
1319    diags: &mut crate::collect::Diagnostics,
1320) {
1321    use std::collections::BTreeSet;
1322    let buses: BTreeSet<String> = net
1323        .buses()
1324        .iter()
1325        .map(|b| b.id.to_ascii_lowercase())
1326        .collect();
1327    let linecodes: BTreeSet<String> = net
1328        .line_codes()
1329        .iter()
1330        .map(|c| c.name.to_ascii_lowercase())
1331        .collect();
1332    let mut warnings = Vec::new();
1333    {
1334        let mut bus = |what: &str, field: &str, id: &str| {
1335            if id.is_empty() {
1336                warnings.push(format!("{what}: `{field}` reference is empty or missing"));
1337            } else if !buses.contains(&id.to_ascii_lowercase()) {
1338                warnings.push(format!("{what}: references undefined bus `{id}`"));
1339            }
1340        };
1341        for l in net.lines() {
1342            let what = format!("line {}", l.name);
1343            bus(&what, "bus_from", &l.bus_from);
1344            bus(&what, "bus_to", &l.bus_to);
1345        }
1346        for sw in net.switches() {
1347            let what = format!("switch {}", sw.name);
1348            bus(&what, "bus_from", &sw.bus_from);
1349            bus(&what, "bus_to", &sw.bus_to);
1350        }
1351        for t in net.transformers() {
1352            let what = format!("transformer {}", t.name);
1353            for w in &t.windings {
1354                bus(&what, "bus", &w.bus);
1355            }
1356        }
1357        for (what, id) in std::iter::empty()
1358            .chain(
1359                net.loads()
1360                    .iter()
1361                    .map(|x| (format!("load {}", x.name), &x.bus)),
1362            )
1363            .chain(
1364                net.generators()
1365                    .iter()
1366                    .map(|x| (format!("generator {}", x.name), &x.bus)),
1367            )
1368            .chain(
1369                net.shunts()
1370                    .iter()
1371                    .map(|x| (format!("shunt {}", x.name), &x.bus)),
1372            )
1373            .chain(
1374                net.capacitors()
1375                    .iter()
1376                    .map(|x| (format!("capacitor {}", x.name), &x.bus)),
1377            )
1378            .chain(
1379                net.ibrs()
1380                    .iter()
1381                    .map(|x| (format!("ibr {}", x.name), &x.bus)),
1382            )
1383            .chain(
1384                net.sources()
1385                    .iter()
1386                    .map(|x| (format!("voltage_source {}", x.name), &x.bus)),
1387            )
1388        {
1389            bus(&what, "bus", id);
1390        }
1391    }
1392    for l in net.lines() {
1393        if l.linecode.is_empty() {
1394            warnings.push(format!(
1395                "line {}: `linecode` reference is empty or missing",
1396                l.name
1397            ));
1398        } else if !linecodes.contains(&l.linecode.to_ascii_lowercase()) {
1399            warnings.push(format!(
1400                "line {}: references undefined linecode `{}`",
1401                l.name, l.linecode
1402            ));
1403        }
1404    }
1405    for message in warnings {
1406        diags.push(
1407            &crate::diagnostics::codes::VALIDATE_MULTICONDUCTOR_REFERENCE_UNDEFINED,
1408            message,
1409        );
1410    }
1411}
1412
1413fn zero_mat(n: usize) -> ConductorMatrix {
1414    vec![vec![0.0; n]; n]
1415}
1416
1417fn matrix_extent(m: &ConductorMatrix) -> usize {
1418    m.iter().map(Vec::len).fold(m.len(), usize::max)
1419}
1420
1421/// The two phase conductors of a line to line regulating winding: exactly
1422/// two terminals, both named 1..=3, distinct, in terminal map order.
1423pub(crate) fn winding_phase_pair(winding: &DistWinding) -> Option<(u8, u8)> {
1424    let [first, second] = winding.terminal_map.as_slice() else {
1425        return None;
1426    };
1427    let phase = |term: &String| term.parse::<u8>().ok().filter(|n| (1..=3).contains(n));
1428    match (phase(first), phase(second)) {
1429        (Some(lead), Some(lag)) if lead != lag => Some((lead, lag)),
1430        _ => None,
1431    }
1432}
1433
1434/// The GridLAB-D open delta connection two ordered line to line phase pairs
1435/// spell (the naming the BMOPFTools schema extension uses), and whether the
1436/// legs arrived in the swapped order. Any other orientation is `None`.
1437pub(crate) fn open_delta_connection(a: (u8, u8), b: (u8, u8)) -> Option<(&'static str, bool)> {
1438    match (a, b) {
1439        ((1, 2), (2, 3)) => Some(("ABBC", false)),
1440        ((2, 3), (1, 2)) => Some(("ABBC", true)),
1441        ((2, 3), (1, 3)) => Some(("BCAC", false)),
1442        ((1, 3), (2, 3)) => Some(("BCAC", true)),
1443        ((3, 1), (2, 1)) => Some(("CABA", false)),
1444        ((2, 1), (3, 1)) => Some(("CABA", true)),
1445        _ => None,
1446    }
1447}
1448
1449/// Whether two single phase regulator legs are electrically identical, so
1450/// one BMOPF `open_delta_regulator` object (which states one per regulator
1451/// impedance and rating) can carry both without collapsing anything.
1452pub(crate) fn open_delta_pairable(a: &DistTransformer, b: &DistTransformer) -> bool {
1453    let ([a0, a1], [b0, b1]) = (a.windings.as_slice(), b.windings.as_slice()) else {
1454        return false;
1455    };
1456    let eq = |x: f64, y: f64| x.to_bits() == y.to_bits();
1457    eq(a0.v_ref, b0.v_ref)
1458        && eq(a1.v_ref, b1.v_ref)
1459        && eq(a0.s_rating, b0.s_rating)
1460        && eq(a1.s_rating, b1.s_rating)
1461        && eq(a0.r_pct, b0.r_pct)
1462        && eq(a1.r_pct, b1.r_pct)
1463        && a.xsc_pct.len() == b.xsc_pct.len()
1464        && a.xsc_pct.iter().zip(&b.xsc_pct).all(|(x, y)| eq(*x, *y))
1465        && ["%noloadloss", "%imag", "g_no_load", "b_no_load"]
1466            .iter()
1467            .all(|k| a.extras.get(*k) == b.extras.get(*k))
1468}
1469
1470/// Upper triangular `(i, j)` winding index pairs for `n` windings, the order
1471/// short circuit test pairs (`x_sc`/`xsc_pct`) are keyed by.
1472pub(crate) fn pair_keys(n: usize) -> Vec<(usize, usize)> {
1473    let mut pairs = Vec::new();
1474    for i in 0..n {
1475        for j in i + 1..n {
1476            pairs.push((i, j));
1477        }
1478    }
1479    pairs
1480}
1481
1482/// OpenDSS no-load percentages for an explicit winding-2 terminal-coil shunt.
1483/// Other winding locations cannot use the OpenDSS exciting-branch parameters.
1484pub(crate) fn transformer_no_load_percentages(t: &DistTransformer) -> Option<(f64, f64)> {
1485    let shunt = t.extras.get("no_load_shunt")?;
1486    if shunt.get("winding")?.as_u64()? != 2 {
1487        return None;
1488    }
1489    let g = shunt.get("g")?.as_f64()?;
1490    let b = shunt.get("b")?.as_f64()?;
1491    let voltage = crate::transformer::calc_coil_voltage(t, 1) * t.windings.get(1)?.tap;
1492    let rating = t.windings.first()?.s_rating;
1493    if !voltage.is_finite()
1494        || voltage <= 0.0
1495        || !rating.is_finite()
1496        || rating <= 0.0
1497        || g < 0.0
1498        || b > 0.0
1499    {
1500        return None;
1501    }
1502    let scale = 100.0
1503        * t.phases.max(1) as f64
1504        * powerio_core::electrical::calc_impedance_base(voltage, rating)?;
1505    Some((g * scale, -b * scale))
1506}
1507
1508#[cfg(test)]
1509mod tests {
1510    use super::*;
1511
1512    #[test]
1513    fn terminal_roles_follow_the_conventions_or_the_spellings() {
1514        let four = ["1", "2", "3", "4"];
1515        assert_eq!(calc_terminal_role(&four, "4", None), TerminalRole::Neutral);
1516        assert_eq!(
1517            calc_terminal_role(&["1", "4"], "4", None),
1518            TerminalRole::Phase
1519        );
1520        assert_eq!(
1521            calc_terminal_role(&["a", "N"], "N", None),
1522            TerminalRole::Neutral
1523        );
1524        assert_eq!(calc_terminal_role(&["1"], "0", None), TerminalRole::Earth);
1525        let conventions = serde_json::json!({"neutral": ["x"], "earth": ["g"]});
1526        let names = ["1", "x", "g", "n"];
1527        let role = |t| calc_terminal_role(&names, t, Some(&conventions));
1528        assert_eq!(role("x"), TerminalRole::Neutral);
1529        assert_eq!(role("g"), TerminalRole::Earth);
1530        assert_eq!(role("n"), TerminalRole::Phase);
1531        let bus = DistBus::new("b", names.iter().map(|t| (*t).to_owned()).collect());
1532        assert_eq!(bus.phase_indices(Some(&conventions)), vec![0, 3]);
1533        assert_eq!(bus.neutral_indices(Some(&conventions)), vec![1]);
1534        assert_eq!(bus.neutral_indices(None), vec![3]);
1535    }
1536
1537    #[test]
1538    fn multiconductor_json_uses_only_final_nonfinite_spellings() {
1539        let mut network = MulticonductorNetwork::named("strict-ir");
1540        let mut code = DistLineCode::new("lc", vec![vec![0.1]], vec![vec![0.2]]);
1541        code.i_max = Some(vec![f64::INFINITY]);
1542        network.line_codes_mut().push(code);
1543
1544        let text = serde_json::to_string(&network).unwrap();
1545        assert!(text.contains(r#""i_max":["Infinity"]"#), "{text}");
1546
1547        let invalid = text.replace(r#""i_max":["Infinity"]"#, r#""i_max":[null]"#);
1548        let error = serde_json::from_str::<MulticonductorNetwork>(&invalid).unwrap_err();
1549        assert!(error.to_string().contains("cannot be null"), "{error}");
1550    }
1551}