Skip to main content

powerio_pkg/
lowering.rs

1//! Lowering records and preflight checks.
2//!
3//! Lowering is where PowerIO is a compiler rather than a parser: every pass that
4//! transforms one model into another (normalization, multiconductor to balanced,
5//! emission to a target format) appends a [`LoweringRecord`] to the package's
6//! `lowering_history`, so the transformation is auditable. The most consequential
7//! case, multiconductor to balanced, must be an explicit pass with diagnostics,
8//! never a silent positive sequence projection.
9
10use std::collections::{BTreeMap, BTreeSet};
11use std::f64::consts::PI;
12
13use num_complex::Complex64;
14use serde::{Deserialize, Serialize};
15
16use powerio::{
17    BalancedNetwork, Branch, BranchCharging, Bus, BusId, BusType, Extras as BalancedExtras,
18    Generator, Load, Network, Shunt, SourceFormat,
19};
20use powerio_dist::{
21    DistBus, DistLine, DistLineCode, DistLoadVoltageModel, Mat, MulticonductorNetwork,
22};
23
24use crate::diagnostics::{DiagnosticSeverity, DiagnosticStage, StructuredDiagnostic};
25use crate::model::ModelKind;
26use crate::validation::ValidationStatus;
27
28/// One lowering/normalization/emission pass and what it changed.
29#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
30#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
31pub struct LoweringRecord {
32    /// A stable pass name, e.g. `normalize-balanced` or `multiconductor-to-balanced`.
33    pub pass: String,
34    pub input_kind: ModelKind,
35    pub output_kind: ModelKind,
36    #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
37    pub options: serde_json::Map<String, serde_json::Value>,
38    /// Modeling assumptions the pass relied on (e.g. "balanced four-wire feeder").
39    #[serde(default, skip_serializing_if = "Vec::is_empty")]
40    pub assumptions: Vec<String>,
41    /// Approximations the pass introduced (e.g. "Kron reduction of neutral").
42    #[serde(default, skip_serializing_if = "Vec::is_empty")]
43    pub approximations: Vec<String>,
44    /// Fields/constraints dropped because the output family cannot carry them.
45    #[serde(default, skip_serializing_if = "Vec::is_empty")]
46    pub dropped_fields: Vec<String>,
47    #[serde(default, skip_serializing_if = "Vec::is_empty")]
48    pub diagnostics: Vec<StructuredDiagnostic>,
49    pub validation_status: ValidationStatus,
50}
51
52impl LoweringRecord {
53    pub fn new(pass: impl Into<String>, input_kind: ModelKind, output_kind: ModelKind) -> Self {
54        Self {
55            pass: pass.into(),
56            input_kind,
57            output_kind,
58            options: serde_json::Map::new(),
59            assumptions: Vec::new(),
60            approximations: Vec::new(),
61            dropped_fields: Vec::new(),
62            diagnostics: Vec::new(),
63            validation_status: ValidationStatus::Ok,
64        }
65    }
66}
67
68/// Sequence transform used by the multiconductor to balanced lowering.
69#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
70#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
71#[serde(rename_all = "snake_case")]
72pub enum SequenceTransformConvention {
73    FortescuePowerInvariant,
74}
75
76impl std::fmt::Display for SequenceTransformConvention {
77    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78        match self {
79            Self::FortescuePowerInvariant => f.write_str("FortescuePowerInvariant"),
80        }
81    }
82}
83
84const DEFAULT_LOWERING_BASE_MVA: f64 = 100.0;
85const SQRT_3: f64 = 1.732_050_807_568_877_2;
86const COUPLING_TOLERANCE: f64 = 1.0e-9;
87
88fn default_lowering_base_mva() -> f64 {
89    DEFAULT_LOWERING_BASE_MVA
90}
91
92/// Options for the multiconductor to balanced lowering preflight and pass.
93#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
94#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
95pub struct MulticonductorToBalancedOptions {
96    pub convention: SequenceTransformConvention,
97    /// Three phase system power base used for the balanced per-unit projection.
98    #[serde(default = "default_lowering_base_mva")]
99    pub base_mva: f64,
100}
101
102impl Default for MulticonductorToBalancedOptions {
103    fn default() -> Self {
104        Self {
105            convention: SequenceTransformConvention::FortescuePowerInvariant,
106            base_mva: DEFAULT_LOWERING_BASE_MVA,
107        }
108    }
109}
110
111/// Readiness report for the multiconductor to balanced lowering pass.
112#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
113#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
114pub struct MulticonductorToBalancedReadiness {
115    pub convention: SequenceTransformConvention,
116    pub base_mva: f64,
117    pub status: ValidationStatus,
118    #[serde(default, skip_serializing_if = "Vec::is_empty")]
119    pub assumptions: Vec<String>,
120    #[serde(default, skip_serializing_if = "Vec::is_empty")]
121    pub approximations: Vec<String>,
122    #[serde(default, skip_serializing_if = "Vec::is_empty")]
123    pub diagnostics: Vec<StructuredDiagnostic>,
124}
125
126impl MulticonductorToBalancedReadiness {
127    #[must_use]
128    pub fn is_ready(&self) -> bool {
129        self.status <= ValidationStatus::Info
130    }
131}
132
133/// A successful raw multiconductor to balanced lowering result.
134#[derive(Clone, Debug, Serialize, Deserialize)]
135#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
136pub struct MulticonductorToBalancedLowering {
137    pub network: BalancedNetwork,
138    pub record: LoweringRecord,
139}
140
141/// Structured failure from the raw multiconductor to balanced lowering pass.
142#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
143#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
144pub struct MulticonductorToBalancedError {
145    pub options: MulticonductorToBalancedOptions,
146    pub status: ValidationStatus,
147    #[serde(default, skip_serializing_if = "Vec::is_empty")]
148    pub diagnostics: Vec<StructuredDiagnostic>,
149}
150
151impl MulticonductorToBalancedError {
152    pub fn new(
153        options: MulticonductorToBalancedOptions,
154        diagnostics: Vec<StructuredDiagnostic>,
155    ) -> Self {
156        Self {
157            options,
158            status: status_from_diagnostics(&diagnostics),
159            diagnostics,
160        }
161    }
162}
163
164impl std::fmt::Display for MulticonductorToBalancedError {
165    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
166        match self.diagnostics.first() {
167            Some(diagnostic) => write!(f, "{}", diagnostic.message),
168            None => f.write_str("multiconductor to balanced lowering failed"),
169        }
170    }
171}
172
173impl std::error::Error for MulticonductorToBalancedError {}
174
175/// Check whether a multiconductor package is ready for the lowering pass.
176///
177/// This is a preflight only: it reports the assumptions and blockers that the
178/// lowering would need to account for, but it does not produce a balanced model
179/// and does not append to `lowering_history`.
180#[must_use]
181pub fn check_multiconductor_to_balanced_lowering(
182    net: &MulticonductorNetwork,
183    options: MulticonductorToBalancedOptions,
184) -> MulticonductorToBalancedReadiness {
185    let mut report = MulticonductorToBalancedReadiness {
186        convention: options.convention,
187        base_mva: options.base_mva,
188        status: ValidationStatus::Ok,
189        assumptions: vec![format!(
190            "sequence transform convention: {}",
191            options.convention
192        )],
193        approximations: Vec::new(),
194        diagnostics: Vec::new(),
195    };
196
197    check_options(options, &mut report);
198    check_bus_conductor_sets(net, &mut report);
199    check_phase_reference(net, &mut report);
200    check_line_terminal_maps(net, &mut report);
201    check_linecodes(net, &mut report);
202    check_switches(net, &mut report);
203    check_transformers(net, &mut report);
204    check_untyped_objects(net, &mut report);
205
206    report.status = status_from_diagnostics(&report.diagnostics);
207    report
208}
209
210/// Lower a transparent three phase multiconductor network to a balanced model.
211///
212/// The pass is explicit. It does not run from readers, writers, matrix builders,
213/// bindings, or package deserialization. Unsupported inputs return structured
214/// `LOWER.MULTI_TO_BALANCED.*` diagnostics in [`MulticonductorToBalancedError`].
215pub fn lower_multiconductor_to_balanced(
216    net: &MulticonductorNetwork,
217    options: MulticonductorToBalancedOptions,
218) -> Result<MulticonductorToBalancedLowering, MulticonductorToBalancedError> {
219    let readiness = check_multiconductor_to_balanced_lowering(net, options);
220    if !readiness.is_ready() {
221        return Err(MulticonductorToBalancedError::new(
222            options,
223            readiness.diagnostics,
224        ));
225    }
226
227    let mut state = LoweringState::new(net, options, readiness);
228    state.lower()
229}
230
231struct LoweringState<'a> {
232    net: &'a MulticonductorNetwork,
233    options: MulticonductorToBalancedOptions,
234    neutral_terminals: BTreeSet<String>,
235    bus_ids: BTreeMap<String, BusId>,
236    record: LoweringRecord,
237}
238
239impl<'a> LoweringState<'a> {
240    fn new(
241        net: &'a MulticonductorNetwork,
242        options: MulticonductorToBalancedOptions,
243        readiness: MulticonductorToBalancedReadiness,
244    ) -> Self {
245        let mut record = LoweringRecord::new(
246            "multiconductor-to-balanced",
247            ModelKind::Multiconductor,
248            ModelKind::Balanced,
249        );
250        record.options = options_map(options);
251        record.assumptions = readiness.assumptions;
252        record.approximations = readiness.approximations;
253        record.diagnostics = readiness.diagnostics;
254        record
255            .assumptions
256            .push(format!("balanced power base: {} MVA", options.base_mva));
257        record
258            .assumptions
259            .push("balanced bus ids are synthesized from multiconductor bus order".to_owned());
260        record.approximations.push(
261            "wire-coordinate branch and shunt matrices are projected to positive sequence"
262                .to_owned(),
263        );
264        record.approximations.push(
265            "phase injection records are aggregated into scalar balanced injections".to_owned(),
266        );
267        record.approximations.push(
268            "units are converted from W/var/V/ohm/siemens/radians to MW/MVAr/per-unit/degrees"
269                .to_owned(),
270        );
271        if net.switches.iter().any(|sw| sw.open) {
272            record
273                .dropped_fields
274                .push("open switches dropped from balanced model".to_owned());
275        }
276
277        let bus_ids = net
278            .buses
279            .iter()
280            .enumerate()
281            .map(|(idx, bus)| (bus.id.to_ascii_lowercase(), BusId(idx + 1)))
282            .collect();
283
284        Self {
285            net,
286            options,
287            neutral_terminals: global_neutral_terminals(net),
288            bus_ids,
289            record,
290        }
291    }
292
293    #[allow(clippy::too_many_lines)]
294    fn lower(&mut self) -> Result<MulticonductorToBalancedLowering, MulticonductorToBalancedError> {
295        let Some(base) = self.voltage_base()? else {
296            return Err(MulticonductorToBalancedError::new(
297                self.options,
298                self.record.diagnostics.clone(),
299            ));
300        };
301
302        let buses = self.lower_buses(base);
303        let branches = self.lower_lines(base)?;
304        let loads = self.lower_loads();
305        let shunts = self.lower_shunts(base)?;
306        let generators = self.lower_generators(&buses);
307        self.record_capacitor_drops();
308        self.err_if_errors()?;
309
310        let mut network = Network::new(
311            self.net
312                .name
313                .clone()
314                .unwrap_or_else(|| "lowered-multiconductor".to_owned()),
315            self.options.base_mva,
316        );
317        network.base_frequency = self.net.base_frequency;
318        network.buses = buses;
319        network.loads = loads;
320        network.shunts = shunts;
321        network.branches = branches;
322        network.generators = generators;
323        network.source_format = SourceFormat::InMemory;
324
325        if let Err(err) = network.validate() {
326            self.record.diagnostics.push(StructuredDiagnostic::new(
327                "LOWER.MULTI_TO_BALANCED.INVALID_BALANCED_OUTPUT",
328                DiagnosticSeverity::Error,
329                DiagnosticStage::Lower,
330                format!("lowered balanced network failed structural validation: {err}"),
331            ));
332            return Err(MulticonductorToBalancedError::new(
333                self.options,
334                self.record.diagnostics.clone(),
335            ));
336        }
337        for finding in network.validate_values() {
338            self.record.diagnostics.push(
339                StructuredDiagnostic::new(
340                    "LOWER.MULTI_TO_BALANCED.BALANCED_VALUE_DOMAIN",
341                    DiagnosticSeverity::Warning,
342                    DiagnosticStage::Lower,
343                    format!(
344                        "{} field `{}` is outside its value domain after lowering",
345                        finding.element, finding.field
346                    ),
347                )
348                .with_suggested_action(
349                    "Inspect the multiconductor source values before using the lowered model.",
350                ),
351            );
352        }
353
354        self.record.validation_status = status_from_diagnostics(&self.record.diagnostics);
355        Ok(MulticonductorToBalancedLowering {
356            network,
357            record: self.record.clone(),
358        })
359    }
360
361    fn voltage_base(&mut self) -> Result<Option<VoltageBase>, MulticonductorToBalancedError> {
362        for (idx, source) in self.net.sources.iter().enumerate() {
363            let Some(bus) = self.net.bus(&source.bus) else {
364                self.record.diagnostics.push(
365                    StructuredDiagnostic::new(
366                        "LOWER.MULTI_TO_BALANCED.UNKNOWN_SOURCE_BUS",
367                        DiagnosticSeverity::Error,
368                        DiagnosticStage::Lower,
369                        format!(
370                            "voltage source {} references unknown bus {}",
371                            source.name, source.bus
372                        ),
373                    )
374                    .with_element_path(format!("/model/multiconductor_network/sources/{idx}/bus")),
375                );
376                continue;
377            };
378            let positions =
379                active_positions(&source.terminal_map, Some(bus), &self.neutral_terminals);
380            if positions.len() != 3 {
381                continue;
382            }
383            let Some(v1) = positive_sequence_voltage(source, &positions) else {
384                self.record.diagnostics.push(
385                    StructuredDiagnostic::new(
386                        "LOWER.MULTI_TO_BALANCED.INVALID_PHASE_REFERENCE",
387                        DiagnosticSeverity::Error,
388                        DiagnosticStage::Lower,
389                        format!(
390                            "voltage source {} does not carry finite three phase voltage magnitudes and angles",
391                            source.name
392                        ),
393                    )
394                    .with_element_path(format!("/model/multiconductor_network/sources/{idx}")),
395                );
396                continue;
397            };
398            let line_to_line_volts = v1.norm();
399            if !line_to_line_volts.is_finite() || line_to_line_volts <= 0.0 {
400                self.record.diagnostics.push(
401                    StructuredDiagnostic::new(
402                        "LOWER.MULTI_TO_BALANCED.INVALID_PHASE_REFERENCE",
403                        DiagnosticSeverity::Error,
404                        DiagnosticStage::Lower,
405                        format!(
406                            "voltage source {} produced a non-positive positive-sequence voltage base",
407                            source.name
408                        ),
409                    )
410                    .with_element_path(format!("/model/multiconductor_network/sources/{idx}")),
411                );
412                continue;
413            }
414            self.record.assumptions.push(format!(
415                "voltage base synthesized from source {} positive-sequence voltage: {} kV line-to-line",
416                source.name,
417                line_to_line_volts / 1000.0
418            ));
419            return Ok(Some(VoltageBase { line_to_line_volts }));
420        }
421
422        if self
423            .record
424            .diagnostics
425            .iter()
426            .any(|d| d.severity >= DiagnosticSeverity::Error)
427        {
428            return Err(MulticonductorToBalancedError::new(
429                self.options,
430                self.record.diagnostics.clone(),
431            ));
432        }
433        self.record.diagnostics.push(StructuredDiagnostic::new(
434            "LOWER.MULTI_TO_BALANCED.MISSING_PHASE_REFERENCE",
435            DiagnosticSeverity::Error,
436            DiagnosticStage::Lower,
437            "multiconductor to balanced lowering requires a finite three phase voltage source reference",
438        ));
439        Ok(None)
440    }
441
442    fn lower_buses(&mut self, base: VoltageBase) -> Vec<Bus> {
443        self.net
444            .buses
445            .iter()
446            .enumerate()
447            .map(|(idx, bus)| {
448                let source = self
449                    .net
450                    .sources
451                    .iter()
452                    .find(|source| source.bus.eq_ignore_ascii_case(&bus.id));
453                let (vm, va) = source
454                    .and_then(|source| {
455                        let positions = active_positions(
456                            &source.terminal_map,
457                            Some(bus),
458                            &self.neutral_terminals,
459                        );
460                        positive_sequence_voltage(source, &positions)
461                    })
462                    .map_or((1.0, 0.0), |v| {
463                        (
464                            v.norm() / base.line_to_line_volts,
465                            radians_to_degrees(v.arg()),
466                        )
467                    });
468                if source.is_none() {
469                    self.record.dropped_fields.push(format!(
470                        "bus {} voltage magnitude and angle defaulted to 1.0 p.u. and 0 degrees",
471                        bus.id
472                    ));
473                }
474                let (vmin, vmax) = match (bus.v_min, bus.v_max) {
475                    (Some(vmin), Some(vmax)) if vmin.is_finite() && vmax.is_finite() => (
476                        vmin / base.line_to_line_volts,
477                        vmax / base.line_to_line_volts,
478                    ),
479                    _ => {
480                        self.record.dropped_fields.push(format!(
481                            "bus {} voltage bounds defaulted to 0.9/1.1 p.u.",
482                            bus.id
483                        ));
484                        (0.9, 1.1)
485                    }
486                };
487                self.record_bus_bound_drops(bus);
488                let mut balanced = Bus::new(
489                    BusId(idx + 1),
490                    self.bus_kind(&bus.id),
491                    base.line_to_line_volts / 1000.0,
492                );
493                balanced.vm = vm;
494                balanced.va = va;
495                balanced.vmax = vmax;
496                balanced.vmin = vmin;
497                balanced.name = Some(bus.id.clone());
498                balanced.extras = source_extra("multiconductor_bus_id", &bus.id);
499                balanced
500            })
501            .collect()
502    }
503
504    /// A rated capacitor bank (BMOPF schema 0.1.0 `capacitor`) has no
505    /// balanced equivalent yet: `q_rated` at `v_nom` is a nameplate rating,
506    /// not the admittance a balanced `Shunt` carries. The bank therefore
507    /// drops, and the record names it, because a silent drop removes
508    /// reactive support the case depends on.
509    fn record_capacitor_drops(&mut self) {
510        for capacitor in &self.net.capacitors {
511            self.record.dropped_fields.push(format!(
512                "capacitor {} dropped: a rated bank has no balanced shunt equivalent",
513                capacitor.name
514            ));
515        }
516    }
517
518    fn record_bus_bound_drops(&mut self, bus: &DistBus) {
519        if bus.vpn_min.is_some()
520            || bus.vpn_max.is_some()
521            || bus.vpp_min.is_some()
522            || bus.vpp_max.is_some()
523            || bus.vpos_min.is_some()
524            || bus.vpos_max.is_some()
525            || bus.vneg_max.is_some()
526            || bus.vzero_max.is_some()
527            || bus.vn_max.is_some()
528        {
529            self.record.dropped_fields.push(format!(
530                "bus {} conductor voltage bound families dropped",
531                bus.id
532            ));
533        }
534    }
535
536    fn bus_kind(&self, bus_id: &str) -> BusType {
537        if self
538            .net
539            .sources
540            .iter()
541            .any(|source| source.bus.eq_ignore_ascii_case(bus_id))
542        {
543            BusType::Ref
544        } else if self
545            .net
546            .generators
547            .iter()
548            .any(|generator| generator.bus.eq_ignore_ascii_case(bus_id))
549        {
550            BusType::Pv
551        } else {
552            BusType::Pq
553        }
554    }
555
556    #[allow(clippy::too_many_lines)]
557    fn lower_lines(
558        &mut self,
559        base: VoltageBase,
560    ) -> Result<Vec<Branch>, MulticonductorToBalancedError> {
561        let mut branches = Vec::with_capacity(self.net.lines.len());
562        for (idx, line) in self.net.lines.iter().enumerate() {
563            let Some(code) = self.net.linecode(&line.linecode) else {
564                self.record.diagnostics.push(
565                    StructuredDiagnostic::new(
566                        "LOWER.MULTI_TO_BALANCED.UNKNOWN_LINECODE",
567                        DiagnosticSeverity::Error,
568                        DiagnosticStage::Lower,
569                        format!(
570                            "line {} references unknown linecode `{}`",
571                            line.name, line.linecode
572                        ),
573                    )
574                    .with_element_path(format!(
575                        "/model/multiconductor_network/lines/{idx}/linecode"
576                    )),
577                );
578                continue;
579            };
580            if !same_active_phase_order(
581                self.net.bus(&line.bus_from),
582                &line.terminal_map_from,
583                self.net.bus(&line.bus_to),
584                &line.terminal_map_to,
585                &self.neutral_terminals,
586            ) {
587                self.record.diagnostics.push(
588                    StructuredDiagnostic::new(
589                        "LOWER.MULTI_TO_BALANCED.PHASE_MAP_MISMATCH",
590                        DiagnosticSeverity::Error,
591                        DiagnosticStage::Lower,
592                        format!(
593                            "line {} connects different active terminal orders and cannot be lowered transparently",
594                            line.name
595                        ),
596                    )
597                    .with_element_path(format!("/model/multiconductor_network/lines/{idx}")),
598                );
599                continue;
600            }
601            let Some(from) = self.bus_id(&line.bus_from) else {
602                self.unknown_bus_diag("line", &line.name, &line.bus_from, idx, "bus_from");
603                continue;
604            };
605            let Some(to) = self.bus_id(&line.bus_to) else {
606                self.unknown_bus_diag("line", &line.name, &line.bus_to, idx, "bus_to");
607                continue;
608            };
609            let from_bus = self.net.bus(&line.bus_from);
610            let active =
611                active_positions(&line.terminal_map_from, from_bus, &self.neutral_terminals);
612            let neutral =
613                neutral_positions(&line.terminal_map_from, from_bus, &self.neutral_terminals);
614            let z_ohm =
615                self.line_positive_sequence_impedance(idx, code, &active, &neutral, line.length)?;
616            let y_from = self.line_positive_sequence_admittance(
617                idx,
618                code,
619                &active,
620                &neutral,
621                line.length,
622                ShuntSide::From,
623            )?;
624            let y_to = self.line_positive_sequence_admittance(
625                idx,
626                code,
627                &active,
628                &neutral,
629                line.length,
630                ShuntSide::To,
631            )?;
632            let z_base = base.z_base_ohm(self.options.base_mva);
633            let y_scale = z_base;
634            let charging = BranchCharging::new(
635                y_from.re * y_scale,
636                y_from.im * y_scale,
637                y_to.re * y_scale,
638                y_to.im * y_scale,
639            );
640            let rate =
641                line_rate_mva(line, code, &active, base.line_to_line_volts).unwrap_or_else(|| {
642                    self.record.dropped_fields.push(format!(
643                        "line {} thermal rating defaulted to 0 MVA",
644                        line.name
645                    ));
646                    0.0
647                });
648            let mut branch = Branch::new(from, to, z_ohm.re / z_base, z_ohm.im / z_base);
649            branch.b = charging.total_b();
650            branch.charging = Some(charging);
651            branch.rate_a = rate;
652            branch.rate_b = rate;
653            branch.rate_c = rate;
654            branch.extras = source_extra("multiconductor_line", &line.name);
655            branches.push(branch);
656        }
657        self.err_if_errors()?;
658        Ok(branches)
659    }
660
661    fn line_positive_sequence_impedance(
662        &mut self,
663        line_idx: usize,
664        code: &DistLineCode,
665        active: &[usize],
666        neutral: &[usize],
667        length: f64,
668    ) -> Result<Complex64, MulticonductorToBalancedError> {
669        let matrix = complex_matrix(&code.r_series, &code.x_series, length);
670        let reduced = kron_or_select(&matrix, active, neutral).map_err(|message| {
671            self.matrix_error(line_idx, &code.name, "series impedance", &message)
672        })?;
673        Ok(self.positive_sequence_from_matrix(line_idx, &code.name, "series impedance", &reduced))
674    }
675
676    fn line_positive_sequence_admittance(
677        &mut self,
678        line_idx: usize,
679        code: &DistLineCode,
680        active: &[usize],
681        neutral: &[usize],
682        length: f64,
683        side: ShuntSide,
684    ) -> Result<Complex64, MulticonductorToBalancedError> {
685        let (g, b, label) = match side {
686            ShuntSide::From => (&code.g_from, &code.b_from, "from shunt admittance"),
687            ShuntSide::To => (&code.g_to, &code.b_to, "to shunt admittance"),
688        };
689        let matrix = complex_matrix(g, b, length);
690        let reduced = kron_or_select(&matrix, active, neutral)
691            .map_err(|message| self.matrix_error(line_idx, &code.name, label, &message))?;
692        Ok(self.positive_sequence_from_matrix(line_idx, &code.name, label, &reduced))
693    }
694
695    fn positive_sequence_from_matrix(
696        &mut self,
697        line_idx: usize,
698        code_name: &str,
699        label: &str,
700        matrix: &[Vec<Complex64>],
701    ) -> Complex64 {
702        let seq = sequence_matrix(matrix);
703        let coupling = sequence_coupling_norm(&seq);
704        if coupling > COUPLING_TOLERANCE {
705            self.record.approximations.push(format!(
706                "linecode {code_name} {label} has sequence coupling norm {coupling}; positive-sequence diagonal retained"
707            ));
708            let mut diagnostic = StructuredDiagnostic::new(
709                "LOWER.MULTI_TO_BALANCED.SEQUENCE_COUPLING_DROPPED",
710                DiagnosticSeverity::Info,
711                DiagnosticStage::Lower,
712                format!(
713                    "linecode {code_name} {label} has nonzero sequence coupling; the balanced model keeps the positive-sequence diagonal"
714                ),
715            )
716            .with_element_path(format!("/model/multiconductor_network/lines/{line_idx}/linecode"));
717            diagnostic.details.insert(
718                "sequence_coupling_norm".to_owned(),
719                serde_json::json!(coupling),
720            );
721            self.record.diagnostics.push(diagnostic);
722        }
723        seq[1][1]
724    }
725
726    fn matrix_error(
727        &self,
728        line_idx: usize,
729        code_name: &str,
730        label: &str,
731        message: &str,
732    ) -> MulticonductorToBalancedError {
733        let mut diagnostics = self.record.diagnostics.clone();
734        diagnostics.push(
735            StructuredDiagnostic::new(
736                "LOWER.MULTI_TO_BALANCED.INVALID_LINECODE_MATRIX",
737                DiagnosticSeverity::Error,
738                DiagnosticStage::Lower,
739                format!("linecode {code_name} {label} cannot be lowered: {message}"),
740            )
741            .with_element_path(format!(
742                "/model/multiconductor_network/lines/{line_idx}/linecode"
743            )),
744        );
745        MulticonductorToBalancedError::new(self.options, diagnostics)
746    }
747
748    fn lower_loads(&mut self) -> Vec<Load> {
749        self.net
750            .loads
751            .iter()
752            .enumerate()
753            .filter_map(|(idx, load)| {
754                let Some(bus) = self.bus_id(&load.bus) else {
755                    self.unknown_bus_diag("load", &load.name, &load.bus, idx, "bus");
756                    return None;
757                };
758                if !matches!(
759                    load.voltage_model,
760                    DistLoadVoltageModel::ConstantPower { .. }
761                ) {
762                    self.record.dropped_fields.push(format!(
763                        "load {} voltage model dropped; balanced load is constant power",
764                        load.name
765                    ));
766                    self.record.diagnostics.push(
767                        StructuredDiagnostic::new(
768                            "LOWER.MULTI_TO_BALANCED.DROPPED_LOAD_VOLTAGE_MODEL",
769                            DiagnosticSeverity::Warning,
770                            DiagnosticStage::Lower,
771                            format!(
772                                "load {} voltage model cannot be represented by the conservative balanced lowering",
773                                load.name
774                            ),
775                        )
776                        .with_element_path(format!("/model/multiconductor_network/loads/{idx}/voltage_model")),
777                    );
778                }
779                let mut balanced = Load::new(
780                    bus,
781                    si_power_to_mega(load.p_nom.iter().sum()),
782                    si_power_to_mega(load.q_nom.iter().sum()),
783                );
784                balanced.extras = source_extra("multiconductor_load", &load.name);
785                Some(balanced)
786            })
787            .collect()
788    }
789
790    fn lower_shunts(
791        &mut self,
792        base: VoltageBase,
793    ) -> Result<Vec<Shunt>, MulticonductorToBalancedError> {
794        let mut shunts = Vec::with_capacity(self.net.shunts.len());
795        for (idx, shunt) in self.net.shunts.iter().enumerate() {
796            let Some(bus) = self.bus_id(&shunt.bus) else {
797                self.unknown_bus_diag("shunt", &shunt.name, &shunt.bus, idx, "bus");
798                continue;
799            };
800            let dist_bus = self.net.bus(&shunt.bus);
801            let active = active_positions(&shunt.terminal_map, dist_bus, &self.neutral_terminals);
802            let neutral = neutral_positions(&shunt.terminal_map, dist_bus, &self.neutral_terminals);
803            let y = if active.len() == 3 {
804                let matrix = complex_matrix(&shunt.g, &shunt.b, 1.0);
805                let reduced = kron_or_select(&matrix, &active, &neutral)
806                    .map_err(|message| self.shunt_matrix_error(idx, &shunt.name, &message))?;
807                let seq = sequence_matrix(&reduced);
808                seq[1][1]
809            } else {
810                self.record.approximations.push(format!(
811                    "shunt {} has {} active terminal(s); diagonal admittance projected with missing phases as zero",
812                    shunt.name,
813                    active.len()
814                ));
815                partial_phase_admittance(&shunt.g, &shunt.b, &active)
816            };
817            let scale = base.line_to_line_volts * base.line_to_line_volts / 1_000_000.0;
818            let mut balanced = Shunt::new(bus, y.re * scale, y.im * scale);
819            balanced.extras = source_extra("multiconductor_shunt", &shunt.name);
820            shunts.push(balanced);
821        }
822        self.err_if_errors()?;
823        Ok(shunts)
824    }
825
826    fn shunt_matrix_error(
827        &self,
828        shunt_idx: usize,
829        name: &str,
830        message: &str,
831    ) -> MulticonductorToBalancedError {
832        let mut diagnostics = self.record.diagnostics.clone();
833        diagnostics.push(
834            StructuredDiagnostic::new(
835                "LOWER.MULTI_TO_BALANCED.INVALID_SHUNT_MATRIX",
836                DiagnosticSeverity::Error,
837                DiagnosticStage::Lower,
838                format!("shunt {name} cannot be lowered: {message}"),
839            )
840            .with_element_path(format!("/model/multiconductor_network/shunts/{shunt_idx}")),
841        );
842        MulticonductorToBalancedError::new(self.options, diagnostics)
843    }
844
845    fn lower_generators(&mut self, buses: &[Bus]) -> Vec<Generator> {
846        self.net
847            .generators
848            .iter()
849            .enumerate()
850            .filter_map(|(idx, generator)| {
851                let Some(bus) = self.bus_id(&generator.bus) else {
852                    self.unknown_bus_diag("generator", &generator.name, &generator.bus, idx, "bus");
853                    return None;
854                };
855                let pg = si_power_to_mega(generator.p_nom.iter().sum());
856                let qg = si_power_to_mega(generator.q_nom.iter().sum());
857                let pmin = option_vec_sum_mw(generator.p_min.as_deref()).unwrap_or_else(|| {
858                    self.record.dropped_fields.push(format!(
859                        "generator {} p_min defaulted to pg",
860                        generator.name
861                    ));
862                    pg
863                });
864                let pmax = option_vec_sum_mw(generator.p_max.as_deref()).unwrap_or_else(|| {
865                    self.record.dropped_fields.push(format!(
866                        "generator {} p_max defaulted to pg",
867                        generator.name
868                    ));
869                    pg
870                });
871                let qmin = option_vec_sum_mw(generator.q_min.as_deref()).unwrap_or_else(|| {
872                    self.record.dropped_fields.push(format!(
873                        "generator {} q_min defaulted to qg",
874                        generator.name
875                    ));
876                    qg
877                });
878                let qmax = option_vec_sum_mw(generator.q_max.as_deref()).unwrap_or_else(|| {
879                    self.record.dropped_fields.push(format!(
880                        "generator {} q_max defaulted to qg",
881                        generator.name
882                    ));
883                    qg
884                });
885                if generator.cost.is_some() {
886                    self.record.dropped_fields.push(format!(
887                        "generator {} scalar distribution cost dropped",
888                        generator.name
889                    ));
890                }
891                if generator.s_max.is_some() || generator.i_max.is_some() {
892                    self.record.dropped_fields.push(format!(
893                        "generator {} per-conductor rating fields dropped",
894                        generator.name
895                    ));
896                }
897                let vg = buses
898                    .iter()
899                    .find(|balanced_bus| balanced_bus.id == bus)
900                    .map_or(1.0, |balanced_bus| balanced_bus.vm);
901                let mut balanced = Generator::new(bus);
902                balanced.pg = pg;
903                balanced.qg = qg;
904                balanced.pmax = pmax;
905                balanced.pmin = pmin;
906                balanced.qmax = qmax;
907                balanced.qmin = qmin;
908                balanced.vg = vg;
909                balanced.mbase = self.options.base_mva;
910                Some(balanced)
911            })
912            .collect()
913    }
914
915    fn bus_id(&self, bus: &str) -> Option<BusId> {
916        self.bus_ids.get(&bus.to_ascii_lowercase()).copied()
917    }
918
919    fn unknown_bus_diag(&mut self, element: &str, name: &str, bus: &str, idx: usize, field: &str) {
920        self.record.diagnostics.push(
921            StructuredDiagnostic::new(
922                "LOWER.MULTI_TO_BALANCED.UNKNOWN_BUS",
923                DiagnosticSeverity::Error,
924                DiagnosticStage::Lower,
925                format!("{element} {name} references unknown bus {bus}"),
926            )
927            .with_element_path(format!(
928                "/model/multiconductor_network/{element}s/{idx}/{field}"
929            )),
930        );
931    }
932
933    fn err_if_errors(&self) -> Result<(), MulticonductorToBalancedError> {
934        if self
935            .record
936            .diagnostics
937            .iter()
938            .any(|d| d.severity >= DiagnosticSeverity::Error)
939        {
940            Err(MulticonductorToBalancedError::new(
941                self.options,
942                self.record.diagnostics.clone(),
943            ))
944        } else {
945            Ok(())
946        }
947    }
948}
949
950#[derive(Clone, Copy)]
951struct VoltageBase {
952    line_to_line_volts: f64,
953}
954
955impl VoltageBase {
956    fn z_base_ohm(self, base_mva: f64) -> f64 {
957        self.line_to_line_volts * self.line_to_line_volts / (base_mva * 1_000_000.0)
958    }
959}
960
961#[derive(Clone, Copy)]
962enum ShuntSide {
963    From,
964    To,
965}
966
967fn options_map(
968    options: MulticonductorToBalancedOptions,
969) -> serde_json::Map<String, serde_json::Value> {
970    serde_json::to_value(options)
971        .ok()
972        .and_then(|value| value.as_object().cloned())
973        .unwrap_or_default()
974}
975
976fn source_extra(key: &str, value: &str) -> BalancedExtras {
977    let mut extras = BalancedExtras::new();
978    extras.insert(key.to_owned(), serde_json::Value::String(value.to_owned()));
979    extras
980}
981
982fn active_positions(
983    terminals: &[String],
984    bus: Option<&DistBus>,
985    neutral_terminals: &BTreeSet<String>,
986) -> Vec<usize> {
987    terminals
988        .iter()
989        .enumerate()
990        .filter_map(|(idx, terminal)| {
991            (!is_neutral_terminal(terminal, bus, neutral_terminals)).then_some(idx)
992        })
993        .collect()
994}
995
996fn neutral_positions(
997    terminals: &[String],
998    bus: Option<&DistBus>,
999    neutral_terminals: &BTreeSet<String>,
1000) -> Vec<usize> {
1001    terminals
1002        .iter()
1003        .enumerate()
1004        .filter_map(|(idx, terminal)| {
1005            is_neutral_terminal(terminal, bus, neutral_terminals).then_some(idx)
1006        })
1007        .collect()
1008}
1009
1010fn same_active_phase_order(
1011    from_bus: Option<&DistBus>,
1012    from_terminals: &[String],
1013    to_bus: Option<&DistBus>,
1014    to_terminals: &[String],
1015    neutral_terminals: &BTreeSet<String>,
1016) -> bool {
1017    let from: Vec<_> = from_terminals
1018        .iter()
1019        .filter(|terminal| !is_neutral_terminal(terminal, from_bus, neutral_terminals))
1020        .map(|terminal| terminal.to_ascii_lowercase())
1021        .collect();
1022    let to: Vec<_> = to_terminals
1023        .iter()
1024        .filter(|terminal| !is_neutral_terminal(terminal, to_bus, neutral_terminals))
1025        .map(|terminal| terminal.to_ascii_lowercase())
1026        .collect();
1027    from == to
1028}
1029
1030fn positive_sequence_voltage(
1031    source: &powerio_dist::VoltageSource,
1032    positions: &[usize],
1033) -> Option<Complex64> {
1034    if positions.len() != 3 {
1035        return None;
1036    }
1037    let mut phase = [Complex64::new(0.0, 0.0); 3];
1038    for (out, &idx) in phase.iter_mut().zip(positions.iter()) {
1039        let magnitude = *source.v_magnitude.get(idx)?;
1040        let angle = *source.v_angle.get(idx)?;
1041        if !magnitude.is_finite() || !angle.is_finite() {
1042            return None;
1043        }
1044        *out = Complex64::from_polar(magnitude, angle);
1045    }
1046    let basis = sequence_basis();
1047    let mut seq = [Complex64::new(0.0, 0.0); 3];
1048    for (sequence_idx, out) in seq.iter_mut().enumerate() {
1049        for phase_idx in 0..3 {
1050            *out += basis[phase_idx][sequence_idx].conj() * phase[phase_idx];
1051        }
1052    }
1053    Some(seq[1])
1054}
1055
1056fn complex_matrix(g_or_r: &Mat, b_or_x: &Mat, scale: f64) -> Vec<Vec<Complex64>> {
1057    g_or_r
1058        .iter()
1059        .zip(b_or_x.iter())
1060        .map(|(g_row, b_row)| {
1061            g_row
1062                .iter()
1063                .zip(b_row.iter())
1064                .map(|(&g, &b)| Complex64::new(g * scale, b * scale))
1065                .collect()
1066        })
1067        .collect()
1068}
1069
1070fn kron_or_select(
1071    matrix: &[Vec<Complex64>],
1072    active: &[usize],
1073    neutral: &[usize],
1074) -> Result<Vec<Vec<Complex64>>, String> {
1075    if active.len() != 3 {
1076        return Err(format!(
1077            "expected three active conductors, got {}",
1078            active.len()
1079        ));
1080    }
1081    validate_indices(matrix, active)?;
1082    validate_indices(matrix, neutral)?;
1083    if neutral.is_empty() {
1084        return Ok(submatrix(matrix, active, active));
1085    }
1086
1087    let m_pp = submatrix(matrix, active, active);
1088    let m_pn = submatrix(matrix, active, neutral);
1089    let m_np = submatrix(matrix, neutral, active);
1090    let m_nn = submatrix(matrix, neutral, neutral);
1091    if matrix_is_near_zero(&m_pn) && matrix_is_near_zero(&m_np) && matrix_is_near_zero(&m_nn) {
1092        return Ok(m_pp);
1093    }
1094    let inv_nn = invert_complex_matrix(&m_nn)?;
1095    let correction = matmul(&matmul(&m_pn, &inv_nn), &m_np);
1096    Ok(matrix_sub(&m_pp, &correction))
1097}
1098
1099fn matrix_is_near_zero(matrix: &[Vec<Complex64>]) -> bool {
1100    matrix
1101        .iter()
1102        .flatten()
1103        .all(|value| value.norm() <= f64::EPSILON)
1104}
1105
1106fn validate_indices(matrix: &[Vec<Complex64>], indices: &[usize]) -> Result<(), String> {
1107    let n = matrix.len();
1108    if matrix.iter().any(|row| row.len() != n) {
1109        return Err("matrix is not square".to_owned());
1110    }
1111    if indices.iter().any(|&idx| idx >= n) {
1112        return Err("terminal map references a conductor outside the matrix".to_owned());
1113    }
1114    Ok(())
1115}
1116
1117fn submatrix(matrix: &[Vec<Complex64>], rows: &[usize], cols: &[usize]) -> Vec<Vec<Complex64>> {
1118    rows.iter()
1119        .map(|&row| cols.iter().map(|&col| matrix[row][col]).collect())
1120        .collect()
1121}
1122
1123#[allow(clippy::needless_range_loop)]
1124fn invert_complex_matrix(matrix: &[Vec<Complex64>]) -> Result<Vec<Vec<Complex64>>, String> {
1125    let n = matrix.len();
1126    if n == 0 || matrix.iter().any(|row| row.len() != n) {
1127        return Err("neutral block is not square".to_owned());
1128    }
1129    let mut aug = vec![vec![Complex64::new(0.0, 0.0); 2 * n]; n];
1130    for i in 0..n {
1131        for j in 0..n {
1132            aug[i][j] = matrix[i][j];
1133        }
1134        aug[i][n + i] = Complex64::new(1.0, 0.0);
1135    }
1136
1137    for col in 0..n {
1138        let pivot = (col..n)
1139            .max_by(|&a, &b| aug[a][col].norm_sqr().total_cmp(&aug[b][col].norm_sqr()))
1140            .ok_or_else(|| "neutral block is singular".to_owned())?;
1141        if aug[pivot][col].norm() <= f64::EPSILON {
1142            return Err("neutral block is singular".to_owned());
1143        }
1144        if pivot != col {
1145            aug.swap(pivot, col);
1146        }
1147        let pivot_value = aug[col][col];
1148        for j in 0..(2 * n) {
1149            aug[col][j] /= pivot_value;
1150        }
1151        for row in 0..n {
1152            if row == col {
1153                continue;
1154            }
1155            let factor = aug[row][col];
1156            if factor.norm() <= f64::EPSILON {
1157                continue;
1158            }
1159            for j in 0..(2 * n) {
1160                let pivot_entry = aug[col][j];
1161                aug[row][j] -= factor * pivot_entry;
1162            }
1163        }
1164    }
1165
1166    Ok(aug
1167        .into_iter()
1168        .map(|row| row.into_iter().skip(n).collect())
1169        .collect())
1170}
1171
1172fn matmul(a: &[Vec<Complex64>], b: &[Vec<Complex64>]) -> Vec<Vec<Complex64>> {
1173    if a.is_empty() || b.is_empty() {
1174        return Vec::new();
1175    }
1176    let rows = a.len();
1177    let cols = b[0].len();
1178    let inner = b.len();
1179    let mut out = vec![vec![Complex64::new(0.0, 0.0); cols]; rows];
1180    for i in 0..rows {
1181        for k in 0..inner {
1182            for j in 0..cols {
1183                out[i][j] += a[i][k] * b[k][j];
1184            }
1185        }
1186    }
1187    out
1188}
1189
1190fn matrix_sub(a: &[Vec<Complex64>], b: &[Vec<Complex64>]) -> Vec<Vec<Complex64>> {
1191    a.iter()
1192        .zip(b.iter())
1193        .map(|(a_row, b_row)| {
1194            a_row
1195                .iter()
1196                .zip(b_row.iter())
1197                .map(|(&a_value, &b_value)| a_value - b_value)
1198                .collect()
1199        })
1200        .collect()
1201}
1202
1203#[allow(clippy::many_single_char_names)]
1204fn sequence_basis() -> [[Complex64; 3]; 3] {
1205    let scale = 1.0 / SQRT_3;
1206    let a = Complex64::from_polar(1.0, 2.0 * PI / 3.0);
1207    let a2 = a * a;
1208    [
1209        [
1210            Complex64::new(scale, 0.0),
1211            Complex64::new(scale, 0.0),
1212            Complex64::new(scale, 0.0),
1213        ],
1214        [Complex64::new(scale, 0.0), a2 * scale, a * scale],
1215        [Complex64::new(scale, 0.0), a * scale, a2 * scale],
1216    ]
1217}
1218
1219fn sequence_matrix(matrix: &[Vec<Complex64>]) -> [[Complex64; 3]; 3] {
1220    let basis = sequence_basis();
1221    let mut seq = [[Complex64::new(0.0, 0.0); 3]; 3];
1222    for p in 0..3 {
1223        for q in 0..3 {
1224            for i in 0..3 {
1225                for j in 0..3 {
1226                    seq[p][q] += basis[i][p].conj() * matrix[i][j] * basis[j][q];
1227                }
1228            }
1229        }
1230    }
1231    seq
1232}
1233
1234fn sequence_coupling_norm(seq: &[[Complex64; 3]; 3]) -> f64 {
1235    let mut sum = 0.0;
1236    for (i, row) in seq.iter().enumerate() {
1237        for (j, value) in row.iter().enumerate() {
1238            if i != j {
1239                sum += value.norm_sqr();
1240            }
1241        }
1242    }
1243    sum.sqrt()
1244}
1245
1246/// The branch rating, in MVA. BMOPF schema 0.1.0 gives a line its own
1247/// `i_max`/`s_max`, which "overrides the linecode's i_max for this line", so
1248/// both line fields are tried before either linecode field. Within one owner
1249/// `s_max` comes first, because an apparent power limit needs no voltage.
1250///
1251/// A field the active conductors leave unusable falls through to the next
1252/// candidate rather than ending the search: a line whose `s_max` is all
1253/// infinities must not hide a linecode that carries a real rating.
1254fn line_rate_mva(
1255    line: &DistLine,
1256    code: &DistLineCode,
1257    active: &[usize],
1258    line_to_line_volts: f64,
1259) -> Option<f64> {
1260    for (s_max, i_max) in [
1261        (line.s_max.as_ref(), line.i_max.as_ref()),
1262        (code.s_max.as_ref(), code.i_max.as_ref()),
1263    ] {
1264        if let Some(mva) = s_max.and_then(|values| apparent_power_mva(values, active)) {
1265            return Some(mva);
1266        }
1267        if let Some(amps) = i_max.and_then(|values| limiting_amps(values, active)) {
1268            return Some(SQRT_3 * line_to_line_volts * amps / 1_000_000.0);
1269        }
1270    }
1271    None
1272}
1273
1274/// The summed apparent power limit of the active conductors, in MVA, or None
1275/// when any of them has no finite limit.
1276fn apparent_power_mva(s_max: &[f64], active: &[usize]) -> Option<f64> {
1277    let values: Vec<_> = active
1278        .iter()
1279        .filter_map(|&idx| s_max.get(idx).copied())
1280        .collect();
1281    (!values.is_empty() && values.iter().all(|value| value.is_finite()))
1282        .then(|| values.iter().sum::<f64>() / 1_000_000.0)
1283}
1284
1285/// The smallest usable current limit over the active conductors, in amps.
1286fn limiting_amps(i_max: &[f64], active: &[usize]) -> Option<f64> {
1287    active
1288        .iter()
1289        .filter_map(|&idx| i_max.get(idx).copied())
1290        .filter(|value| value.is_finite() && *value >= 0.0)
1291        .reduce(f64::min)
1292}
1293
1294fn partial_phase_admittance(g: &Mat, b: &Mat, active: &[usize]) -> Complex64 {
1295    let mut total = Complex64::new(0.0, 0.0);
1296    for &idx in active {
1297        let Some(g_row) = g.get(idx) else {
1298            continue;
1299        };
1300        let Some(b_row) = b.get(idx) else {
1301            continue;
1302        };
1303        let Some(&g_value) = g_row.get(idx) else {
1304            continue;
1305        };
1306        let Some(&b_value) = b_row.get(idx) else {
1307            continue;
1308        };
1309        total += Complex64::new(g_value, b_value);
1310    }
1311    total / 3.0
1312}
1313
1314fn si_power_to_mega(value: f64) -> f64 {
1315    value / 1_000_000.0
1316}
1317
1318fn option_vec_sum_mw(values: Option<&[f64]>) -> Option<f64> {
1319    values.map(|v| si_power_to_mega(v.iter().sum()))
1320}
1321
1322fn radians_to_degrees(value: f64) -> f64 {
1323    value * 180.0 / PI
1324}
1325
1326fn status_from_diagnostics(diagnostics: &[StructuredDiagnostic]) -> ValidationStatus {
1327    diagnostics
1328        .iter()
1329        .map(|d| match d.severity {
1330            DiagnosticSeverity::Debug => ValidationStatus::Ok,
1331            DiagnosticSeverity::Info => ValidationStatus::Info,
1332            DiagnosticSeverity::Warning => ValidationStatus::Warning,
1333            DiagnosticSeverity::Error => ValidationStatus::Error,
1334            DiagnosticSeverity::Fatal => ValidationStatus::Fatal,
1335        })
1336        .max()
1337        .unwrap_or(ValidationStatus::Ok)
1338}
1339
1340fn check_options(
1341    options: MulticonductorToBalancedOptions,
1342    report: &mut MulticonductorToBalancedReadiness,
1343) {
1344    if !options.base_mva.is_finite() || options.base_mva <= 0.0 {
1345        report.diagnostics.push(StructuredDiagnostic::new(
1346            "LOWER.MULTI_TO_BALANCED.INVALID_BASE_MVA",
1347            DiagnosticSeverity::Error,
1348            DiagnosticStage::Lower,
1349            format!(
1350                "base_mva must be positive and finite for multiconductor to balanced lowering; got {}",
1351                options.base_mva
1352            ),
1353        ));
1354    }
1355}
1356
1357fn check_bus_conductor_sets(
1358    net: &MulticonductorNetwork,
1359    report: &mut MulticonductorToBalancedReadiness,
1360) {
1361    let neutral_terminals = global_neutral_terminals(net);
1362    let mut saw_neutral = false;
1363    for (i, bus) in net.buses.iter().enumerate() {
1364        let active_count = active_terminal_count(&bus.terminals, Some(bus), &neutral_terminals);
1365        if active_count < bus.terminals.len() {
1366            saw_neutral = true;
1367        }
1368
1369        match active_count {
1370            3 => {}
1371            2 => report.diagnostics.push(
1372                StructuredDiagnostic::new(
1373                    "LOWER.MULTI_TO_BALANCED.AMBIGUOUS_TERMINAL_MAP",
1374                    DiagnosticSeverity::Error,
1375                    DiagnosticStage::Lower,
1376                    format!(
1377                        "bus {} has two active terminals; no unique positive sequence projection is defined",
1378                        bus.id
1379                    ),
1380                )
1381                .with_element_path(format!("/model/multiconductor_network/buses/{i}/terminals")),
1382            ),
1383            0 | 1 => report.diagnostics.push(
1384                StructuredDiagnostic::new(
1385                    "LOWER.MULTI_TO_BALANCED.UNSUPPORTED_CONDUCTOR_SET",
1386                    DiagnosticSeverity::Error,
1387                    DiagnosticStage::Lower,
1388                    format!(
1389                        "bus {} has {active_count} active terminal; multiconductor to balanced lowering starts with three phase input",
1390                        bus.id
1391                    ),
1392                )
1393                .with_element_path(format!("/model/multiconductor_network/buses/{i}/terminals")),
1394            ),
1395            _ => report.diagnostics.push(
1396                StructuredDiagnostic::new(
1397                    "LOWER.MULTI_TO_BALANCED.UNSUPPORTED_CONDUCTOR_SET",
1398                    DiagnosticSeverity::Error,
1399                    DiagnosticStage::Lower,
1400                    format!(
1401                        "bus {} has {active_count} active terminals; multiconductor to balanced lowering starts with three phase input",
1402                        bus.id
1403                    ),
1404                )
1405                .with_element_path(format!("/model/multiconductor_network/buses/{i}/terminals")),
1406            ),
1407        }
1408    }
1409
1410    if saw_neutral {
1411        report
1412            .approximations
1413            .push("Kron reduction of neutral conductor before sequence transform".to_owned());
1414        report.diagnostics.push(StructuredDiagnostic::new(
1415            "LOWER.MULTI_TO_BALANCED.KRON_REDUCTION_REQUIRED",
1416            DiagnosticSeverity::Info,
1417            DiagnosticStage::Lower,
1418            "neutral conductors require Kron reduction before the sequence transform",
1419        ));
1420    }
1421}
1422
1423fn check_line_terminal_maps(
1424    net: &MulticonductorNetwork,
1425    report: &mut MulticonductorToBalancedReadiness,
1426) {
1427    let neutral_terminals = global_neutral_terminals(net);
1428    for (i, line) in net.lines.iter().enumerate() {
1429        for (field, bus_id, terminal_map) in [
1430            (
1431                "terminal_map_from",
1432                line.bus_from.as_str(),
1433                line.terminal_map_from.as_slice(),
1434            ),
1435            (
1436                "terminal_map_to",
1437                line.bus_to.as_str(),
1438                line.terminal_map_to.as_slice(),
1439            ),
1440        ] {
1441            let bus = net.bus(bus_id);
1442            let active_count = active_terminal_count(terminal_map, bus, &neutral_terminals);
1443            if active_count != 3 {
1444                report.diagnostics.push(
1445                    StructuredDiagnostic::new(
1446                        "LOWER.MULTI_TO_BALANCED.UNSUPPORTED_CONDUCTOR_SET",
1447                        DiagnosticSeverity::Error,
1448                        DiagnosticStage::Lower,
1449                        format!(
1450                            "line {} {field} has {active_count} active terminal(s); balanced branch lowering requires three active phase conductors",
1451                            line.name
1452                        ),
1453                    )
1454                    .with_element_path(format!("/model/multiconductor_network/lines/{i}/{field}")),
1455                );
1456            }
1457        }
1458    }
1459}
1460
1461fn check_linecodes(net: &MulticonductorNetwork, report: &mut MulticonductorToBalancedReadiness) {
1462    for (i, line) in net.lines.iter().enumerate() {
1463        let Some(code) = net.linecode(&line.linecode) else {
1464            report.diagnostics.push(
1465                StructuredDiagnostic::new(
1466                    "LOWER.MULTI_TO_BALANCED.UNKNOWN_LINECODE",
1467                    DiagnosticSeverity::Error,
1468                    DiagnosticStage::Lower,
1469                    format!(
1470                        "line {} references unknown linecode `{}`",
1471                        line.name, line.linecode
1472                    ),
1473                )
1474                .with_element_path(format!("/model/multiconductor_network/lines/{i}/linecode")),
1475            );
1476            continue;
1477        };
1478        if code.n_conductors != line.terminal_map_from.len()
1479            || code.n_conductors != line.terminal_map_to.len()
1480        {
1481            report.diagnostics.push(
1482                StructuredDiagnostic::new(
1483                    "LOWER.MULTI_TO_BALANCED.LINECODE_TERMINAL_MISMATCH",
1484                    DiagnosticSeverity::Error,
1485                    DiagnosticStage::Lower,
1486                    format!(
1487                        "line {} uses linecode {} with {} conductor(s), but its terminal maps have {} and {} terminal(s)",
1488                        line.name,
1489                        code.name,
1490                        code.n_conductors,
1491                        line.terminal_map_from.len(),
1492                        line.terminal_map_to.len()
1493                    ),
1494                )
1495                .with_element_path(format!("/model/multiconductor_network/lines/{i}/linecode")),
1496            );
1497        }
1498        if !square_matrix_shape(&code.r_series, code.n_conductors)
1499            || !square_matrix_shape(&code.x_series, code.n_conductors)
1500            || !square_matrix_shape(&code.g_from, code.n_conductors)
1501            || !square_matrix_shape(&code.b_from, code.n_conductors)
1502            || !square_matrix_shape(&code.g_to, code.n_conductors)
1503            || !square_matrix_shape(&code.b_to, code.n_conductors)
1504        {
1505            report.diagnostics.push(
1506                StructuredDiagnostic::new(
1507                    "LOWER.MULTI_TO_BALANCED.INVALID_LINECODE_MATRIX",
1508                    DiagnosticSeverity::Error,
1509                    DiagnosticStage::Lower,
1510                    format!(
1511                        "linecode {} does not carry square {} conductor matrices",
1512                        code.name, code.n_conductors
1513                    ),
1514                )
1515                .with_element_path(format!(
1516                    "/model/multiconductor_network/linecodes/{}",
1517                    code.name
1518                )),
1519            );
1520        }
1521    }
1522}
1523
1524fn square_matrix_shape(matrix: &Mat, n: usize) -> bool {
1525    matrix.len() == n && matrix.iter().all(|row| row.len() == n)
1526}
1527
1528fn check_switches(net: &MulticonductorNetwork, report: &mut MulticonductorToBalancedReadiness) {
1529    for (i, sw) in net.switches.iter().enumerate() {
1530        if sw.open {
1531            report.diagnostics.push(
1532                StructuredDiagnostic::new(
1533                    "LOWER.MULTI_TO_BALANCED.DROPPED_OPEN_SWITCH",
1534                    DiagnosticSeverity::Info,
1535                    DiagnosticStage::Lower,
1536                    format!(
1537                        "open switch {} is dropped by multiconductor to balanced lowering",
1538                        sw.name
1539                    ),
1540                )
1541                .with_element_path(format!("/model/multiconductor_network/switches/{i}")),
1542            );
1543        } else {
1544            report.diagnostics.push(
1545                StructuredDiagnostic::new(
1546                    "LOWER.MULTI_TO_BALANCED.UNSUPPORTED_CLOSED_SWITCH",
1547                    DiagnosticSeverity::Error,
1548                    DiagnosticStage::Lower,
1549                    format!(
1550                        "closed switch {} is not lowered into a zero impedance balanced branch",
1551                        sw.name
1552                    ),
1553                )
1554                .with_element_path(format!("/model/multiconductor_network/switches/{i}")),
1555            );
1556        }
1557    }
1558}
1559
1560fn global_neutral_terminals(net: &MulticonductorNetwork) -> BTreeSet<String> {
1561    net.buses
1562        .iter()
1563        .flat_map(|bus| bus.grounded.iter().cloned())
1564        .collect()
1565}
1566
1567fn active_terminal_count(
1568    terminals: &[String],
1569    bus: Option<&DistBus>,
1570    neutral_terminals: &BTreeSet<String>,
1571) -> usize {
1572    terminals
1573        .iter()
1574        .filter(|terminal| !is_neutral_terminal(terminal, bus, neutral_terminals))
1575        .count()
1576}
1577
1578fn is_neutral_terminal(
1579    terminal: &str,
1580    bus: Option<&DistBus>,
1581    neutral_terminals: &BTreeSet<String>,
1582) -> bool {
1583    terminal == "0"
1584        || terminal.eq_ignore_ascii_case("n")
1585        || bus.is_some_and(|b| b.grounded.iter().any(|g| g == terminal))
1586        || neutral_terminals.contains(terminal)
1587}
1588
1589fn check_phase_reference(
1590    net: &MulticonductorNetwork,
1591    report: &mut MulticonductorToBalancedReadiness,
1592) {
1593    let neutral_terminals = global_neutral_terminals(net);
1594    let has_three_phase_source = net.sources.iter().any(|source| {
1595        let bus = net.bus(&source.bus);
1596        active_terminal_count(&source.terminal_map, bus, &neutral_terminals) == 3
1597    });
1598
1599    if !has_three_phase_source {
1600        report.diagnostics.push(StructuredDiagnostic::new(
1601            "LOWER.MULTI_TO_BALANCED.MISSING_PHASE_REFERENCE",
1602            DiagnosticSeverity::Error,
1603            DiagnosticStage::Lower,
1604            "multiconductor to balanced lowering requires a three phase voltage source reference",
1605        ));
1606    }
1607}
1608
1609fn check_transformers(net: &MulticonductorNetwork, report: &mut MulticonductorToBalancedReadiness) {
1610    for (i, transformer) in net.transformers.iter().enumerate() {
1611        report.diagnostics.push(
1612            StructuredDiagnostic::new(
1613                "LOWER.MULTI_TO_BALANCED.UNSUPPORTED_TRANSFORMER",
1614                DiagnosticSeverity::Error,
1615                DiagnosticStage::Lower,
1616                format!(
1617                    "transformer {} is not supported by the multiconductor to balanced preflight",
1618                    transformer.name
1619                ),
1620            )
1621            .with_element_path(format!("/model/multiconductor_network/transformers/{i}")),
1622        );
1623    }
1624}
1625
1626fn check_untyped_objects(
1627    net: &MulticonductorNetwork,
1628    report: &mut MulticonductorToBalancedReadiness,
1629) {
1630    for (i, obj) in net.untyped.iter().enumerate() {
1631        report.diagnostics.push(
1632            StructuredDiagnostic::new(
1633                "LOWER.MULTI_TO_BALANCED.UNSUPPORTED_OBJECT",
1634                DiagnosticSeverity::Error,
1635                DiagnosticStage::Lower,
1636                format!(
1637                    "{} {} is preserved as an untyped object and cannot be lowered",
1638                    obj.class, obj.name
1639                ),
1640            )
1641            .with_element_path(format!("/model/multiconductor_network/untyped/{i}")),
1642        );
1643    }
1644}