Skip to main content

powerio_dist/bmopf/
write.rs

1//! [`MulticonductorNetwork`] into strict BMOPF JSON.
2//!
3//! Output is schema valid wherever the schema permits the data.
4//!
5//! Numbers serialize through serde_json (shortest round trip form).
6//! Nonfinite values cannot appear in JSON; they emit as 0 with a warning
7//! naming the element and field.
8
9use std::collections::{BTreeMap, BTreeSet};
10use std::f64::consts::{FRAC_PI_2, PI, TAU};
11
12use serde_json::{Map, Value, json};
13
14use super::profile;
15use super::validate::strictly_positive;
16use crate::convert::TextEmission;
17use crate::diagnostics::codes as C;
18use crate::diagnostics::{Diagnostic, DiagnosticInfo};
19use crate::model::{
20    ActivePowerReference, ActivePowerUnit, ConductorMatrix, Configuration, ControlVoltageReference,
21    DistControlProfile, DistGenerator, DistIbr, DistLoadVoltageModel, DistTransformer, DistWinding,
22    DistWindingConn, Extras, MulticonductorNetwork, ReactivePowerReference, ReactivePowerUnit,
23    VoltVarControl, VoltWattControl, VoltageSource, open_delta_connection, open_delta_pairable,
24    pair_keys, winding_phase_pair,
25};
26
27/// Untyped classes that belong to the BMOPF ecosystem. The schema declares
28/// all but `capacitor` at the top level; [`Writer::raw_table_at_top_level`]
29/// answers which, and the rest re-emit under the free-form `extras` object.
30const RAW_BMOPF_EXTRAS_TABLES: &[&str] = &[
31    "ibr",
32    "control_profile",
33    "dc_bus",
34    "dc_branch",
35    "dc_grounding",
36    "dc_load",
37    "dc_source",
38    "time_series",
39    // An OpenDSS capacitor the dss reader could not type (a nonpositive
40    // phase count) stays an untyped object. The typed `capacitor` table is
41    // strict, so the raw properties cannot go there; they re-emit under
42    // `extras`, which the schema leaves free-form.
43    "capacitor",
44];
45
46/// The reader's verbatim stash of a source document's own `extras` object.
47const BMOPF_EXTRAS_STASH: &str = "bmopf_extras";
48
49/// The reader's verbatim stash of a source document's `meta` object.
50const BMOPF_META_STASH: &str = "bmopf_meta";
51
52/// The reader's verbatim stash of a source document's `terminal_conventions`.
53const BMOPF_TERMINAL_CONVENTIONS_STASH: &str = "bmopf_terminal_conventions";
54
55const IBR_EXTRA_FIELDS: &[&str] = &[
56    "dc_link_coupled",
57    "p_dc_min",
58    "p_dc_max",
59    "dc_bus",
60    "dc_terminal_map",
61    "dc_control",
62    "dc_v_set",
63    "dc_p_ref",
64    "dc_droop",
65    "dc_deadband",
66    "r_filter",
67    "x_filter",
68    "b_filter_shunt",
69    "grid_forming",
70    "v_ref_internal",
71    "cost",
72    "energy_cost_rate",
73    "time_series",
74];
75
76const BMOPF_DELTA_ROLLS_EXTRA: &str = "bmopf_delta_rolls";
77
78/// Upper bound on the model-driven dimensions this writer expands
79/// quadratically: the winding count feeding the `x_sc` pair table and the
80/// conductor count an absent matrix is materialized at as zeros. The BMOPF
81/// and DSS readers cap the same quantities at 64 on their way in, but callers
82/// can construct a `MulticonductorNetwork` without those caps, and a
83/// linear-size model could otherwise demand O(n²) memory here. No physical
84/// element comes near this bound.
85const MAX_DIM: usize = 64;
86
87const TRANSFORMER_NO_LOAD_ALLOWED_EXTRAS: [&str; 8] = [
88    "bmopf_power_base",
89    "bmopf_winding_metadata",
90    "g_no_load",
91    "b_no_load",
92    "no_load_shunt",
93    "%noloadloss",
94    "%imag",
95    BMOPF_DELTA_ROLLS_EXTRA,
96];
97/// The BMOPFTools schema extension fields the regulator subtypes carry
98/// beyond the shared transformer shape; read into extras verbatim and
99/// re-emitted verbatim.
100const REGULATOR_EXTENSION_EXTRAS: [&str; 5] = [
101    "tap_ratio_min",
102    "tap_ratio_max",
103    "regulator_type",
104    "i_max_from",
105    "i_max_to",
106];
107
108/// The stated regulator ohm fields a BMOPF read stashes verbatim so a round
109/// trip reproduces exactly the fields the source stated.
110const REGULATOR_STATED_OHMS: [&str; 4] = [
111    "r_series_from",
112    "r_series_to",
113    "x_series_from",
114    "x_series_to",
115];
116
117const TRANSFORMER_TWO_WINDING_ALLOWED_EXTRAS: [&str; 19] = [
118    "tap_min",
119    "tap_max",
120    "mintap",
121    "maxtap",
122    "numtaps",
123    "pmd_tm_set",
124    "pmd_tm_lb",
125    "pmd_tm_ub",
126    "pmd_tm_fix",
127    "pmd_tm_step",
128    "g_no_load",
129    "b_no_load",
130    "no_load_shunt",
131    "r_neutral_from",
132    "x_neutral_from",
133    "r_neutral_to",
134    "x_neutral_to",
135    "%noloadloss",
136    "%imag",
137];
138
139/// The regulator subtypes keep both the shared allowed extras and the
140/// extension fields.
141fn regulator_allowed_extras() -> Vec<&'static str> {
142    TRANSFORMER_TWO_WINDING_ALLOWED_EXTRAS
143        .iter()
144        .chain(REGULATOR_EXTENSION_EXTRAS.iter())
145        .chain(REGULATOR_STATED_OHMS.iter())
146        .chain(["bmopf_open_delta"].iter())
147        .copied()
148        .collect()
149}
150
151/// Options for BMOPF JSON output. PowerIO writes one BMOPF, so there is
152/// nothing to choose yet; the type is `#[non_exhaustive]` so options can be
153/// added without breaking callers.
154#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
155#[non_exhaustive]
156pub struct BmopfEmitOptions {}
157
158/// Emits the strict BMOPF document. Every field the schema cannot carry
159/// is reported in the warnings. [The module docs](crate::bmopf) state when
160/// the emitted `terminal_conventions` block stops being valid.
161///
162/// # Panics
163///
164/// Never in practice: the document is maps, strings, and finite numbers,
165/// which always serialize.
166#[cfg(test)]
167pub(crate) fn emit_bmopf_json_text(net: &MulticonductorNetwork) -> TextEmission {
168    emit_bmopf_json_text_with_options(net, BmopfEmitOptions::default())
169}
170
171/// Emits BMOPF JSON with explicit options.
172///
173/// # Panics
174///
175/// Never in practice: the document is maps, strings, and finite numbers,
176/// which always serialize.
177pub(crate) fn emit_bmopf_json_text_with_options(
178    net: &MulticonductorNetwork,
179    BmopfEmitOptions {}: BmopfEmitOptions,
180) -> TextEmission {
181    let mut w = Writer {
182        warnings: crate::diagnostics::Diagnostics::new(),
183        dropped_extras: BTreeMap::new(),
184        time_series_profiles: BTreeMap::new(),
185        geometry_embedded: false,
186    };
187    let doc = w.document(net);
188    w.flush_dropped_extras();
189    TextEmission::new(
190        serde_json::to_string_pretty(&doc).expect("maps and finite numbers") + "\n",
191        Vec::new(),
192        w.warnings,
193    )
194}
195
196struct Writer {
197    warnings: crate::diagnostics::Diagnostics,
198    /// Passthrough extras with no schema slot, keyed by field name with the
199    /// elements that carried them, flushed as one aggregated finding per
200    /// field: on a real feeder one warning per field per element buried
201    /// every finding a consumer would act on (#377).
202    dropped_extras: BTreeMap<String, Vec<String>>,
203    /// Normalized, schema-compatible profiles prepared once for this emission.
204    time_series_profiles: BTreeMap<String, (Value, Option<Value>)>,
205    /// Whether a bus or line of this emission carries a typed `geo` field, so
206    /// `meta.crs` (and, when the schema cannot name the space, the
207    /// `extras.powerio_geo` record) must describe its coordinate system.
208    geometry_embedded: bool,
209}
210
211impl Writer {
212    fn prepare_time_series_profiles(&mut self, net: &MulticonductorNetwork) {
213        // Retained PMD provenance also survives canonical values whose source
214        // format hint was cleared. MATHEMATICAL/unknown PMD profiles have no
215        // supported ENGINEERING hour-axis interpretation here.
216        let engineering_marker = net
217            .extras()
218            .get("pmd_data_model")
219            .and_then(Value::as_str)
220            .is_some_and(|model| model.eq_ignore_ascii_case("ENGINEERING"));
221        let is_pmd = *net.source_format() == Some(crate::model::DistSourceFormat::PmdJson)
222            || engineering_marker;
223        let foreign_pmd = *net.source_format() == Some(crate::model::DistSourceFormat::PmdMathJson)
224            || net.extras().contains_key("pmd_math_top_level")
225            || net.extras().contains_key("pmd_data_model") && !is_pmd;
226        self.time_series_profiles = net
227            .untyped_objects()
228            .iter()
229            .filter(|object| object.class == "time_series" && !foreign_pmd)
230            .filter_map(|object| {
231                let mut unplaced = Vec::new();
232                raw_bmopf_value(object, &mut unplaced)
233                    .filter(|_| unplaced.is_empty())
234                    .and_then(|value| normalized_bmopf_time_series_for_source(&value, is_pmd))
235                    .map(|normalized| (object.name.clone(), normalized))
236            })
237            .collect();
238
239        // Only load p/q references are activated by this writer. Compare each
240        // referenced profile once; BMOPF cannot resample different step axes.
241        let referenced: BTreeSet<&str> = net
242            .loads()
243            .iter()
244            .filter_map(|load| load.extras.get("time_series").and_then(Value::as_object))
245            .flat_map(|refs| refs.iter())
246            .filter(|(field, _)| matches!(field.as_str(), "pd_nom" | "p_nom" | "qd_nom" | "q_nom"))
247            .filter_map(|(_, value)| value.as_str())
248            .filter(|name| self.time_series_profiles.contains_key(*name))
249            .collect();
250        let incompatible_steps = {
251            let mut profiles = referenced
252                .iter()
253                .filter_map(|name| self.time_series_profiles.get(*name));
254            profiles.next().is_some_and(|(first, _)| {
255                profiles.any(|(other, _)| !bmopf_profiles_share_steps(first, other))
256            })
257        };
258        if incompatible_steps {
259            self.warn(
260                &C::EMIT_BMOPF_RETAINED_SOURCE_ONLY,
261                "referenced time_series profiles have different step counts or time axes; \
262                 retained under extras.time_series with inactive load references",
263            );
264            self.time_series_profiles
265                .retain(|name, _| !referenced.contains(name.as_str()));
266        }
267    }
268
269    fn warn(&mut self, info: &'static DiagnosticInfo, msg: impl Into<String>) {
270        self.warnings.push(info, msg);
271    }
272
273    fn diagnostic(
274        &mut self,
275        code: &'static DiagnosticInfo,
276        element_path: impl Into<String>,
277        message: impl Into<String>,
278        details: Map<String, Value>,
279    ) {
280        let mut diagnostic = Diagnostic::of(code, message)
281            .with_details(details)
282            .expect("writer-built details stay within the record bounds");
283        crate::diagnostics::attach_target(&mut diagnostic, element_path.into());
284        self.warnings.record(diagnostic);
285    }
286
287    fn transformer_diagnostic(
288        &mut self,
289        t: &DistTransformer,
290        code: &'static DiagnosticInfo,
291        message: impl Into<String>,
292        mut details: Map<String, Value>,
293    ) {
294        details.insert("transformer".into(), json!(&t.name));
295        self.diagnostic(code, format!("transformer {}", t.name), message, details);
296    }
297
298    /// Finite number guard (the jnum pattern): JSON has no Inf/NaN.
299    fn num(&mut self, v: f64, what: &str) -> Value {
300        if v.is_finite() {
301            json!(v)
302        } else {
303            self.warn(
304                &C::EMIT_BMOPF_VALUE_DEFAULTED,
305                format!("{what}: nonfinite value emitted as 0"),
306            );
307            json!(0.0)
308        }
309    }
310
311    fn nums(&mut self, vs: &[f64], what: &str) -> Value {
312        Value::Array(vs.iter().map(|&v| self.num(v, what)).collect())
313    }
314
315    /// A rating/bound array. PMD spells an unbounded phase as JSON null,
316    /// which restores as ±Inf; BMOPF has no unbounded spelling, and the
317    /// `num` zero fallback would turn "no limit" into a zero limit. Drop
318    /// the whole field with a warning instead.
319    /// BMOPF semantic rules on bus bounds: `vng_max` and `vpn_*` need a
320    /// neutral terminal, `vpp_*` two phases, and the sequence bounds exactly
321    /// three. A bound the bus cannot carry is dropped and reported rather
322    /// than written into a document that would not conform.
323    fn drop_bounds_the_bus_cannot_carry(
324        &mut self,
325        b: &crate::model::DistBus,
326        o: &mut Map<String, Value>,
327        conventions: Option<&Value>,
328    ) {
329        let phases = b.phase_indices(conventions).len();
330        // The one terminal classification: an earth `0` is not a neutral.
331        let neutral = !b.neutral_indices(conventions).is_empty();
332        let mut rules: Vec<(&str, bool, &str)> = Vec::new();
333        for key in ["vng_max", "vpn_min", "vpn_max"] {
334            rules.push((key, neutral, "needs a neutral terminal"));
335        }
336        for key in ["vpp_min", "vpp_max"] {
337            rules.push((key, phases >= 2, "needs at least two phase terminals"));
338        }
339        for key in ["vpos_min", "vpos_max", "vneg_max", "vzero_max"] {
340            rules.push((key, phases == 3, "needs exactly three phase terminals"));
341        }
342        for (key, allowed, why) in rules {
343            if !allowed && o.remove(key).is_some() {
344                self.warn(
345                    &C::EMIT_BMOPF_FIELD_DROPPED,
346                    format!(
347                        "bus {}: {key} {why} under the BMOPF semantic rules; dropped",
348                        b.id
349                    ),
350                );
351            }
352        }
353    }
354
355    /// Whether a limit array has one entry per conductor, as the schema
356    /// states line and linecode `s_max`. Any other length is dropped and
357    /// reported rather than padded: a missing conductor's limit is unknown.
358    fn per_conductor(&mut self, vs: &[f64], conductors: usize, what: &str) -> bool {
359        if vs.len() == conductors {
360            return true;
361        }
362        self.warn(
363            &C::EMIT_BMOPF_FIELD_DROPPED,
364            format!(
365                "{what}: {} entries for {conductors} conductors; the BMOPF schema states one \
366                 per conductor, and the missing limits are unknown; field dropped",
367                vs.len()
368            ),
369        );
370        false
371    }
372
373    fn bounds(&mut self, vs: &[f64], what: &str) -> Option<Value> {
374        if vs.iter().all(|v| v.is_finite()) {
375            Some(json!(vs))
376        } else {
377            self.warn(
378                &C::EMIT_BMOPF_FIELD_DROPPED,
379                format!(
380                    "{what}: nonfinite entries (an unbounded phase) have no BMOPF spelling; \
381                 field dropped"
382                ),
383            );
384            None
385        }
386    }
387
388    fn extras_dropped(&mut self, extras: &crate::model::Extras, what: &str) {
389        for key in extras.keys() {
390            // `bmopf_subtype` is reader bookkeeping; `conn` marks a delta shunt
391            // whose geometry already lives in the off diagonal B matrix, so it
392            // is preserved, not dropped.
393            if key == "bmopf_subtype" || key == "conn" {
394                continue;
395            }
396            self.dropped_extras
397                .entry(key.clone())
398                .or_default()
399                .push(what.to_owned());
400        }
401    }
402
403    /// The elements a details list names before it collapses to a count: the
404    /// record stays attributable without one details value growing with the
405    /// case.
406    const DROPPED_ELEMENT_LIST_CAP: usize = 100;
407
408    /// One aggregated finding per dropped field name, carrying the count and
409    /// the element list in details and, for a single element, the target.
410    fn flush_dropped_extras(&mut self) {
411        for (key, elements) in std::mem::take(&mut self.dropped_extras) {
412            let count = elements.len();
413            let mut details = Map::new();
414            details.insert("field".into(), json!(key));
415            details.insert("count".into(), json!(count));
416            details.insert(
417                "elements".into(),
418                json!(elements[..count.min(Self::DROPPED_ELEMENT_LIST_CAP)]),
419            );
420            if count > Self::DROPPED_ELEMENT_LIST_CAP {
421                details.insert("elements_truncated".into(), json!(true));
422            }
423            let message = if count == 1 {
424                format!(
425                    "{}: `{key}` has no place in the BMOPF schema; dropped from the output",
426                    elements[0]
427                )
428            } else {
429                format!("`{key}` has no place in the BMOPF schema; dropped from {count} elements")
430            };
431            let mut diagnostic = Diagnostic::of(&C::EMIT_BMOPF_FIELD_DROPPED, message)
432                .with_details(details)
433                .expect("writer-built details stay within the record bounds");
434            if count == 1 {
435                crate::diagnostics::attach_target(&mut diagnostic, elements[0].clone());
436            }
437            self.warnings.record(diagnostic);
438        }
439    }
440
441    /// Provenance + schema-vintage self-identification (the BMOPF `meta` object):
442    /// "generated by powerio vX, targeting BMOPF schema vintage Y." The writer
443    /// owns `schema_version`, `frequency`, and `case_study_generator`, and
444    /// drops the earlier `$schema` key, which the current schema removed; every other
445    /// schema `meta` field of a BMOPF source (title, authors, license, ...)
446    /// folds back from the reader's stash, so a round trip keeps the case
447    /// provenance. Deterministic and round-trip stable — no generated
448    /// timestamp, and nothing that depends on the immediate source format
449    /// (which a round trip would change) — so canonical output is idempotent.
450    /// `meta.schema_version` is the document's one version identifier; the
451    /// schema's `$id`, where the exact bytes were retrieved from, and their
452    /// digest are the provenance record's job.
453    fn meta(&mut self, net: &MulticonductorNetwork) -> Value {
454        let mut m = Map::new();
455        m.insert("schema_version".into(), json!(profile::release()));
456        // The schema requires a strictly positive frequency.
457        let frequency = net.base_frequency();
458        if frequency.is_finite() && frequency > 0.0 {
459            m.insert("frequency".into(), json!(frequency));
460        } else {
461            self.warn(
462                &C::EMIT_BMOPF_FIELD_DROPPED,
463                format!(
464                    "meta frequency {frequency} is not a positive finite frequency, which the \
465                     BMOPF schema requires; dropped"
466                ),
467            );
468        }
469        m.insert(
470            "case_study_generator".into(),
471            json!({"tool": "powerio", "version": env!("CARGO_PKG_VERSION")}),
472        );
473        if let Some(Value::Object(stash)) = net.extras().get(BMOPF_META_STASH) {
474            for (key, value) in stash {
475                match key.as_str() {
476                    // Writer-owned: this document is powerio's emission, at
477                    // the model's frequency, against the version above. A
478                    // source `schema_version` names the version that document
479                    // was written against, not this one, and `crs` is stated
480                    // from the network's geometry by `geometry`.
481                    "$schema" | "schema_version" | "frequency" | "case_study_generator" | "crs" => {
482                    }
483                    "title" | "description" | "license" | "authors" | "data_sources"
484                    | "created" | "modified" | "provenance" | "version" => {
485                        m.insert(key.clone(), value.clone());
486                    }
487                    other => self.warn(
488                        &C::EMIT_BMOPF_FIELD_DROPPED,
489                        format!("meta `{other}` has no slot in the BMOPF schema; dropped"),
490                    ),
491                }
492            }
493        }
494        proposal_provenance(&mut m);
495        Value::Object(m)
496    }
497
498    fn document(&mut self, net: &MulticonductorNetwork) -> Value {
499        self.prepare_time_series_profiles(net);
500        let mut doc = Map::new();
501        if let Some(name) = &net.name() {
502            doc.insert("name".into(), json!(name));
503        }
504        let meta = self.meta(net);
505        doc.insert("meta".into(), meta);
506        if let Some(Value::Object(tc)) = net.extras().get(BMOPF_TERMINAL_CONVENTIONS_STASH) {
507            doc.insert("terminal_conventions".into(), Value::Object(tc.clone()));
508        } else if let Some(tc) = authored_terminal_conventions(net) {
509            doc.insert("terminal_conventions".into(), tc);
510        }
511        self.buses(net, &mut doc);
512        self.line_codes(net, &mut doc);
513
514        self.branches(net, &mut doc);
515        self.injections(net, &mut doc);
516        self.capacitors(net, &mut doc);
517
518        let transformers = self.transformers(net);
519        if !transformers.is_empty() {
520            doc.insert("transformer".into(), Value::Object(transformers));
521        }
522
523        let mut extras = Map::new();
524        if let Some(Value::Object(stash)) = net.extras().get(BMOPF_EXTRAS_STASH) {
525            extras.extend(stash.clone());
526        }
527        self.control_profiles(net, &mut doc);
528        self.ibrs(net, &mut doc);
529        self.untyped_bmopf_tables(net, &mut doc, &mut extras);
530        rename_cost_fields(&mut doc);
531        self.enforce_positive_values(&mut doc);
532        self.component_geometry(net, &mut doc);
533        self.geometry(net, &mut doc, &mut extras);
534        if !extras.is_empty() {
535            doc.insert("extras".into(), Value::Object(extras));
536        }
537        self.warn_unemitted_untyped(net);
538        Value::Object(doc)
539    }
540
541    /// The schema requires ratings, nominal voltages, taps and ratios to be
542    /// strictly positive. A value outside that is dropped and reported rather
543    /// than written: an optional field leaves the record, and a record whose
544    /// required rating or nominal voltage is not positive is dropped whole,
545    /// since it cannot be stated validly without it.
546    fn enforce_positive_values(&mut self, doc: &mut Map<String, Value>) {
547        let drop_fields = |o: &mut Map<String, Value>, keys: &[&str], what: &str, w: &mut Self| {
548            for key in keys {
549                if o.get(*key).is_some_and(|v| !strictly_positive(v)) {
550                    let value = o.remove(*key).unwrap_or(Value::Null);
551                    w.warn(
552                        &C::EMIT_BMOPF_FIELD_DROPPED,
553                        format!(
554                            "{what}: {key} {value} is not strictly positive, which the BMOPF \
555                             schema requires; dropped"
556                        ),
557                    );
558                }
559            }
560        };
561        let mut drop_records = Vec::new();
562        if let Some(Value::Object(subtypes)) = doc.get_mut("transformer") {
563            for (subtype, table) in subtypes.iter_mut() {
564                let (required, optional): (&[&str], &[&str]) = match subtype.as_str() {
565                    "single_phase" | "center_tap" | "wye_delta" | "delta_wye" => (
566                        &["s_rating", "v_nom_from", "v_nom_to"],
567                        &["tap_ratio", "tap_ratio_min", "tap_ratio_max"],
568                    ),
569                    "single_phase_autotransformer" | "open_delta_regulator" => (
570                        &[],
571                        &[
572                            "s_rating",
573                            "voltage_ratio",
574                            "voltage_ratio_min",
575                            "voltage_ratio_max",
576                        ],
577                    ),
578                    "n_winding" => (&["s_rating"], &[]),
579                    _ => continue,
580                };
581                let Value::Object(table) = table else {
582                    continue;
583                };
584                for (name, record) in table.iter_mut() {
585                    let Value::Object(o) = record else { continue };
586                    let what = format!("transformer {name}");
587                    drop_fields(o, optional, &what, self);
588                    let mut invalid = required
589                        .iter()
590                        .find(|key| o.get(**key).is_some_and(|v| !strictly_positive(v)))
591                        .map(|key| (*key).to_owned());
592                    if let Some(Value::Array(windings)) = o.get_mut("windings") {
593                        for (idx, winding) in windings.iter_mut().enumerate() {
594                            let Value::Object(w) = winding else { continue };
595                            let what = format!("transformer {name} winding {idx}");
596                            drop_fields(
597                                w,
598                                &["s_rating", "tap_ratio", "tap_ratio_min", "tap_ratio_max"],
599                                &what,
600                                self,
601                            );
602                            if w.get("v_nom").is_some_and(|v| !strictly_positive(v)) {
603                                invalid.get_or_insert_with(|| format!("winding {idx} v_nom"));
604                            }
605                        }
606                    }
607                    if let Some(key) = invalid {
608                        drop_records.push((subtype.clone(), name.clone(), key));
609                    }
610                }
611            }
612            for (subtype, name, key) in drop_records.drain(..) {
613                if let Some(Value::Object(table)) = subtypes.get_mut(&subtype) {
614                    table.remove(&name);
615                }
616                self.warn(
617                    &C::EMIT_BMOPF_RECORD_DROPPED,
618                    format!(
619                        "transformer {name}: {key} is not strictly positive, which the BMOPF \
620                         schema requires; the {subtype} record is dropped from the output"
621                    ),
622                );
623            }
624            subtypes.retain(|_, table| table.as_object().is_none_or(|t| !t.is_empty()));
625        }
626        self.drop_nonpositive_capacitors(doc);
627    }
628
629    /// A capacitor's `v_nom` is required and strictly positive in the
630    /// schema; a capacitor without a positive one is dropped and reported.
631    fn drop_nonpositive_capacitors(&mut self, doc: &mut Map<String, Value>) {
632        if let Some(Value::Object(capacitors)) = doc.get_mut("capacitor") {
633            let invalid: Vec<String> = capacitors
634                .iter()
635                .filter(|(_, c)| c.get("v_nom").is_some_and(|v| !strictly_positive(v)))
636                .map(|(name, _)| name.clone())
637                .collect();
638            for name in invalid {
639                capacitors.remove(&name);
640                self.warn(
641                    &C::EMIT_BMOPF_RECORD_DROPPED,
642                    format!(
643                        "capacitor {name}: v_nom is not strictly positive, which the BMOPF schema \
644                         requires; dropped from the output"
645                    ),
646                );
647            }
648        }
649    }
650
651    /// The component locations as the `geo` Point of the element each one
652    /// attaches to: a voltage source, load, generator, IBR, shunt, capacitor,
653    /// switch or transformer. A component location is geographic degrees, so
654    /// it is written only into a document whose geometry is WGS84 (no
655    /// `meta.crs`), with both axes stated and a WGS84 datum or none. The rest,
656    /// bus and line points included (their `geo` slots carry the bus location
657    /// and the line route), are reported as dropped. BMOPF `geo` has no datum
658    /// or origin of its own, so a point stating no datum, or an origin other
659    /// than the source data, reads back as WGS84 source coordinates, which is
660    /// reported too.
661    fn component_geometry(&mut self, net: &MulticonductorNetwork, doc: &mut Map<String, Value>) {
662        let locations = net.component_locations();
663        if locations.is_empty() {
664            return;
665        }
666        let document_wgs84 = !self.geometry_embedded
667            || matches!(
668                &super::geo::meta_or_default(net).space,
669                crate::geo::CoordinateSpace::Geographic { crs }
670                    if crs.as_deref().is_none_or(super::geo::is_wgs84)
671            );
672        let (mut dropped, mut restated) = (0usize, 0usize);
673        for location in locations {
674            let point = &location.point;
675            let (Some(latitude), Some(longitude)) = (point.latitude, point.longitude) else {
676                dropped += 1;
677                continue;
678            };
679            if !document_wgs84
680                || point
681                    .datum
682                    .as_deref()
683                    .is_some_and(|d| !super::geo::is_wgs84(d))
684            {
685                dropped += 1;
686                continue;
687            }
688            let Some(element) = super::geo::component_element(doc, location.target, &location.name)
689            else {
690                dropped += 1;
691                continue;
692            };
693            element.insert("geo".into(), super::geo::lon_lat_point(longitude, latitude));
694            if point.datum.is_none()
695                || !matches!(
696                    location.kind,
697                    None | Some(crate::geo::DistCoordsKind::Source)
698                )
699            {
700                restated += 1;
701            }
702        }
703        if dropped > 0 {
704            self.warn(
705                &C::EMIT_DIST_COMPONENT_COORDINATES_DROPPED,
706                format!(
707                    "{dropped} component point(s) dropped: BMOPF carries a component point as \
708                     the WGS84 `geo` Point of a located element, and these state a partial axis \
709                     or another datum, sit in a projected document, or attach to a bus, line or \
710                     element this document does not write under that name"
711                ),
712            );
713        }
714        if restated > 0 {
715            self.warn(
716                &C::EMIT_BMOPF_VALUE_SUBSTITUTED,
717                format!(
718                    "{restated} component point(s) written as `geo` read back as WGS84 source \
719                     coordinates: they state no datum, or an origin other than the source data, \
720                     which BMOPF `geo` cannot carry"
721                ),
722            );
723        }
724    }
725
726    /// The document level geometry record. The geometry travels in the
727    /// typed `bus.*.geo` and `line.*.geo` slots the element writers filled,
728    /// and `meta.crs` names their coordinate system (absent means WGS84); a
729    /// space the schema cannot name, or coordinates not from the source data,
730    /// are also recorded as `extras.powerio_geo` so a read gets the same
731    /// metadata back.
732    fn geometry(
733        &mut self,
734        net: &MulticonductorNetwork,
735        doc: &mut Map<String, Value>,
736        extras: &mut Map<String, Value>,
737    ) {
738        if !self.geometry_embedded {
739            return;
740        }
741        let meta = super::geo::meta_or_default(net);
742        if let Some(crs) = super::geo::declared_crs(&meta)
743            && let Some(Value::Object(m)) = doc.get_mut("meta")
744        {
745            m.insert("crs".into(), json!(crs));
746        }
747        if super::geo::needs_declared_meta(&meta) {
748            extras.insert("powerio_geo".into(), json!(meta));
749        }
750    }
751
752    fn buses(&mut self, net: &MulticonductorNetwork, doc: &mut Map<String, Value>) {
753        let mut buses = Map::new();
754        for b in net.buses() {
755            let mut o = Map::new();
756            o.insert("terminal_names".into(), json!(b.terminals));
757            if !b.grounded.is_empty() {
758                o.insert("perfectly_grounded_terminals".into(), json!(b.grounded));
759            }
760            // Phase to ground bounds: `vpg_min`/`vpg_max` since the revised draft;
761            // The schema rejects the first draft's spelling `v_*`.
762            for (key, scalar, phases) in [
763                ("vpg_min", b.v_min, &b.v_min_phase),
764                ("vpg_max", b.v_max, &b.v_max_phase),
765            ] {
766                if let Some(v) = scalar {
767                    o.insert(
768                        key.into(),
769                        Value::Array(vec![
770                            self.num(v, key);
771                            b.phase_indices(doc.get("terminal_conventions")).len()
772                        ]),
773                    );
774                } else if let Some(values) = phases {
775                    o.insert(key.into(), self.nums(values, key));
776                }
777            }
778            for (key, bound) in [
779                ("vpn_min", &b.vpn_min),
780                ("vpn_max", &b.vpn_max),
781                ("vpp_min", &b.vpp_min),
782                ("vpp_max", &b.vpp_max),
783            ] {
784                if let Some(v) = bound {
785                    o.insert(key.into(), self.nums(v, &format!("bus {key}")));
786                }
787            }
788            for (key, bound) in [
789                ("vpos_min", b.vpos_min),
790                ("vpos_max", b.vpos_max),
791                ("vneg_max", b.vneg_max),
792                ("vzero_max", b.vzero_max),
793                // The neutral to ground cap, `vng_max` since the schema.
794                ("vng_max", b.vn_max),
795            ] {
796                if let Some(v) = bound {
797                    o.insert(key.into(), self.num(v, &format!("bus {key}")));
798                }
799            }
800            self.drop_bounds_the_bus_cannot_carry(b, &mut o, doc.get("terminal_conventions"));
801            self.bus_location(b);
802            if let Some(geo) = super::geo::bus_geo(b) {
803                o.insert("geo".into(), geo);
804                self.geometry_embedded = true;
805            }
806            // Other extras have no bus fields in the schema.
807            self.extras_dropped(&b.extras, &format!("bus {}", b.id));
808            buses.insert(b.id.clone(), Value::Object(o));
809        }
810        doc.insert("bus".into(), Value::Object(buses));
811    }
812
813    fn line_codes(&mut self, net: &MulticonductorNetwork, doc: &mut Map<String, Value>) {
814        if !net.line_codes().is_empty() {
815            let mut codes = Map::new();
816            for c in net.line_codes() {
817                let mut o = Map::new();
818                // The schema requires R_series_1_1 and X_series_1_1; an
819                // empty matrix would drop them and invalidate the output.
820                let dim = c.r_series.len().max(c.x_series.len()).max(1);
821                if c.r_series.is_empty() && c.x_series.is_empty() {
822                    self.warn(
823                        &C::EMIT_BMOPF_VALUE_DEFAULTED,
824                        format!(
825                            "linecode {}: no series matrix; emitted as 1 conductor \
826                         zero impedance",
827                            c.name
828                        ),
829                    );
830                } else if c.r_series.is_empty() || c.x_series.is_empty() {
831                    self.warn(
832                        &C::EMIT_BMOPF_VALUE_DEFAULTED,
833                        format!(
834                            "linecode {}: R_series and X_series sizes disagree; the \
835                         empty one emitted as zeros",
836                            c.name
837                        ),
838                    );
839                }
840                self.required_matrix(&mut o, "R_series", &c.r_series, dim, &c.name);
841                self.required_matrix(&mut o, "X_series", &c.x_series, dim, &c.name);
842                self.flat_matrix(&mut o, "G_from", &c.g_from, &c.name);
843                self.flat_matrix(&mut o, "G_to", &c.g_to, &c.name);
844                self.flat_matrix(&mut o, "B_from", &c.b_from, &c.name);
845                self.flat_matrix(&mut o, "B_to", &c.b_to, &c.name);
846                if let Some(i_max) = &c.i_max
847                    && let Some(v) = self.bounds(i_max, &format!("linecode {} i_max", c.name))
848                {
849                    o.insert("i_max".into(), v);
850                }
851                if let Some(s_max) = &c.s_max
852                    && self.per_conductor(s_max, dim, &format!("linecode {} s_max", c.name))
853                    && let Some(v) = self.bounds(s_max, &format!("linecode {} s_max", c.name))
854                {
855                    o.insert("s_max".into(), v);
856                }
857                if let Some(source) = &c.source {
858                    o.insert("source".into(), json!(source));
859                }
860                self.extras_dropped(&c.extras, &format!("linecode {}", c.name));
861                codes.insert(c.name.clone(), Value::Object(o));
862            }
863            doc.insert("linecode".into(), Value::Object(codes));
864        }
865    }
866
867    fn bus_location(&mut self, b: &crate::model::DistBus) {
868        if let Some(location) = b.location
869            && (!location.x.is_finite() || !location.y.is_finite())
870        {
871            self.diagnostic(
872                &C::EMIT_BMOPF_BUS_LOCATION_DROPPED,
873                format!("bus {}", b.id),
874                format!(
875                    "bus {}: nonfinite location cannot be written to GeoJSON",
876                    b.id
877                ),
878                json!({ "bus": b.id, "x": location.x, "y": location.y })
879                    .as_object()
880                    .expect("object literal")
881                    .clone(),
882            );
883        }
884    }
885
886    fn warn_unemitted_untyped(&mut self, net: &MulticonductorNetwork) {
887        for u in net.untyped_objects() {
888            if Self::is_emitted_untyped(u) {
889                continue;
890            }
891            let message = format!(
892                "{} {}: class is not represented in BMOPF; dropped from the output",
893                u.class, u.name
894            );
895            if u.class == "regcontrol" || u.class == "autotrans" {
896                let mut details = Map::new();
897                details.insert("class".into(), json!(&u.class));
898                details.insert("name".into(), json!(&u.name));
899                let code = if u.class == "regcontrol" {
900                    &C::EMIT_BMOPF_REGCONTROL_DROPPED
901                } else {
902                    &C::EMIT_BMOPF_AUTOTRANSFORMER_DROPPED
903                };
904                self.diagnostic(code, format!("{} {}", u.class, u.name), message, details);
905            } else {
906                self.warn(&C::EMIT_BMOPF_RECORD_DROPPED, message);
907            }
908        }
909    }
910
911    fn is_emitted_untyped(u: &crate::model::UntypedObject) -> bool {
912        RAW_BMOPF_EXTRAS_TABLES.contains(&u.class.as_str()) || u.class.starts_with("transformer.")
913    }
914
915    /// Map PMD load-shape references onto BMOPF's numeric load fields.
916    /// Only profiles whose PMD-only options are at their neutral defaults can
917    /// be represented by BMOPF's multiplicative profile semantics.
918    fn load_time_series_refs(
919        &mut self,
920        extras: &crate::model::Extras,
921        out: &mut Map<String, Value>,
922        what: &str,
923    ) {
924        let Some(value) = extras.get("time_series") else {
925            return;
926        };
927        let Some(refs) = value.as_object() else {
928            self.warn(
929                &C::EMIT_BMOPF_FIELD_DROPPED,
930                format!("{what}: malformed `time_series` references have no BMOPF mapping"),
931            );
932            return;
933        };
934        let mut mapped = Map::new();
935        for (field, value) in refs {
936            let target = match field.as_str() {
937                "pd_nom" | "p_nom" => "p_nom",
938                "qd_nom" | "q_nom" => "q_nom",
939                _ => {
940                    self.warn(
941                        &C::EMIT_BMOPF_FIELD_DROPPED,
942                        format!("{what}: time-series field `{field}` has no BMOPF mapping"),
943                    );
944                    continue;
945                }
946            };
947            let Some(name) = value.as_str() else {
948                self.warn(
949                    &C::EMIT_BMOPF_FIELD_DROPPED,
950                    format!("{what}: time-series reference `{field}` is not a profile name"),
951                );
952                continue;
953            };
954            if !self.time_series_profiles.contains_key(name) {
955                self.warn(
956                    &C::EMIT_BMOPF_FIELD_DROPPED,
957                    format!(
958                        "{what}: time-series profile `{name}` cannot be represented by BMOPF; `{field}` reference dropped"
959                    ),
960                );
961                continue;
962            }
963            mapped.insert(target.to_string(), Value::String(name.to_owned()));
964        }
965        if !mapped.is_empty() {
966            out.insert("time_series".into(), Value::Object(mapped));
967        }
968    }
969
970    fn stash_named_extra(
971        &mut self,
972        extras: &mut Map<String, Value>,
973        table_name: &str,
974        name: &str,
975        value: Value,
976    ) {
977        if extras.get(table_name).is_some_and(|v| !v.is_object()) {
978            self.warn(
979                &C::EMIT_BMOPF_VALUE_SUBSTITUTED,
980                format!(
981                    "extras.`{table_name}` is not a table; replaced to retain time-series metadata"
982                ),
983            );
984            extras.insert(table_name.to_string(), Value::Object(Map::new()));
985        }
986        let collision = extras
987            .get(table_name)
988            .and_then(Value::as_object)
989            .is_some_and(|table| table.contains_key(name));
990        if collision {
991            self.warn(
992                &C::EMIT_BMOPF_VALUE_SUBSTITUTED,
993                format!(
994                    "extras.`{table_name}.{name}` was replaced by retained time-series metadata"
995                ),
996            );
997        }
998        extras
999            .entry(table_name.to_string())
1000            .or_insert_with(|| Value::Object(Map::new()))
1001            .as_object_mut()
1002            .expect("the writer creates a table for retained time-series metadata")
1003            .insert(name.to_string(), value);
1004    }
1005
1006    fn normalize_time_series_for_emit(
1007        &mut self,
1008        name: &str,
1009        value: Value,
1010        extras: &mut Map<String, Value>,
1011    ) -> Value {
1012        let Some((profile, metadata)) = self.time_series_profiles.get(name).cloned() else {
1013            self.warn(
1014                &C::EMIT_BMOPF_RETAINED_SOURCE_ONLY,
1015                format!(
1016                    "time_series {name}: profile is not representable by BMOPF; retained verbatim under extras.time_series"
1017                ),
1018            );
1019            return value;
1020        };
1021        if let Some(metadata) = metadata {
1022            self.stash_named_extra(extras, "pmd_time_series_metadata", name, metadata);
1023        }
1024        profile
1025    }
1026
1027    /// Untyped BMOPF ecosystem objects, one pass: the classes with a
1028    /// top-level table emit there, the rest re-emit under `extras`, and
1029    /// untyped transformer subtypes keep their place under `transformer`.
1030    fn untyped_bmopf_tables(
1031        &mut self,
1032        net: &MulticonductorNetwork,
1033        doc: &mut Map<String, Value>,
1034        extras: &mut Map<String, Value>,
1035    ) {
1036        self.clear_non_table_extras_slots(net, extras);
1037        for u in net.untyped_objects() {
1038            let subtype = u.class.strip_prefix("transformer.");
1039            if !Self::is_emitted_untyped(u) {
1040                continue;
1041            }
1042            let mut unplaced = Vec::new();
1043            let Some(value) = raw_bmopf_value(u, &mut unplaced) else {
1044                self.warn(
1045                    &C::EMIT_BMOPF_RECORD_DROPPED,
1046                    format!(
1047                        "{} {}: the untyped BMOPF object carries no field this writer can \
1048                     place; dropped from the output",
1049                        u.class, u.name
1050                    ),
1051                );
1052                continue;
1053            };
1054            for text in unplaced {
1055                self.diagnostic(
1056                    &C::EMIT_BMOPF_FIELD_DROPPED,
1057                    format!("{} {}", u.class, u.name),
1058                    format!(
1059                        "{} {}: the value `{text}` has no field name; dropped from the \
1060                     output, the named fields beside it are kept",
1061                        u.class, u.name
1062                    ),
1063                    Map::new(),
1064                );
1065            }
1066            // A profile only gets an active BMOPF slot when its complete
1067            // semantics are representable in the schema. Otherwise preserve
1068            // the original profile under extras.time_series.
1069            let top_level = subtype.is_none() && self.raw_object_at_top_level(u);
1070            let value = if u.class == "time_series" && top_level {
1071                self.normalize_time_series_for_emit(&u.name, value, extras)
1072            } else {
1073                if u.class == "time_series" {
1074                    self.warn(
1075                        &C::EMIT_BMOPF_RETAINED_SOURCE_ONLY,
1076                        format!(
1077                            "time_series {}: profile is not representable in the BMOPF schema; retained verbatim under extras.time_series",
1078                            u.name
1079                        ),
1080                    );
1081                }
1082                value
1083            };
1084            // An untyped transformer subtype lands in the top-level
1085            // `transformer` table, not under `extras`. Name the slot the
1086            // object really went to, so a warning points at the part of the
1087            // document a reader must look at.
1088            let slot_path = match subtype {
1089                Some(sub) => format!("transformer.{sub}"),
1090                None if top_level => u.class.clone(),
1091                None => format!("extras.{}", u.class),
1092            };
1093            let slot = match subtype {
1094                Some(sub) => doc
1095                    .entry("transformer")
1096                    .or_insert_with(|| Value::Object(Map::new()))
1097                    .as_object_mut()
1098                    .expect("the writer builds the transformer table as an object")
1099                    .entry(sub.to_string())
1100                    .or_insert_with(|| Value::Object(Map::new())),
1101                None if top_level => doc
1102                    .entry(u.class.clone())
1103                    .or_insert_with(|| Value::Object(Map::new())),
1104                None => extras
1105                    .entry(u.class.clone())
1106                    .or_insert_with(|| Value::Object(Map::new())),
1107            };
1108            // `clear_non_table_extras_slots` makes this hold, and every slot
1109            // the writer creates is a table. The path still runs on untrusted
1110            // input, so a surprise drops the object instead of the process.
1111            let Some(table) = slot.as_object_mut() else {
1112                self.warn(
1113                    &C::EMIT_BMOPF_RECORD_DROPPED,
1114                    format!(
1115                        "{} {}: the `{slot_path}` slot is not a table; dropped from the output",
1116                        u.class, u.name
1117                    ),
1118                );
1119                continue;
1120            };
1121            if table.insert(u.name.clone(), value).is_some() {
1122                self.warn(
1123                    &C::EMIT_BMOPF_VALUE_SUBSTITUTED,
1124                    format!(
1125                        "{} {}: the source `{slot_path}` carried an entry of the same name; \
1126                     the top-level object replaced it",
1127                        u.class, u.name
1128                    ),
1129                );
1130            }
1131        }
1132    }
1133
1134    /// Whether this untyped BMOPF class has a top-level table.
1135    ///
1136    /// The schema declares every class in [`RAW_BMOPF_EXTRAS_TABLES`] except
1137    /// `capacitor`, whose top-level table is strict, so a capacitor too
1138    /// malformed to type has no slot in it and keeps its raw properties under
1139    /// `extras`.
1140    fn raw_table_at_top_level(class: &str) -> bool {
1141        class != "capacitor"
1142    }
1143
1144    /// A raw object is top-level only when the schema declares its
1145    /// table and, for time series, the profile has BMOPF multiplicative
1146    /// semantics and satisfies the schema's required-values constraint.
1147    fn raw_object_at_top_level(&self, object: &crate::model::UntypedObject) -> bool {
1148        if !Self::raw_table_at_top_level(&object.class) {
1149            return false;
1150        }
1151        if object.class != "time_series" {
1152            return true;
1153        }
1154        self.time_series_profiles.contains_key(&object.name)
1155    }
1156
1157    /// `extras` is seeded from the source document's own `extras` object, so
1158    /// a value under one of the relocated table names is input, not something
1159    /// this writer built. A value that is not a table has no slot for a named
1160    /// entry; warn once per name and replace it with an empty table, which
1161    /// the untyped objects of that class then fill.
1162    fn clear_non_table_extras_slots(
1163        &mut self,
1164        net: &MulticonductorNetwork,
1165        extras: &mut Map<String, Value>,
1166    ) {
1167        let classes: BTreeSet<&str> = net
1168            .untyped_objects()
1169            .iter()
1170            .filter(|u| RAW_BMOPF_EXTRAS_TABLES.contains(&u.class.as_str()))
1171            .filter(|u| !self.raw_object_at_top_level(u))
1172            .map(|u| u.class.as_str())
1173            .collect();
1174        for class in classes {
1175            if extras.get(class).is_some_and(|v| !v.is_object()) {
1176                self.warn(
1177                    &C::EMIT_BMOPF_VALUE_SUBSTITUTED,
1178                    format!(
1179                        "extras `{class}`: the source value is not a table; replaced by the \
1180                     top-level `{class}` objects"
1181                    ),
1182                );
1183                extras.insert(class.to_string(), Value::Object(Map::new()));
1184            }
1185        }
1186    }
1187
1188    /// Lines and switches.
1189    fn branches(&mut self, net: &MulticonductorNetwork, doc: &mut Map<String, Value>) {
1190        if !net.lines().is_empty() {
1191            let mut lines = Map::new();
1192            for l in net.lines() {
1193                let mut o = Map::new();
1194                o.insert("length".into(), self.num(l.length, "line length"));
1195                o.insert("linecode".into(), json!(l.linecode));
1196                o.insert("bus_from".into(), json!(l.bus_from));
1197                o.insert("bus_to".into(), json!(l.bus_to));
1198                o.insert("terminal_map_from".into(), json!(l.terminal_map_from));
1199                o.insert("terminal_map_to".into(), json!(l.terminal_map_to));
1200                let what = format!("line {}", l.name);
1201                if let Some(i_max) = &l.i_max
1202                    && let Some(v) = self.bounds(i_max, &format!("{what} i_max"))
1203                {
1204                    o.insert("i_max".into(), v);
1205                }
1206                if let Some(s_max) = &l.s_max
1207                    && self.per_conductor(
1208                        s_max,
1209                        l.terminal_map_from.len(),
1210                        &format!("{what} s_max"),
1211                    )
1212                    && let Some(v) = self.bounds(s_max, &format!("{what} s_max"))
1213                {
1214                    o.insert("s_max".into(), v);
1215                }
1216                if let Some(geo) = super::geo::line_geo(l) {
1217                    o.insert("geo".into(), geo);
1218                    self.geometry_embedded = true;
1219                } else if l.route.is_some() {
1220                    self.warn(
1221                        &C::EMIT_MULTICONDUCTOR_ROUTE_DROPPED,
1222                        format!(
1223                            "{what}: the route has fewer than two finite vertices, so it has no \
1224                             `geo` LineString; dropped"
1225                        ),
1226                    );
1227                }
1228                self.extras_dropped(&l.extras, &what);
1229                lines.insert(l.name.clone(), Value::Object(o));
1230            }
1231            doc.insert("line".into(), Value::Object(lines));
1232        }
1233        if !net.switches().is_empty() {
1234            let mut switches = Map::new();
1235            for s in net.switches() {
1236                let mut o = Map::new();
1237                o.insert("bus_from".into(), json!(s.bus_from));
1238                o.insert("bus_to".into(), json!(s.bus_to));
1239                o.insert("terminal_map_from".into(), json!(s.terminal_map_from));
1240                o.insert("terminal_map_to".into(), json!(s.terminal_map_to));
1241                o.insert("open_switch".into(), json!(s.open));
1242                if let Some(i_max) = &s.i_max
1243                    && let Some(v) = self.bounds(i_max, &format!("switch {} i_max", s.name))
1244                {
1245                    o.insert("i_max".into(), v);
1246                }
1247                self.extras_dropped(&s.extras, &format!("switch {}", s.name));
1248                switches.insert(s.name.clone(), Value::Object(o));
1249            }
1250            doc.insert("switch".into(), Value::Object(switches));
1251        }
1252    }
1253
1254    /// Rated capacitor banks (the schema's `capacitor`), distinct from the
1255    /// raw admittance `shunt` table.
1256    fn capacitors(&mut self, net: &MulticonductorNetwork, doc: &mut Map<String, Value>) {
1257        if net.capacitors().is_empty() {
1258            return;
1259        }
1260        let mut caps = Map::new();
1261        for c in net.capacitors() {
1262            let mut o = Map::new();
1263            o.insert("bus".into(), json!(c.bus));
1264            o.insert("terminal_map".into(), json!(c.terminal_map));
1265            o.insert("configuration".into(), json!(config_str(c.configuration)));
1266            o.insert("q_rated".into(), self.num(c.q_rated, "capacitor q_rated"));
1267            o.insert("v_nom".into(), self.num(c.v_nom, "capacitor v_nom"));
1268            self.extras_dropped(&c.extras, &format!("capacitor {}", c.name));
1269            caps.insert(c.name.clone(), Value::Object(o));
1270        }
1271        doc.insert("capacitor".into(), Value::Object(caps));
1272    }
1273
1274    /// Loads, generators, shunts, and the voltage sources.
1275    fn injections(&mut self, net: &MulticonductorNetwork, doc: &mut Map<String, Value>) {
1276        let mut loads = Map::new();
1277        for l in net.loads() {
1278            let mut o = Map::new();
1279            o.insert("configuration".into(), json!(config_str(l.configuration)));
1280            o.insert("p_nom".into(), self.nums(&l.p_nom, "load p_nom"));
1281            o.insert("q_nom".into(), self.nums(&l.q_nom, "load q_nom"));
1282            o.insert("bus".into(), json!(l.bus));
1283            o.insert("terminal_map".into(), json!(l.terminal_map));
1284            let what = format!("load {}", l.name);
1285            self.load_time_series_refs(&l.extras, &mut o, &what);
1286            self.load_voltage_model(&mut o, &l.voltage_model, &what);
1287            let mut extras = l.extras.clone();
1288            extras.remove("time_series");
1289            self.extras_dropped(&extras, &what);
1290            loads.insert(l.name.clone(), Value::Object(o));
1291        }
1292        let mut gens = Map::new();
1293        for g in net.generators() {
1294            gens.insert(g.name.clone(), self.generator(g));
1295        }
1296        if !loads.is_empty() {
1297            doc.insert("load".into(), Value::Object(loads));
1298        }
1299        if !gens.is_empty() {
1300            doc.insert("generator".into(), Value::Object(gens));
1301        }
1302        if !net.shunts().is_empty() {
1303            let mut shunts = Map::new();
1304            for s in net.shunts() {
1305                let mut o = Map::new();
1306                o.insert("bus".into(), json!(s.bus));
1307                o.insert("terminal_map".into(), json!(s.terminal_map));
1308                // The schema requires G_1_1 and B_1_1.
1309                let dim = s.g.len().max(s.b.len()).max(1);
1310                if s.g.is_empty() && s.b.is_empty() {
1311                    self.warn(
1312                        &C::EMIT_BMOPF_VALUE_DEFAULTED,
1313                        format!(
1314                            "shunt {}: no admittance matrix; emitted as 1 conductor \
1315                         zero admittance",
1316                            s.name
1317                        ),
1318                    );
1319                } else if s.g.is_empty() || s.b.is_empty() {
1320                    self.warn(
1321                        &C::EMIT_BMOPF_VALUE_DEFAULTED,
1322                        format!(
1323                            "shunt {}: G and B sizes disagree; the empty one emitted \
1324                         as zeros",
1325                            s.name
1326                        ),
1327                    );
1328                }
1329                self.required_matrix(&mut o, "G", &s.g, dim, &s.name);
1330                self.required_matrix(&mut o, "B", &s.b, dim, &s.name);
1331                self.extras_dropped(&s.extras, &format!("shunt {}", s.name));
1332                shunts.insert(s.name.clone(), Value::Object(o));
1333            }
1334            doc.insert("shunt".into(), Value::Object(shunts));
1335        }
1336        self.voltage_sources(net, doc);
1337    }
1338
1339    fn voltage_sources(&mut self, net: &MulticonductorNetwork, doc: &mut Map<String, Value>) {
1340        let emitted_sources = bmopf_voltage_sources(net);
1341        let mut sources = Map::new();
1342        if emitted_sources.is_empty() {
1343            self.warn(
1344                &C::EMIT_BMOPF_SOURCE_COUNT,
1345                "network has no voltage source; BMOPF requires exactly one",
1346            );
1347        }
1348        for (i, vs) in emitted_sources.iter().enumerate() {
1349            if i > 0 {
1350                self.warn(
1351                    &C::EMIT_BMOPF_SOURCE_COUNT,
1352                    format!(
1353                        "voltage source {}: the BMOPF formulation expects exactly one source; \
1354                     this network has {}",
1355                        vs.name,
1356                        emitted_sources.len()
1357                    ),
1358                );
1359            }
1360            let mut o = Map::new();
1361            o.insert(
1362                "v_magnitude".into(),
1363                self.nums(&vs.v_magnitude, "voltage_source v_magnitude"),
1364            );
1365            o.insert(
1366                "v_angle".into(),
1367                self.nums(&vs.v_angle, "voltage_source v_angle"),
1368            );
1369            o.insert("bus".into(), json!(&vs.bus));
1370            o.insert("terminal_map".into(), json!(&vs.terminal_map));
1371            let mut extras = vs.extras.clone();
1372            if let Some(rates) = &vs.energy_cost_rate {
1373                o.insert(
1374                    "energy_cost_rate".into(),
1375                    self.nums(rates, "voltage source energy cost rate"),
1376                );
1377                extras.remove("energy_cost_rate");
1378                extras.remove("cost");
1379            }
1380            if let Some(cost) = extras.remove("cost") {
1381                o.insert("cost".into(), cost);
1382            }
1383            self.extras_dropped(&extras, &format!("voltage source {}", vs.name));
1384            for (name, extras) in &vs.dropped_extras {
1385                self.extras_dropped(extras, &format!("voltage source {name}"));
1386            }
1387            sources.insert(vs.name.clone(), Value::Object(o));
1388        }
1389        doc.insert("voltage_source".into(), Value::Object(sources));
1390    }
1391
1392    fn control_profiles(&mut self, net: &MulticonductorNetwork, doc: &mut Map<String, Value>) {
1393        if net.control_profiles().is_empty() {
1394            return;
1395        }
1396        let mut profiles = Map::new();
1397        for profile in net.control_profiles() {
1398            profiles.insert(profile.name.clone(), self.control_profile(profile));
1399        }
1400        doc.insert("control_profile".into(), Value::Object(profiles));
1401    }
1402
1403    fn control_profile(&mut self, profile: &DistControlProfile) -> Value {
1404        let mut o = Map::new();
1405        // The schema enforces the control laws' shapes: 0 < |pf| <= 1,
1406        // four non-decreasing volt-var breakpoints with `q_limits`
1407        // `[q_absorb <= 0, q_inject >= 0]`, and two non-decreasing volt-watt
1408        // breakpoints with `p_limits` `[p_low, p_high]`, both nonnegative. A
1409        // law outside that shape is dropped and reported, not written.
1410        let invalid = |law: &str, why: &str, w: &mut Self| {
1411            w.warn(
1412                &C::EMIT_BMOPF_FIELD_DROPPED,
1413                format!(
1414                    "control_profile {}: {law} {why}, which the BMOPF schema rejects; dropped",
1415                    profile.name
1416                ),
1417            );
1418        };
1419        if let Some(pf) = &profile.power_factor {
1420            if pf.pf.is_finite() && pf.pf != 0.0 && pf.pf.abs() <= 1.0 {
1421                o.insert("power_factor".into(), json!({ "pf": pf.pf }));
1422            } else {
1423                invalid(
1424                    "power_factor",
1425                    &format!("pf {} is not in 0 < |pf| <= 1", pf.pf),
1426                    self,
1427                );
1428            }
1429        }
1430        if let Some(vv) = &profile.volt_var {
1431            let limits = &vv.q_limits;
1432            if vv.voltage_reference.is_none() {
1433                invalid("volt_var", "states no voltage_reference", self);
1434            } else if vv.breakpoints.len() != 4 || !non_decreasing(&vv.breakpoints) {
1435                invalid(
1436                    "volt_var",
1437                    "states other than four non-decreasing breakpoints",
1438                    self,
1439                );
1440            } else if limits.len() != 2 || !(limits[0] <= 0.0 && limits[1] >= 0.0) {
1441                invalid(
1442                    "volt_var",
1443                    "q_limits is not [q_absorb <= 0, q_inject >= 0]",
1444                    self,
1445                );
1446            } else {
1447                o.insert("volt_var".into(), self.volt_var(vv));
1448            }
1449        }
1450        if let Some(vw) = &profile.volt_watt {
1451            let limits = &vw.p_limits;
1452            if vw.voltage_reference.is_none() {
1453                invalid("volt_watt", "states no voltage_reference", self);
1454            } else if vw.breakpoints.len() != 2 || !non_decreasing(&vw.breakpoints) {
1455                invalid(
1456                    "volt_watt",
1457                    "states other than two non-decreasing breakpoints",
1458                    self,
1459                );
1460            } else if limits.len() != 2 || !(0.0 <= limits[0] && limits[0] <= limits[1]) {
1461                invalid(
1462                    "volt_watt",
1463                    "p_limits is not [p_low, p_high] with 0 <= p_low <= p_high",
1464                    self,
1465                );
1466            } else {
1467                o.insert("volt_watt".into(), self.volt_watt(vw));
1468            }
1469        }
1470        for (key, value) in &profile.extras {
1471            if value.is_object() {
1472                o.insert(key.clone(), value.clone());
1473            } else {
1474                self.warn(&C::EMIT_BMOPF_FIELD_DROPPED, format!(
1475                    "control_profile {}: extra `{key}` is not an object; dropped from the output",
1476                    profile.name
1477                ));
1478            }
1479        }
1480        Value::Object(o)
1481    }
1482
1483    fn volt_var(&mut self, vv: &VoltVarControl) -> Value {
1484        let mut o = Map::new();
1485        if let Some(v) = vv.voltage_reference {
1486            o.insert("voltage_reference".into(), json_enum(v));
1487        }
1488        o.insert(
1489            "breakpoints".into(),
1490            self.nums(&vv.breakpoints, "volt_var breakpoints"),
1491        );
1492        o.insert(
1493            "q_limits".into(),
1494            self.nums(&vv.q_limits, "volt_var q_limits"),
1495        );
1496        if let Some(v) = vv.q_unit {
1497            o.insert(
1498                "q_unit".into(),
1499                unit_token(json_enum::<ReactivePowerUnit>(v)),
1500            );
1501        }
1502        if let Some(v) = vv.q_ref {
1503            o.insert("q_ref".into(), json_enum::<ReactivePowerReference>(v));
1504        }
1505        if let Some(v) = vv.p_min_for_q {
1506            o.insert("p_min_for_q".into(), self.num(v, "volt_var p_min_for_q"));
1507        }
1508        if let Some(v) = vv.p_min_for_q_max {
1509            o.insert(
1510                "p_min_for_q_max".into(),
1511                self.num(v, "volt_var p_min_for_q_max"),
1512            );
1513        }
1514        Value::Object(o)
1515    }
1516
1517    fn volt_watt(&mut self, vw: &VoltWattControl) -> Value {
1518        let mut o = Map::new();
1519        if let Some(v) = vw.voltage_reference {
1520            o.insert(
1521                "voltage_reference".into(),
1522                json_enum::<ControlVoltageReference>(v),
1523            );
1524        }
1525        o.insert(
1526            "breakpoints".into(),
1527            self.nums(&vw.breakpoints, "volt_watt breakpoints"),
1528        );
1529        o.insert(
1530            "p_limits".into(),
1531            self.nums(&vw.p_limits, "volt_watt p_limits"),
1532        );
1533        if let Some(v) = vw.p_unit {
1534            o.insert("p_unit".into(), unit_token(json_enum::<ActivePowerUnit>(v)));
1535        }
1536        if let Some(v) = vw.p_ref {
1537            o.insert("p_ref".into(), json_enum::<ActivePowerReference>(v));
1538        }
1539        Value::Object(o)
1540    }
1541
1542    fn ibrs(&mut self, net: &MulticonductorNetwork, doc: &mut Map<String, Value>) {
1543        if net.ibrs().is_empty() {
1544            return;
1545        }
1546        let mut ibrs = Map::new();
1547        for ibr in net.ibrs() {
1548            ibrs.insert(ibr.name.clone(), self.ibr(ibr));
1549        }
1550        doc.insert("ibr".into(), Value::Object(ibrs));
1551    }
1552
1553    fn ibr(&mut self, ibr: &DistIbr) -> Value {
1554        let mut o = Map::new();
1555        o.insert("bus".into(), json!(ibr.bus));
1556        o.insert("terminal_map".into(), json!(ibr.terminal_map));
1557        o.insert("topology".into(), json_enum(ibr.topology));
1558        if ibr.prime_mover == crate::model::IbrPrimeMover::Dstatcom {
1559            // The schema removed DSTATCOM, a synonym of STATCOM.
1560            self.warn(
1561                &C::EMIT_BMOPF_VALUE_SUBSTITUTED,
1562                format!(
1563                    "ibr {}: prime_mover DSTATCOM is written as STATCOM, the one spelling the \
1564                     BMOPF schema keeps for it",
1565                    ibr.name
1566                ),
1567            );
1568            o.insert("prime_mover".into(), json!("STATCOM"));
1569        } else {
1570            o.insert("prime_mover".into(), json_enum(ibr.prime_mover));
1571        }
1572        o.insert("s_max".into(), self.nums(&ibr.s_max, "ibr s_max"));
1573        if let Some(v) = &ibr.i_max {
1574            o.insert("i_max".into(), self.nums(v, "ibr i_max"));
1575        }
1576        if let Some(v) = ibr.p_avail {
1577            o.insert("p_avail".into(), self.num(v, "ibr p_avail"));
1578        }
1579        if let Some(v) = &ibr.p_min {
1580            o.insert("p_min".into(), self.nums(v, "ibr p_min"));
1581        }
1582        if let Some(v) = &ibr.p_max {
1583            o.insert("p_max".into(), self.nums(v, "ibr p_max"));
1584        }
1585        if let Some(v) = &ibr.q_min {
1586            o.insert("q_min".into(), self.nums(v, "ibr q_min"));
1587        }
1588        if let Some(v) = &ibr.q_max {
1589            o.insert("q_max".into(), self.nums(v, "ibr q_max"));
1590        }
1591        if let Some(v) = &ibr.control_profile {
1592            o.insert("control_profile".into(), json!(v));
1593        }
1594        if let Some(v) = ibr.voltage_aggregation {
1595            o.insert("voltage_aggregation".into(), json_enum(v));
1596        }
1597        for (key, value) in &ibr.extras {
1598            if key == "dc_control"
1599                && let Some(mode) = value.as_str()
1600                && matches!(mode.to_ascii_uppercase().as_str(), "P" | "V" | "DROOP")
1601            {
1602                // The schema spells every enum UPPER_SNAKE (was `droop`).
1603                o.insert(key.clone(), json!(mode.to_ascii_uppercase()));
1604            } else if IBR_EXTRA_FIELDS.contains(&key.as_str()) {
1605                o.insert(key.clone(), value.clone());
1606            } else {
1607                self.warn(&C::EMIT_BMOPF_FIELD_DROPPED, format!(
1608                    "ibr {}: extra `{key}` has no place in the BMOPF schema; dropped from the output",
1609                    ibr.name
1610                ));
1611            }
1612        }
1613        // The schema requires `dc_terminal_map` beside `dc_bus`: without it
1614        // the DC coupling names no DC terminals, so it cannot be written.
1615        if o.contains_key("dc_bus") && !o.contains_key("dc_terminal_map") {
1616            o.remove("dc_bus");
1617            self.warn(
1618                &C::EMIT_BMOPF_FIELD_DROPPED,
1619                format!(
1620                    "ibr {}: `dc_bus` states no `dc_terminal_map`, which the BMOPF schema \
1621                     requires beside it; `dc_bus` dropped from the output",
1622                    ibr.name
1623                ),
1624            );
1625        }
1626        Value::Object(o)
1627    }
1628
1629    fn load_voltage_model(
1630        &mut self,
1631        o: &mut Map<String, Value>,
1632        model: &DistLoadVoltageModel,
1633        what: &str,
1634    ) {
1635        match model {
1636            DistLoadVoltageModel::BoundedZip { .. }
1637            | DistLoadVoltageModel::BoundedExponential { .. }
1638            | DistLoadVoltageModel::BoundedConstantPower { .. } => {
1639                self.warn(&C::EMIT_BMOPF_VALUE_SUBSTITUTED, format!("{what}: voltage-band transitions, current limits and dropout have no BMOPF load-law field; emitted the nominal law"));
1640                self.load_voltage_model(o, &model.without_voltage_bounds(), what);
1641            }
1642
1643            DistLoadVoltageModel::ConstantPower { v_nom } => {
1644                o.insert("model".into(), json!("CONSTANT_POWER"));
1645                if !v_nom.is_empty() {
1646                    o.insert("v_nom".into(), self.nums(v_nom, &format!("{what} v_nom")));
1647                }
1648            }
1649            DistLoadVoltageModel::ConstantCurrent { v_nom } => {
1650                o.insert("model".into(), json!("CONSTANT_CURRENT"));
1651                o.insert("v_nom".into(), self.nums(v_nom, &format!("{what} v_nom")));
1652            }
1653            DistLoadVoltageModel::ConstantImpedance { v_nom } => {
1654                o.insert("model".into(), json!("CONSTANT_IMPEDANCE"));
1655                o.insert("v_nom".into(), self.nums(v_nom, &format!("{what} v_nom")));
1656            }
1657            DistLoadVoltageModel::Zip {
1658                v_nom,
1659                alpha_z,
1660                alpha_i,
1661                alpha_p,
1662                beta_z,
1663                beta_i,
1664                beta_p,
1665            } => {
1666                o.insert("model".into(), json!("ZIP"));
1667                o.insert("v_nom".into(), self.nums(v_nom, &format!("{what} v_nom")));
1668                o.insert(
1669                    "alpha_z".into(),
1670                    self.nums(alpha_z, &format!("{what} alpha_z")),
1671                );
1672                o.insert(
1673                    "alpha_i".into(),
1674                    self.nums(alpha_i, &format!("{what} alpha_i")),
1675                );
1676                o.insert(
1677                    "alpha_p".into(),
1678                    self.nums(alpha_p, &format!("{what} alpha_p")),
1679                );
1680                o.insert(
1681                    "beta_z".into(),
1682                    self.nums(beta_z, &format!("{what} beta_z")),
1683                );
1684                o.insert(
1685                    "beta_i".into(),
1686                    self.nums(beta_i, &format!("{what} beta_i")),
1687                );
1688                o.insert(
1689                    "beta_p".into(),
1690                    self.nums(beta_p, &format!("{what} beta_p")),
1691                );
1692            }
1693            DistLoadVoltageModel::Exponential {
1694                v_nom,
1695                gamma_p,
1696                gamma_q,
1697            } => {
1698                o.insert("model".into(), json!("EXPONENTIAL"));
1699                o.insert("v_nom".into(), self.nums(v_nom, &format!("{what} v_nom")));
1700                o.insert(
1701                    "gamma_p".into(),
1702                    self.nums(gamma_p, &format!("{what} gamma_p")),
1703                );
1704                o.insert(
1705                    "gamma_q".into(),
1706                    self.nums(gamma_q, &format!("{what} gamma_q")),
1707                );
1708            }
1709        }
1710    }
1711
1712    fn generator(&mut self, g: &DistGenerator) -> Value {
1713        let mut o = Map::new();
1714        // BMOPF generators carry bounds and cost, no dispatch setpoint: a
1715        // fixed injection becomes pinned bounds. Explicit source bounds win
1716        // over the setpoint, which then has nowhere to go.
1717        let what = format!("generator {}", g.name);
1718        for (key_lo, key_hi, lo, hi, nom) in [
1719            ("p_min", "p_max", &g.p_min, &g.p_max, &g.p_nom),
1720            ("q_min", "q_max", &g.q_min, &g.q_max, &g.q_nom),
1721        ] {
1722            if lo.is_some() || hi.is_some() {
1723                // Pinned bounds ARE the setpoint; only a setpoint that
1724                // differs from the bounds has nowhere to go.
1725                let pinned = lo.as_deref() == Some(nom) && hi.as_deref() == Some(nom);
1726                if !nom.is_empty() && !nom.iter().all(|&v| v == 0.0) && !pinned {
1727                    self.diagnostic(
1728                        &C::EMIT_BMOPF_FIELD_DROPPED,
1729                        what.clone(),
1730                        format!(
1731                            "{what}: explicit {key_lo}/{key_hi} bounds win over the setpoint, \
1732                         which has no BMOPF field"
1733                        ),
1734                        Map::new(),
1735                    );
1736                }
1737                if let Some(v) = lo
1738                    && let Some(v) = self.bounds(v, &format!("{what} {key_lo}"))
1739                {
1740                    o.insert(key_lo.into(), v);
1741                }
1742                if let Some(v) = hi
1743                    && let Some(v) = self.bounds(v, &format!("{what} {key_hi}"))
1744                {
1745                    o.insert(key_hi.into(), v);
1746                }
1747            } else if !nom.is_empty() {
1748                // A fixed injection becomes pinned bounds.
1749                o.insert(key_lo.into(), self.nums(nom, key_lo));
1750                o.insert(key_hi.into(), self.nums(nom, key_hi));
1751            }
1752        }
1753        // BMOPF generation cost is per phase conductor. The model stores the
1754        // stated array exactly; a one-entry statement broadcasts to the
1755        // phase count, and an absent cost defaults to zero with a warning.
1756        let n_phase = if g.p_nom.is_empty() {
1757            g.terminal_map.len().max(1)
1758        } else {
1759            g.p_nom.len()
1760        };
1761        let cost = match &g.cost {
1762            Some(stated) if stated.len() == 1 => vec![stated[0]; n_phase],
1763            Some(stated) => {
1764                if stated.len() != n_phase {
1765                    self.warnings.push(
1766                        &C::EMIT_BMOPF_VALUE_SUBSTITUTED,
1767                        format!(
1768                            "{what}: cost states {} entries for {n_phase} phases; \
1769                             emitted as stated",
1770                            stated.len()
1771                        ),
1772                    );
1773                }
1774                stated.clone()
1775            }
1776            None => {
1777                self.warnings.push(
1778                    &C::EMIT_BMOPF_VALUE_DEFAULTED,
1779                    format!("{what}: no generation cost in the source; emitted cost 0"),
1780                );
1781                vec![0.0; n_phase]
1782            }
1783        };
1784        o.insert("cost".into(), self.nums(&cost, "generator cost"));
1785        if let Some(s_max) = &g.s_max
1786            && let Some(v) = self.bounds(s_max, &format!("{what} s_max"))
1787        {
1788            o.insert("s_max".into(), v);
1789        }
1790        if let Some(i_max) = &g.i_max
1791            && let Some(v) = self.bounds(i_max, &format!("{what} i_max"))
1792        {
1793            o.insert("i_max".into(), v);
1794        }
1795        o.insert("bus".into(), json!(g.bus));
1796        o.insert("configuration".into(), json!(config_str(g.configuration)));
1797        o.insert("terminal_map".into(), json!(g.terminal_map));
1798        if g.configuration == Configuration::Delta {
1799            self.warn(
1800                &C::EMIT_BMOPF_VALUE_SUBSTITUTED,
1801                format!(
1802                    "{what}: the BMOPF formulation covers WYE generators; DELTA emitted as written"
1803                ),
1804            );
1805        }
1806        self.extras_dropped(&g.extras, &what);
1807        Value::Object(o)
1808    }
1809
1810    /// Transformers keyed by subtype; wye-wye three phase units decompose
1811    /// into one single_phase entry per phase, the convention the public
1812    /// example networks use.
1813    fn transformers(&mut self, net: &MulticonductorNetwork) -> Map<String, Value> {
1814        let mut by_subtype: Map<String, Value> = Map::new();
1815        let insert = |sub: &str, name: String, v: Value, map: &mut Map<String, Value>| {
1816            map.entry(sub.to_string())
1817                .or_insert_with(|| Value::Object(Map::new()))
1818                .as_object_mut()
1819                .expect("subtype maps are objects")
1820                .insert(name, v);
1821        };
1822        let merged = self.open_delta_pairs(net, &mut by_subtype);
1823        for t in net.transformers() {
1824            if merged.contains(&t.name) {
1825                continue;
1826            }
1827            self.warn_nonuniform_per_phase_taps(t);
1828            match classify(t) {
1829                Kind::SinglePhase => {
1830                    if t.windings.iter().any(|w| w.conn == DistWindingConn::Delta) {
1831                        // An open wye / open delta leg. The single_phase shape
1832                        // carries the terminals and impedance faithfully, but
1833                        // has no field for the wye/delta connection, so a
1834                        // consumer that models the subtype literally reads it
1835                        // as a wye-wye unit. Flag it; the line to line topology
1836                        // survives in the terminal map.
1837                        let connection = match (t.windings[0].conn, t.windings[1].conn) {
1838                            (DistWindingConn::Wye, DistWindingConn::Delta) => "wye/delta",
1839                            (DistWindingConn::Delta, DistWindingConn::Wye) => "delta/wye",
1840                            _ => "delta",
1841                        };
1842                        let mut details = Map::new();
1843                        details.insert("connection".into(), json!(connection));
1844                        details.insert("emitted_subtype".into(), json!("single_phase"));
1845                        self.transformer_diagnostic(
1846                            t,
1847                            &C::EMIT_BMOPF_TRANSFORMER_CONNECTION_LOSSY,
1848                            format!(
1849                                "transformer {}: single phase wye/delta emitted as single_phase; \
1850                                 the wye/delta connection is not encoded in the subtype, only the \
1851                                 line to line terminal map",
1852                                t.name
1853                            ),
1854                            details,
1855                        );
1856                    }
1857                    let v = self.two_winding(t, &t.windings[0], &t.windings[1], 1.0, true, true);
1858                    insert("single_phase", t.name.clone(), v, &mut by_subtype);
1859                }
1860                Kind::SinglePhaseShape(sub) => {
1861                    let v = self.two_winding(t, &t.windings[0], &t.windings[1], 1.0, true, true);
1862                    insert(sub, t.name.clone(), v, &mut by_subtype);
1863                }
1864                kind @ (Kind::Autotransformer | Kind::OpenDeltaLeg) => {
1865                    // A lone Kind::OpenDeltaLeg is a leg whose partner is
1866                    // missing or no longer identical: still a single phase
1867                    // autotransformer on its own.
1868                    if matches!(kind, Kind::OpenDeltaLeg) {
1869                        self.warn_unpaired_open_delta_leg(t);
1870                    }
1871                    let v = self.autotransformer(t);
1872                    insert(
1873                        "single_phase_autotransformer",
1874                        t.name.clone(),
1875                        v,
1876                        &mut by_subtype,
1877                    );
1878                }
1879                Kind::CenterTap => {
1880                    let v = self.center_tap(t);
1881                    insert("center_tap", t.name.clone(), v, &mut by_subtype);
1882                }
1883                Kind::WyeDelta => {
1884                    let v = self.three_phase(t, 0);
1885                    insert("wye_delta", t.name.clone(), v, &mut by_subtype);
1886                }
1887                Kind::DeltaWye => {
1888                    let v = self.three_phase(t, 1);
1889                    insert("delta_wye", t.name.clone(), v, &mut by_subtype);
1890                }
1891                Kind::WyeWye3 => {
1892                    for (k, v) in self.decompose_wye_wye(t) {
1893                        insert("single_phase", k, v, &mut by_subtype);
1894                    }
1895                }
1896                Kind::NWinding => {
1897                    let v = self.n_winding(t);
1898                    insert("n_winding", t.name.clone(), v, &mut by_subtype);
1899                }
1900                Kind::Unsupported(why) => {
1901                    let mut details = Map::new();
1902                    details.insert("reason".into(), json!(&why));
1903                    details.insert("phases".into(), json!(t.phases));
1904                    details.insert("windings".into(), json!(t.windings.len()));
1905                    self.transformer_diagnostic(
1906                        t,
1907                        &C::EMIT_BMOPF_TRANSFORMER_UNSUPPORTED,
1908                        format!(
1909                            "transformer {}: {why}; not representable in the BMOPF transformer \
1910                             subtypes, dropped from the output",
1911                            t.name
1912                        ),
1913                        details,
1914                    );
1915                }
1916            }
1917        }
1918        rename_tap_fields(&mut by_subtype);
1919        rename_regulator_ratio_fields(&mut by_subtype);
1920        by_subtype
1921    }
1922
1923    fn warn_unpaired_open_delta_leg(&mut self, t: &DistTransformer) {
1924        self.transformer_diagnostic(
1925            t,
1926            &C::EMIT_BMOPF_VALUE_SUBSTITUTED,
1927            format!(
1928                "transformer {}: open delta leg has no matching partner leg; \
1929                 emitted as single_phase_autotransformer",
1930                t.name
1931            ),
1932            Map::new(),
1933        );
1934    }
1935
1936    /// Merges classified open delta leg pairs into single
1937    /// `open_delta_regulator` objects and returns the merged transformer
1938    /// names. Legs are paired by shared bus pair; the pair must spell one of
1939    /// the three connections and stay electrically identical, else each leg
1940    /// falls back to `single_phase_autotransformer` in the main loop.
1941    fn open_delta_pairs(
1942        &mut self,
1943        net: &MulticonductorNetwork,
1944        by_subtype: &mut Map<String, Value>,
1945    ) -> BTreeSet<String> {
1946        let mut merged = BTreeSet::new();
1947        let mut groups: BTreeMap<(String, String), Vec<&DistTransformer>> = BTreeMap::new();
1948        for t in net.transformers() {
1949            if !matches!(classify(t), Kind::OpenDeltaLeg) {
1950                continue;
1951            }
1952            let key = (
1953                t.windings[0].bus.to_ascii_lowercase(),
1954                t.windings[1].bus.to_ascii_lowercase(),
1955            );
1956            groups.entry(key).or_default().push(t);
1957        }
1958        for legs in groups.into_values() {
1959            let [a, b] = legs[..] else { continue };
1960            let pair = |t: &DistTransformer| {
1961                if let Some(meta) = t.extras.get("bmopf_open_delta") {
1962                    let pairs = match meta["connection"].as_str()? {
1963                        "ABBC" => [(1, 2), (2, 3)],
1964                        "BCAC" => [(2, 3), (1, 3)],
1965                        "CABA" => [(3, 1), (2, 1)],
1966                        _ => return None,
1967                    };
1968                    let pair = *pairs.get(usize::try_from(meta["leg"].as_u64()?).ok()?)?;
1969                    for (winding, key) in t.windings.iter().zip(["from", "to"]) {
1970                        let map = meta[key].as_array()?;
1971                        let expected = [
1972                            map.get(pair.0 - 1)?.as_str()?,
1973                            map.get(pair.1 - 1)?.as_str()?,
1974                        ];
1975                        if winding.terminal_map.iter().map(String::as_str).ne(expected) {
1976                            return None;
1977                        }
1978                    }
1979                    Some((u8::try_from(pair.0).ok()?, u8::try_from(pair.1).ok()?))
1980                } else {
1981                    winding_phase_pair(&t.windings[0])
1982                }
1983            };
1984            let (Some(pa), Some(pb)) = (pair(a), pair(b)) else {
1985                continue;
1986            };
1987            let Some((connection, swapped)) = open_delta_connection(pa, pb) else {
1988                continue;
1989            };
1990            let metadata_agrees = match (
1991                a.extras.get("bmopf_open_delta"),
1992                b.extras.get("bmopf_open_delta"),
1993            ) {
1994                (Some(a), Some(b)) => ["from", "to", "connection"]
1995                    .iter()
1996                    .all(|key| a[*key] == b[*key]),
1997                (None, None) => true,
1998                _ => false,
1999            };
2000            if !metadata_agrees || !open_delta_pairable(a, b) {
2001                continue;
2002            }
2003            let (first, second) = if swapped { (b, a) } else { (a, b) };
2004            self.warn_nonuniform_per_phase_taps(first);
2005            self.warn_nonuniform_per_phase_taps(second);
2006            let mut details = Map::new();
2007            details.insert("merged_leg".into(), json!(&second.name));
2008            details.insert("connection".into(), json!(connection));
2009            self.transformer_diagnostic(
2010                first,
2011                &C::EMIT_BMOPF_TRANSFORMER_OPEN_DELTA_MERGED,
2012                format!(
2013                    "transformer {}: legs {} and {} emitted as one open_delta_regulator \
2014                     `{}` (connection {connection})",
2015                    first.name, first.name, second.name, first.name
2016                ),
2017                details,
2018            );
2019            let v = self.open_delta_regulator(first, second, connection);
2020            by_subtype
2021                .entry("open_delta_regulator".to_string())
2022                .or_insert_with(|| Value::Object(Map::new()))
2023                .as_object_mut()
2024                .expect("subtype maps are objects")
2025                .insert(first.name.clone(), v);
2026            merged.insert(first.name.clone());
2027            merged.insert(second.name.clone());
2028        }
2029        merged
2030    }
2031
2032    /// The `single_phase_autotransformer` shape of the BMOPFTools schema
2033    /// extension: a step voltage regulator as series plus common winding.
2034    /// No `v_nom` fields; the ratio is `tap_ratio` (regulated over source).
2035    fn autotransformer(&mut self, t: &DistTransformer) -> Value {
2036        let from = &t.windings[0];
2037        let to = &t.windings[1];
2038        let mut o = self.regulator_fields(t, from, to);
2039        o.insert("terminal_map_from".into(), json!(from.terminal_map));
2040        o.insert("terminal_map_to".into(), json!(to.terminal_map));
2041        if let Some(ratio) = self.regulator_tap_ratio(t, from, to)
2042            && (ratio - 1.0).abs() > 1e-12
2043        {
2044            o.insert("tap_ratio".into(), self.num(ratio, "transformer tap_ratio"));
2045        }
2046        for key in REGULATOR_EXTENSION_EXTRAS {
2047            if let Some(v) = t.extras.get(key) {
2048                o.insert(key.into(), v.clone());
2049            }
2050        }
2051        self.warn_unrepresented_neutral_fields(t, "single_phase_autotransformer");
2052        self.transformer_extras_dropped(t, &regulator_allowed_extras());
2053        o.into()
2054    }
2055
2056    /// The `open_delta_regulator` shape of the BMOPFTools schema extension:
2057    /// two identical line to line regulating legs stated once, with the
2058    /// phase pairing carried by `connection` and per leg `tap_ratio` entries.
2059    fn open_delta_regulator(
2060        &mut self,
2061        first: &DistTransformer,
2062        second: &DistTransformer,
2063        connection: &'static str,
2064    ) -> Value {
2065        let from = &first.windings[0];
2066        let to = &first.windings[1];
2067        let mut o = self.regulator_fields(first, from, to);
2068        // The pairing check pins the legs to phases {1, 2, 3}; the object
2069        // spans the whole phase set on both sides.
2070        let meta = first.extras.get("bmopf_open_delta");
2071        o.insert(
2072            "terminal_map_from".into(),
2073            meta.and_then(|v| v.get("from"))
2074                .cloned()
2075                .unwrap_or_else(|| json!(["1", "2", "3"])),
2076        );
2077        o.insert(
2078            "terminal_map_to".into(),
2079            meta.and_then(|v| v.get("to"))
2080                .cloned()
2081                .unwrap_or_else(|| json!(["1", "2", "3"])),
2082        );
2083        o.insert("connection".into(), json!(connection));
2084        let a1 = self.regulator_tap_ratio(first, from, to);
2085        let a2 = self.regulator_tap_ratio(second, &second.windings[0], &second.windings[1]);
2086        if let (Some(a1), Some(a2)) = (a1, a2)
2087            && ((a1 - 1.0).abs() > 1e-12 || (a2 - 1.0).abs() > 1e-12)
2088        {
2089            o.insert(
2090                "tap_ratio".into(),
2091                self.nums(&[a1, a2], "transformer tap_ratio"),
2092            );
2093        }
2094        for key in REGULATOR_EXTENSION_EXTRAS {
2095            if let Some(v) = first.extras.get(key) {
2096                o.insert(key.into(), v.clone());
2097            }
2098        }
2099        for t in [first, second] {
2100            self.warn_unrepresented_neutral_fields(t, "open_delta_regulator");
2101            self.transformer_extras_dropped(t, &regulator_allowed_extras());
2102        }
2103        o.into()
2104    }
2105
2106    /// The fields the two regulator subtypes share: buses, rating, and the
2107    /// series impedance in referred ohms, leakage on the from side.
2108    fn regulator_fields(
2109        &mut self,
2110        t: &DistTransformer,
2111        from: &DistWinding,
2112        to: &DistWinding,
2113    ) -> Map<String, Value> {
2114        let s = from.s_rating;
2115        let zb_from = base_impedance(from.v_ref, s);
2116        let zb_to = base_impedance(to.v_ref, s);
2117        let mut o = Map::new();
2118        o.insert("bus_from".into(), json!(from.bus));
2119        o.insert("bus_to".into(), json!(to.bus));
2120        o.insert("s_rating".into(), self.num(s, "transformer s_rating"));
2121        // A network read from BMOPF stashed the stated ohm fields verbatim
2122        // (the g_no_load pattern), including which of them the source stated
2123        // at all; prefer those so a round trip reproduces the object exactly.
2124        let stated = [
2125            "r_series_from",
2126            "r_series_to",
2127            "x_series_from",
2128            "x_series_to",
2129        ]
2130        .iter()
2131        .any(|key| t.extras.contains_key(*key));
2132        if stated {
2133            for key in [
2134                "r_series_from",
2135                "r_series_to",
2136                "x_series_from",
2137                "x_series_to",
2138            ] {
2139                if let Some(v) = t.extras.get(key) {
2140                    o.insert(key.into(), v.clone());
2141                }
2142            }
2143        } else {
2144            self.referred_ohms(&mut o, "r_series_from", from.r_pct, zb_from, t, "from");
2145            self.referred_ohms(&mut o, "r_series_to", to.r_pct, zb_to, t, "to");
2146            if t.xsc_pct.is_empty() {
2147                self.transformer_diagnostic(
2148                    t,
2149                    &C::EMIT_BMOPF_TRANSFORMER_MISSING_XSC,
2150                    format!(
2151                        "transformer {}: xsc_pct is empty; emitted x_series_from=0",
2152                        t.name
2153                    ),
2154                    Map::new(),
2155                );
2156            }
2157            let xhl = t.xsc_pct.first().copied().unwrap_or(0.0);
2158            self.referred_ohms(&mut o, "x_series_from", xhl, zb_from, t, "from");
2159            o.insert("x_series_to".into(), json!(0.0));
2160        }
2161        self.transformer_no_load_fields(&mut o, t, from, s);
2162        o
2163    }
2164
2165    /// The regulation ratio (regulated over source): the to side tap over
2166    /// the from side tap. `None` (with a warning) when the taps cannot form
2167    /// a nonnegative finite ratio.
2168    fn regulator_tap_ratio(
2169        &mut self,
2170        t: &DistTransformer,
2171        from: &DistWinding,
2172        to: &DistWinding,
2173    ) -> Option<f64> {
2174        let ratio = to.tap / from.tap;
2175        if ratio.is_finite() && ratio >= 0.0 {
2176            return Some(ratio);
2177        }
2178        let mut details = Map::new();
2179        details.insert("from_tap".into(), json!(from.tap));
2180        details.insert("to_tap".into(), json!(to.tap));
2181        self.transformer_diagnostic(
2182            t,
2183            &C::EMIT_BMOPF_TRANSFORMER_TAP_DROPPED,
2184            format!(
2185                "transformer {}: taps ({}, {}) cannot form a nonnegative finite \
2186                 BMOPF tap_ratio; dropped",
2187                t.name, from.tap, to.tap
2188            ),
2189            details,
2190        );
2191        None
2192    }
2193
2194    /// Shared single_phase / center_tap shape. `to_scale` rescales the to
2195    /// side ratings (used by the wye-wye decomposition).
2196    fn two_winding(
2197        &mut self,
2198        t: &DistTransformer,
2199        from: &DistWinding,
2200        to: &DistWinding,
2201        s_scale: f64,
2202        emit_no_load: bool,
2203        warn_extras: bool,
2204    ) -> Value {
2205        let s = from.s_rating * s_scale;
2206        let zb_from = base_impedance(from.v_ref, s);
2207        let zb_to = base_impedance(to.v_ref, s);
2208        let mut o = Map::new();
2209        o.insert("bus_from".into(), json!(from.bus));
2210        o.insert("bus_to".into(), json!(to.bus));
2211        o.insert("s_rating".into(), self.num(s, "transformer s_rating"));
2212        o.insert(
2213            "v_nom_from".into(),
2214            self.num(from.v_ref, "transformer v_nom_from"),
2215        );
2216        o.insert(
2217            "v_nom_to".into(),
2218            self.num(to.v_ref, "transformer v_nom_to"),
2219        );
2220        self.referred_ohms(&mut o, "r_series_from", from.r_pct, zb_from, t, "from");
2221        self.referred_ohms(&mut o, "r_series_to", to.r_pct, zb_to, t, "to");
2222        // The whole leakage reactance rides on the from side, the
2223        // convention the public example uses.
2224        if t.xsc_pct.is_empty() {
2225            self.transformer_diagnostic(
2226                t,
2227                &C::EMIT_BMOPF_TRANSFORMER_MISSING_XSC,
2228                format!(
2229                    "transformer {}: xsc_pct is empty; emitted x_series_from=0",
2230                    t.name
2231                ),
2232                Map::new(),
2233            );
2234        }
2235        let xhl = t.xsc_pct.first().copied().unwrap_or(0.0);
2236        self.referred_ohms(&mut o, "x_series_from", xhl, zb_from, t, "from");
2237        o.insert("x_series_to".into(), json!(0.0));
2238        o.insert("terminal_map_from".into(), json!(from.terminal_map));
2239        o.insert("terminal_map_to".into(), json!(to.terminal_map));
2240        self.transformer_neutral_fields(&mut o, t, from, to);
2241        self.transformer_tap_fields(&mut o, t, from, to);
2242        if emit_no_load {
2243            self.transformer_no_load_fields(&mut o, t, from, s);
2244        }
2245        if warn_extras {
2246            self.transformer_extras_dropped(t, &TRANSFORMER_TWO_WINDING_ALLOWED_EXTRAS);
2247        }
2248        o.into()
2249    }
2250
2251    fn center_tap(&mut self, t: &DistTransformer) -> Value {
2252        let from = &t.windings[0];
2253        let (w2, w3) = (&t.windings[1], &t.windings[2]);
2254        let common = center_tap_common_terminal(w2, w3);
2255        let r_neutral = self.center_tap_neutral(t, "r_neutral", w2.r_neutral, w3.r_neutral);
2256        let x_neutral = self.center_tap_neutral(t, "x_neutral", w2.x_neutral, w3.x_neutral);
2257        if (w2.tap - w3.tap).abs() > 1e-9 {
2258            let mut details = Map::new();
2259            details.insert("from_tap".into(), json!(from.tap));
2260            details.insert("secondary_taps".into(), json!([w2.tap, w3.tap]));
2261            details.insert("emitted_secondary_tap".into(), json!(w2.tap));
2262            self.transformer_diagnostic(
2263                t,
2264                &C::EMIT_BMOPF_TRANSFORMER_CENTER_TAP_TAP_COLLAPSED,
2265                format!(
2266                    "transformer {}: center tap secondary half winding taps ({}, {}) differ; emitted the first half tap",
2267                    t.name, w2.tap, w3.tap
2268                ),
2269                details,
2270            );
2271        }
2272        let to = center_tap_to_winding(w2, w3, &common, from.s_rating, r_neutral, x_neutral);
2273        if w2.s_rating.to_bits() != from.s_rating.to_bits()
2274            || w3.s_rating.to_bits() != from.s_rating.to_bits()
2275        {
2276            let mut details = Map::new();
2277            details.insert("from_s_rating".into(), json!(from.s_rating));
2278            details.insert("half_s_ratings".into(), json!([w2.s_rating, w3.s_rating]));
2279            self.transformer_diagnostic(
2280                t,
2281                &C::EMIT_BMOPF_TRANSFORMER_CENTER_TAP_RATING_COLLAPSED,
2282                format!(
2283                    "transformer {}: center tap half winding s_ratings ({}, {}) differ \
2284                     from the primary's {}; BMOPF carries one transformer rating, and \
2285                     the first secondary half rating is used for the to-side impedance base",
2286                    t.name, w2.s_rating, w3.s_rating, from.s_rating
2287                ),
2288                details,
2289            );
2290        }
2291        let s = from.s_rating;
2292        let zb_from = winding_base(from);
2293        let zb_to = winding_base(w2);
2294        if t.xsc_pct.is_empty() {
2295            self.transformer_diagnostic(
2296                t,
2297                &C::EMIT_BMOPF_TRANSFORMER_MISSING_XSC,
2298                format!(
2299                    "transformer {}: xsc_pct is empty; emitted x_series_from=0",
2300                    t.name
2301                ),
2302                Map::new(),
2303            );
2304        }
2305        let (x_from_pct, x_to_pct) = self.center_tap_leakage_percentages(t);
2306
2307        let mut o = Map::new();
2308        o.insert("bus_from".into(), json!(from.bus));
2309        o.insert("bus_to".into(), json!(to.bus));
2310        o.insert("s_rating".into(), self.num(s, "transformer s_rating"));
2311        o.insert(
2312            "v_nom_from".into(),
2313            self.num(from.v_ref, "transformer v_nom_from"),
2314        );
2315        o.insert(
2316            "v_nom_to".into(),
2317            self.num(to.v_ref, "transformer v_nom_to"),
2318        );
2319        self.referred_ohms(&mut o, "r_series_from", from.r_pct, zb_from, t, "from");
2320        self.referred_ohms(&mut o, "r_series_to", w2.r_pct, zb_to, t, "to");
2321        self.referred_ohms(&mut o, "x_series_from", x_from_pct, zb_from, t, "from");
2322        self.referred_ohms(&mut o, "x_series_to", x_to_pct, zb_to, t, "to");
2323        o.insert("terminal_map_from".into(), json!(from.terminal_map));
2324        o.insert("terminal_map_to".into(), json!(to.terminal_map));
2325        self.transformer_neutral_fields(&mut o, t, from, &to);
2326        self.transformer_tap_fields(&mut o, t, from, &to);
2327        self.transformer_no_load_fields(&mut o, t, from, s);
2328        self.transformer_extras_dropped(t, &TRANSFORMER_TWO_WINDING_ALLOWED_EXTRAS);
2329        o.into()
2330    }
2331
2332    /// The lumped series resistance on the wye base, in ohms. Each winding
2333    /// holds its percent resistance on its own rating base, so each term is
2334    /// `r_pct / 100 * v_wye^2 / s_rating`. A rating that is not positive
2335    /// makes its term undefined; that term drops with a warning, so the
2336    /// output keeps the resistance of the other winding instead of an
2337    /// infinity that `num` would then emit as a lossless zero.
2338    fn referred_resistance(
2339        &mut self,
2340        t: &DistTransformer,
2341        from: &DistWinding,
2342        to: &DistWinding,
2343        v_wye2: f64,
2344    ) -> f64 {
2345        let mut total = 0.0;
2346        for (side, w) in [("from", from), ("to", to)] {
2347            if w.s_rating > 0.0 && w.s_rating.is_finite() {
2348                total += w.r_pct / w.s_rating;
2349            } else if w.r_pct != 0.0 {
2350                self.diagnostic(
2351                    &C::EMIT_BMOPF_FIELD_DROPPED,
2352                    format!("transformer {}", t.name),
2353                    format!(
2354                        "transformer {}: the `{side}` winding rating is not positive, so its \
2355                     resistance has no base to refer to; the term is dropped from r_series",
2356                        t.name
2357                    ),
2358                    Map::new(),
2359                );
2360            }
2361        }
2362        total / 100.0 * v_wye2
2363    }
2364
2365    /// Emit one series impedance field from a percent on `base`, or drop the
2366    /// field with a warning when the rating leaves that base undefined.
2367    fn referred_ohms(
2368        &mut self,
2369        o: &mut Map<String, Value>,
2370        key: &str,
2371        pct: f64,
2372        base: Option<f64>,
2373        t: &DistTransformer,
2374        side: &str,
2375    ) {
2376        match base {
2377            Some(zb) => {
2378                let value = self.num(pct / 100.0 * zb, key);
2379                o.insert(key.into(), value);
2380            }
2381            None => self.diagnostic(
2382                &C::EMIT_BMOPF_FIELD_DROPPED,
2383                format!("transformer {}", t.name),
2384                format!(
2385                    "transformer {}: the `{side}` winding rating is not positive, so its \
2386                 percent impedance has no base to refer to; `{key}` is dropped from \
2387                 the output",
2388                    t.name
2389                ),
2390                Map::new(),
2391            ),
2392        }
2393    }
2394
2395    fn center_tap_leakage_percentages(&mut self, t: &DistTransformer) -> (f64, f64) {
2396        let (x_from_pct, x_to_pct) = center_tap_star_percentages(&t.xsc_pct);
2397        if x_from_pct.is_finite()
2398            && x_to_pct.is_finite()
2399            && x_from_pct >= -1e-12
2400            && x_to_pct >= -1e-12
2401        {
2402            return (x_from_pct.max(0.0), x_to_pct.max(0.0));
2403        }
2404        let xhl = t.xsc_pct.first().copied().unwrap_or(0.0);
2405        let emitted_from = if xhl.is_finite() { xhl.max(0.0) } else { 0.0 };
2406        let mut details = Map::new();
2407        details.insert("xsc_pct".into(), json!(&t.xsc_pct));
2408        details.insert("star_percentages".into(), json!([x_from_pct, x_to_pct]));
2409        details.insert("emitted_percentages".into(), json!([emitted_from, 0.0]));
2410        self.transformer_diagnostic(
2411            t,
2412            &C::EMIT_BMOPF_TRANSFORMER_CENTER_TAP_LEAKAGE_UNREPRESENTABLE,
2413            format!(
2414                "transformer {}: center tap leakage star arms ({x_from_pct}, {x_to_pct}) \
2415                 are not representable as nonnegative BMOPF fields; emitted xhl on the \
2416                 from side and zero on the to side",
2417                t.name
2418            ),
2419            details,
2420        );
2421        (emitted_from, 0.0)
2422    }
2423
2424    /// Both three phase subtypes use the schema's lumped form: one
2425    /// `r_series`/`x_series` pair referred to the wye winding's base (the
2426    /// schema has no split `_from`/`_to` fields for them).
2427    fn three_phase(&mut self, t: &DistTransformer, wye_idx: usize) -> Value {
2428        let from = &t.windings[0];
2429        let to = &t.windings[1];
2430        let s = from.s_rating;
2431        let mut o = Map::new();
2432        o.insert("bus_from".into(), json!(from.bus));
2433        o.insert("bus_to".into(), json!(to.bus));
2434        o.insert("s_rating".into(), self.num(s, "transformer s_rating"));
2435        o.insert(
2436            "v_nom_from".into(),
2437            self.num(from.v_ref, "transformer v_nom_from"),
2438        );
2439        o.insert(
2440            "v_nom_to".into(),
2441            self.num(to.v_ref, "transformer v_nom_to"),
2442        );
2443        if t.xsc_pct.is_empty() {
2444            self.transformer_diagnostic(
2445                t,
2446                &C::EMIT_BMOPF_TRANSFORMER_MISSING_XSC,
2447                format!(
2448                    "transformer {}: xsc_pct is empty; emitted x_series=0",
2449                    t.name,
2450                ),
2451                Map::new(),
2452            );
2453        }
2454        let xhl = t.xsc_pct.first().copied().unwrap_or(0.0);
2455        let wye = &t.windings[wye_idx];
2456        let v_wye2 = wye.v_ref * wye.v_ref;
2457        // Each winding's percent resistance is on its own rating base; refer
2458        // both to the wye side before lumping (identical to the plain sum
2459        // when the ratings match). XHL is on the first winding's base.
2460        let r_series = self.referred_resistance(t, from, to, v_wye2);
2461        o.insert(
2462            "r_series".into(),
2463            self.num(r_series, "transformer r_series"),
2464        );
2465        // XHL is a percent on the first winding's rating base. That base is
2466        // the same one `referred_resistance` guards, so guard it here too: an
2467        // unusable rating must not reach the output as a zero reactance.
2468        let x_base = base_impedance(wye.v_ref, s);
2469        self.referred_ohms(&mut o, "x_series", xhl, x_base, t, "from");
2470        o.insert("terminal_map_from".into(), json!(from.terminal_map));
2471        o.insert("terminal_map_to".into(), json!(to.terminal_map));
2472        self.transformer_neutral_fields(&mut o, t, from, to);
2473        self.transformer_tap_fields(&mut o, t, from, to);
2474        self.transformer_no_load_fields(&mut o, t, from, s);
2475        self.transformer_extras_dropped(t, &TRANSFORMER_TWO_WINDING_ALLOWED_EXTRAS);
2476        o.into()
2477    }
2478
2479    fn n_winding(&mut self, t: &DistTransformer) -> Value {
2480        let s = t
2481            .extras
2482            .get("bmopf_power_base")
2483            .and_then(Value::as_f64)
2484            .unwrap_or_else(|| t.windings.first().map_or(f64::NAN, |w| w.s_rating));
2485        let mut o = Map::new();
2486        o.insert("s_rating".into(), self.num(s, "transformer s_rating"));
2487        let windings: Vec<Value> = t
2488            .windings
2489            .iter()
2490            .enumerate()
2491            .map(|(idx, w)| {
2492                let mut wj = Map::new();
2493                wj.insert("bus".into(), json!(w.bus));
2494                wj.insert("terminal_map".into(), json!(w.terminal_map));
2495                wj.insert(
2496                    "v_nom".into(),
2497                    self.num(
2498                        crate::transformer::calc_coil_voltage(t, idx),
2499                        "transformer winding v_nom",
2500                    ),
2501                );
2502                wj.insert(
2503                    "configuration".into(),
2504                    json!(match w.conn {
2505                        DistWindingConn::Wye => "WYE",
2506                        DistWindingConn::Delta => "DELTA",
2507                    }),
2508                );
2509                let zbase = crate::transformer::calc_winding_impedance_base(t, idx, w.s_rating)
2510                    .unwrap_or(f64::NAN);
2511                wj.insert(
2512                    "r_winding".into(),
2513                    self.num(w.r_pct / 100.0 * zbase, "transformer winding r_winding"),
2514                );
2515                wj.insert("s_rating".into(), self.num(w.s_rating, "winding s_rating"));
2516                wj.insert("tap_ratio".into(), self.num(w.tap, "winding tap_ratio"));
2517                if crate::transformer::calc_stated_neutral_grounding(w)
2518                    == crate::transformer::WindingNeutralGrounding::Floating
2519                {
2520                    self.warn(&C::EMIT_BMOPF_FIELD_DROPPED, format!("transformer {} winding {idx}: open OpenDSS neutral has no internal impedance branch; neutral impedance fields omitted", t.name));
2521                } else {
2522                    // The schema takes nonnegative winding neutral fields,
2523                    // as the two-winding subtypes do.
2524                    for (key, value) in [("r_neutral", w.r_neutral), ("x_neutral", w.x_neutral)] {
2525                        let Some(value) = value else { continue };
2526                        if value.is_finite() && value >= 0.0 {
2527                            wj.insert(key.into(), json!(value));
2528                        } else {
2529                            let mut details = Map::new();
2530                            details.insert("field".into(), json!(key));
2531                            details.insert("winding".into(), json!(idx));
2532                            details.insert("value".into(), json!(value));
2533                            self.transformer_diagnostic(
2534                                t,
2535                                &C::EMIT_BMOPF_TRANSFORMER_NEUTRAL_DROPPED,
2536                                format!(
2537                                    "transformer {} winding {idx}: {key}={value} is not a nonnegative finite BMOPF neutral impedance; dropped",
2538                                    t.name
2539                                ),
2540                                details,
2541                            );
2542                        }
2543                    }
2544                }
2545                if let Some(metadata) = t.extras.get("bmopf_winding_metadata").and_then(|v| v.get(idx.to_string())).and_then(Value::as_object) {
2546                    for (key, value) in metadata { wj.insert(key.clone(), value.clone()); }
2547                }
2548                if let Some(delta_roll) = bmopf_delta_roll(t, idx, w) {
2549                    wj.insert("delta_roll".into(), json!(delta_roll));
2550                }
2551                Value::Object(wj)
2552            })
2553            .collect();
2554        o.insert("windings".into(), Value::Array(windings));
2555        let base_z = (!t.windings.is_empty())
2556            .then(|| crate::transformer::calc_winding_impedance_base(t, 0, s))
2557            .flatten()
2558            .unwrap_or(f64::NAN);
2559        let x_sc = self.n_winding_x_sc(t, base_z);
2560        o.insert("x_sc".into(), Value::Object(x_sc));
2561        if let Some(first) = t.windings.first() {
2562            self.transformer_no_load_fields(&mut o, t, first, s);
2563        }
2564        self.transformer_extras_dropped(t, &TRANSFORMER_NO_LOAD_ALLOWED_EXTRAS);
2565        o.into()
2566    }
2567
2568    /// The `x_sc` pair table for an n_winding transformer. The winding count
2569    /// is model input, so the quadratic pair expansion is capped at
2570    /// [`MAX_DIM`] with a diagnostic.
2571    fn n_winding_x_sc(&mut self, t: &DistTransformer, base_z: f64) -> Map<String, Value> {
2572        let mut x_sc = Map::new();
2573        let n_windings = t.windings.len();
2574        if n_windings > MAX_DIM {
2575            let mut details = Map::new();
2576            details.insert("windings".into(), json!(n_windings));
2577            self.transformer_diagnostic(
2578                t,
2579                &C::EMIT_BMOPF_TRANSFORMER_WINDINGS_CLAMPED,
2580                format!(
2581                    "transformer {}: {n_windings} windings exceed the supported \
2582                     maximum of {MAX_DIM}; x_sc pairs beyond it are dropped",
2583                    t.name
2584                ),
2585                details,
2586            );
2587        }
2588        for (idx, (i, j)) in pair_keys(n_windings.min(MAX_DIM)).into_iter().enumerate() {
2589            let x_pct = t.xsc_pct.get(idx).copied().unwrap_or_else(|| {
2590                let mut details = Map::new();
2591                details.insert("winding_pair".into(), json!(format!("{}_{}", i + 1, j + 1)));
2592                self.transformer_diagnostic(
2593                    t,
2594                    &C::EMIT_BMOPF_TRANSFORMER_MISSING_XSC,
2595                    format!(
2596                        "transformer {}: missing x_sc for winding pair {}_{}; emitted 0",
2597                        t.name,
2598                        i + 1,
2599                        j + 1
2600                    ),
2601                    details,
2602                );
2603                0.0
2604            });
2605            x_sc.insert(
2606                format!("{}_{}", i + 1, j + 1),
2607                self.num(x_pct / 100.0 * base_z, "transformer x_sc"),
2608            );
2609        }
2610        x_sc
2611    }
2612
2613    /// A three phase wye-wye unit becomes one single_phase entry per phase
2614    /// (`name_1`..), each at line to neutral voltage and a third of the
2615    /// rating. That keeps the impedance base v^2/s, so the percent values
2616    /// carry over unchanged. The public IEEE13 example records the line to
2617    /// line voltage on its decomposed units instead; both are self
2618    /// consistent, they differ in the v_ref convention.
2619    fn decompose_wye_wye(&mut self, t: &DistTransformer) -> Vec<(String, Value)> {
2620        let mut out = Vec::new();
2621        let (from, to) = (&t.windings[0], &t.windings[1]);
2622        for k in 0..t.phases {
2623            let per = |w: &DistWinding| {
2624                let neutral = w.terminal_map.last().cloned().unwrap_or_default();
2625                DistWinding {
2626                    bus: w.bus.clone(),
2627                    terminal_map: vec![w.terminal_map[k].clone(), neutral],
2628                    conn: DistWindingConn::Wye,
2629                    v_ref: crate::electrical::calc_wye_phase_voltage(w.v_ref),
2630                    s_rating: w.s_rating / 3.0,
2631                    r_pct: w.r_pct,
2632                    tap: w.tap,
2633                    r_neutral: if k == 0 { w.r_neutral } else { None },
2634                    x_neutral: if k == 0 { w.x_neutral } else { None },
2635                }
2636            };
2637            let f = per(from);
2638            let to_1 = per(to);
2639            let mut t1 = t.clone();
2640            t1.windings = vec![f.clone(), to_1.clone()];
2641            t1.phases = 1;
2642            split_no_load_extras(&mut t1, t.phases);
2643            let v = self.two_winding(&t1, &f, &to_1, 1.0, true, false);
2644            out.push((format!("{}_{}", t.name, k + 1), v));
2645        }
2646        let mut details = Map::new();
2647        details.insert("emitted_subtype".into(), json!("single_phase"));
2648        details.insert("units".into(), json!(t.phases));
2649        self.transformer_diagnostic(
2650            t,
2651            &C::EMIT_BMOPF_TRANSFORMER_WYE_WYE_DECOMPOSED,
2652            format!(
2653                "transformer {}: three phase wye-wye decomposed into {} single_phase units",
2654                t.name, t.phases
2655            ),
2656            details,
2657        );
2658        self.transformer_extras_dropped(t, &TRANSFORMER_TWO_WINDING_ALLOWED_EXTRAS);
2659        out
2660    }
2661
2662    fn transformer_tap_fields(
2663        &mut self,
2664        o: &mut Map<String, Value>,
2665        t: &DistTransformer,
2666        from: &DistWinding,
2667        to: &DistWinding,
2668    ) {
2669        if to.tap.abs() <= 1e-12 {
2670            if (from.tap - 1.0).abs() > 1e-12 || (to.tap - 1.0).abs() > 1e-12 {
2671                let mut details = Map::new();
2672                details.insert("from_tap".into(), json!(from.tap));
2673                details.insert("to_tap".into(), json!(to.tap));
2674                self.transformer_diagnostic(
2675                    t,
2676                    &C::EMIT_BMOPF_TRANSFORMER_TAP_DROPPED,
2677                    format!(
2678                        "transformer {}: to-side tap {} cannot form a finite BMOPF ratio; dropped",
2679                        t.name, to.tap
2680                    ),
2681                    details,
2682                );
2683            }
2684        } else {
2685            let tap = from.tap / to.tap;
2686            if (tap - 1.0).abs() > 1e-12 || t.extras.contains_key("tap") {
2687                o.insert("tap".into(), self.num(tap, "transformer tap"));
2688            }
2689        }
2690        for key in ["tap_min", "tap_max"] {
2691            if let Some(v) = extras_number(&t.extras, key) {
2692                o.insert(key.into(), self.num(v, &format!("transformer {key}")));
2693            }
2694        }
2695    }
2696
2697    fn warn_nonuniform_per_phase_taps(&mut self, t: &DistTransformer) {
2698        let Some(tm_set) = t.extras.get("pmd_tm_set").and_then(Value::as_array) else {
2699            return;
2700        };
2701        for (idx, raw) in tm_set.iter().enumerate() {
2702            let Some(taps) = tap_values(raw) else {
2703                continue;
2704            };
2705            let Some(first) = taps.first().copied() else {
2706                continue;
2707            };
2708            if taps.iter().any(|tap| (tap - first).abs() > 1e-9) {
2709                let mut details = Map::new();
2710                details.insert("winding".into(), json!(idx + 1));
2711                details.insert("source_taps".into(), json!(taps));
2712                details.insert("emitted_winding_tap".into(), json!(first));
2713                self.transformer_diagnostic(
2714                    t,
2715                    &C::EMIT_BMOPF_TRANSFORMER_PER_PHASE_TAP_COLLAPSED,
2716                    format!(
2717                        "transformer {}: winding {} has non-uniform per phase taps; emitted the first phase tap",
2718                        t.name,
2719                        idx + 1
2720                    ),
2721                    details,
2722                );
2723            }
2724        }
2725    }
2726
2727    fn transformer_neutral_fields(
2728        &mut self,
2729        o: &mut Map<String, Value>,
2730        t: &DistTransformer,
2731        from: &DistWinding,
2732        to: &DistWinding,
2733    ) {
2734        for (side, winding) in [("from", from), ("to", to)] {
2735            let resistance = format!("r_neutral_{side}");
2736            let reactance = format!("x_neutral_{side}");
2737            self.transformer_neutral_field(o, t, &resistance, winding.r_neutral);
2738            if crate::transformer::calc_stated_neutral_grounding(winding)
2739                == crate::transformer::WindingNeutralGrounding::Floating
2740            {
2741                if let Some(x) = winding.x_neutral {
2742                    self.warn(&C::EMIT_BMOPF_TRANSFORMER_NEUTRAL_DROPPED,
2743                        format!("transformer {}: {reactance}={x} omitted with the open neutral encoded by negative {resistance}", t.name));
2744                }
2745            } else {
2746                self.transformer_neutral_field(o, t, &reactance, winding.x_neutral);
2747            }
2748        }
2749    }
2750
2751    fn transformer_neutral_field(
2752        &mut self,
2753        o: &mut Map<String, Value>,
2754        t: &DistTransformer,
2755        key: &str,
2756        value: Option<f64>,
2757    ) {
2758        let Some(v) = value else {
2759            return;
2760        };
2761        if v.is_finite() && v >= 0.0 {
2762            o.insert(key.into(), json!(v));
2763        } else {
2764            let mut details = Map::new();
2765            details.insert("field".into(), json!(key));
2766            details.insert("value".into(), json!(v));
2767            self.transformer_diagnostic(
2768                t,
2769                &C::EMIT_BMOPF_TRANSFORMER_NEUTRAL_DROPPED,
2770                format!(
2771                    "transformer {}: {key}={v} is not a nonnegative finite BMOPF neutral impedance; dropped",
2772                    t.name
2773                ),
2774                details,
2775            );
2776        }
2777    }
2778
2779    fn center_tap_neutral(
2780        &mut self,
2781        t: &DistTransformer,
2782        field: &str,
2783        a: Option<f64>,
2784        b: Option<f64>,
2785    ) -> Option<f64> {
2786        if let (Some(a), Some(b)) = (a, b) {
2787            let mut details = Map::new();
2788            details.insert("field".into(), json!(field));
2789            details.insert("values".into(), json!([a, b]));
2790            self.transformer_diagnostic(
2791                t,
2792                &C::EMIT_BMOPF_TRANSFORMER_CENTER_TAP_NEUTRAL_COLLAPSED,
2793                format!(
2794                    "transformer {}: center tap secondary has two {field} values ({a}, {b}); emitted the first",
2795                    t.name
2796                ),
2797                details,
2798            );
2799        }
2800        a.or(b)
2801    }
2802
2803    fn warn_unrepresented_neutral_fields(&mut self, t: &DistTransformer, target: &str) {
2804        for (idx, w) in t.windings.iter().enumerate() {
2805            if w.r_neutral.is_some() || w.x_neutral.is_some() {
2806                let mut details = Map::new();
2807                details.insert("target".into(), json!(target));
2808                details.insert("winding".into(), json!(idx + 1));
2809                self.transformer_diagnostic(
2810                    t,
2811                    &C::EMIT_BMOPF_TRANSFORMER_NEUTRAL_DROPPED,
2812                    format!(
2813                        "transformer {} winding {}: neutral impedance has no {target} field; dropped",
2814                        t.name,
2815                        idx + 1
2816                    ),
2817                    details,
2818                );
2819            }
2820        }
2821    }
2822
2823    fn transformer_no_load_fields(
2824        &mut self,
2825        o: &mut Map<String, Value>,
2826        t: &DistTransformer,
2827        _from: &DistWinding,
2828        s: f64,
2829    ) {
2830        if let Some(shunt) = t.extras.get("no_load_shunt") {
2831            o.insert("no_load_shunt".into(), shunt.clone());
2832            return;
2833        }
2834        if t.extras.contains_key("g_no_load") || t.extras.contains_key("b_no_load") {
2835            for key in ["g_no_load", "b_no_load"] {
2836                if let Some(value) = t.extras.get(key) {
2837                    o.insert(key.into(), value.clone());
2838                }
2839            }
2840            return;
2841        }
2842        let loss = extras_number(&t.extras, "%noloadloss");
2843        let imag = extras_number(&t.extras, "%imag");
2844        if loss.is_none() && imag.is_none() {
2845            return;
2846        }
2847        // OpenDSS places the exciting branch on physical winding 2. Its
2848        // terminal admittance includes the winding tap and the per-coil base.
2849        let voltage = t
2850            .windings
2851            .get(1)
2852            .map(|w| crate::transformer::calc_coil_voltage(t, 1) * w.tap);
2853        if let Some(voltage) = voltage
2854            && let Some(y_base) =
2855                crate::electrical::calc_admittance_base(voltage, s / t.phases.max(1) as f64)
2856            && loss.is_none_or(|v| v >= 0.0)
2857            && imag.is_none_or(|v| v >= 0.0)
2858        {
2859            o.insert(
2860                "no_load_shunt".into(),
2861                json!({
2862                    "winding": 2,
2863                    "g": loss.unwrap_or(0.0) / 100.0 * y_base,
2864                    "b": -imag.unwrap_or(0.0) / 100.0 * y_base,
2865                }),
2866            );
2867        } else {
2868            let details = Map::from_iter([("field".into(), json!("no_load_shunt"))]);
2869            self.transformer_diagnostic(t, &C::EMIT_BMOPF_TRANSFORMER_NO_LOAD_SHUNT_UNCONVERTIBLE,
2870                format!("transformer {}: no-load percentages require nonnegative values, a positive power base and a positive winding-2 coil voltage", t.name), details);
2871        }
2872    }
2873
2874    fn transformer_extras_dropped(&mut self, t: &DistTransformer, allowed: &[&str]) {
2875        for key in t.extras.keys() {
2876            if key == "bmopf_subtype" || key == "tap" || allowed.contains(&key.as_str()) {
2877                continue;
2878            }
2879            let mut details = Map::new();
2880            details.insert("field".into(), json!(key));
2881            self.transformer_diagnostic(
2882                t,
2883                &C::EMIT_BMOPF_TRANSFORMER_EXTRA_DROPPED,
2884                format!(
2885                    "transformer {}: `{key}` has no place in the BMOPF schema; dropped from the output",
2886                    t.name
2887                ),
2888                details,
2889            );
2890        }
2891    }
2892
2893    /// Emits a matrix whose `_1_1` entry the schema requires; an empty one
2894    /// becomes `dim` by `dim` zeros so the required key exists. `dim` derives
2895    /// from a sibling matrix's row count, which model input controls, so the
2896    /// dense zero fill is capped at [`MAX_DIM`].
2897    fn required_matrix(
2898        &mut self,
2899        o: &mut Map<String, Value>,
2900        prefix: &str,
2901        m: &ConductorMatrix,
2902        dim: usize,
2903        name: &str,
2904    ) {
2905        if m.is_empty() {
2906            let dim = if dim > MAX_DIM {
2907                self.warn(
2908                    &C::EMIT_BMOPF_VALUE_CLAMPED,
2909                    format!(
2910                        "{name}: {prefix} dimension {dim} exceeds the supported \
2911                     maximum of {MAX_DIM}; zero matrix clamped"
2912                    ),
2913                );
2914                MAX_DIM
2915            } else {
2916                dim
2917            };
2918            self.flat_matrix(o, prefix, &vec![vec![0.0; dim]; dim], name);
2919        } else {
2920            self.flat_matrix(o, prefix, m, name);
2921        }
2922    }
2923
2924    fn flat_matrix(
2925        &mut self,
2926        o: &mut Map<String, Value>,
2927        prefix: &str,
2928        m: &ConductorMatrix,
2929        name: &str,
2930    ) {
2931        for (i, row) in m.iter().enumerate() {
2932            for (j, &v) in row.iter().enumerate() {
2933                o.insert(
2934                    format!("{prefix}_{}_{}", i + 1, j + 1),
2935                    self.num(v, &format!("{name} {prefix}")),
2936                );
2937            }
2938        }
2939    }
2940}
2941
2942/// Spells the two-winding tap ratio the way the schema names it.
2943///
2944/// The emitters spell it `tap`; the schema declares `tap_ratio` on the two-winding
2945/// subtypes and on both regulator subtypes, so one name covers every
2946/// transformer that has a ratio. The value is unchanged: it is the multiplier
2947/// on the nameplate turns ratio in both spellings.
2948fn rename_tap_fields(by_subtype: &mut Map<String, Value>) {
2949    const RENAMED: [(&str, &str); 3] = [
2950        ("tap", "tap_ratio"),
2951        ("tap_min", "tap_ratio_min"),
2952        ("tap_max", "tap_ratio_max"),
2953    ];
2954    for subtype in ["single_phase", "center_tap", "wye_delta", "delta_wye"] {
2955        let Some(Value::Object(table)) = by_subtype.get_mut(subtype) else {
2956            continue;
2957        };
2958        for entry in table.values_mut() {
2959            let Value::Object(o) = entry else { continue };
2960            for (from, to) in RENAMED {
2961                if let Some(value) = o.remove(from) {
2962                    o.insert(to.to_string(), value);
2963                }
2964            }
2965        }
2966    }
2967}
2968
2969/// Spell the generator, IBR and voltage source cost `energy_cost_rate`, the
2970/// name the schema declares; the model reads the older `cost` spelling too.
2971fn rename_cost_fields(doc: &mut Map<String, Value>) {
2972    for class in ["generator", "ibr", "voltage_source"] {
2973        let Some(table) = doc.get_mut(class).and_then(Value::as_object_mut) else {
2974            continue;
2975        };
2976        for record in table.values_mut().filter_map(Value::as_object_mut) {
2977            if let Some(cost) = record.remove("cost") {
2978                record.entry("energy_cost_rate").or_insert(cost);
2979            }
2980        }
2981    }
2982}
2983
2984/// Spells the regulators' ratio the way the schema names it:
2985/// `voltage_ratio`, `voltage_ratio_min` and `voltage_ratio_max`, the regulated
2986/// over source voltage, in the record and in its `time_series` references.
2987/// The model keeps the ratio as `tap_ratio`, the name earlier BMOPF used.
2988fn rename_regulator_ratio_fields(by_subtype: &mut Map<String, Value>) {
2989    const RENAMED: [(&str, &str); 3] = [
2990        ("tap_ratio", "voltage_ratio"),
2991        ("tap_ratio_min", "voltage_ratio_min"),
2992        ("tap_ratio_max", "voltage_ratio_max"),
2993    ];
2994    for subtype in ["single_phase_autotransformer", "open_delta_regulator"] {
2995        let Some(Value::Object(table)) = by_subtype.get_mut(subtype) else {
2996            continue;
2997        };
2998        for entry in table.values_mut() {
2999            let Value::Object(o) = entry else { continue };
3000            for (from, to) in RENAMED {
3001                if let Some(value) = o.remove(from) {
3002                    o.insert(to.to_string(), value);
3003                }
3004                if let Some(Value::Object(refs)) = o.get_mut("time_series")
3005                    && let Some(value) = refs.remove(from)
3006                {
3007                    refs.insert(to.to_string(), value);
3008                }
3009            }
3010        }
3011    }
3012}
3013
3014#[derive(Clone)]
3015struct SourceEmit {
3016    name: String,
3017    bus: String,
3018    terminal_map: Vec<String>,
3019    v_magnitude: Vec<f64>,
3020    v_angle: Vec<f64>,
3021    energy_cost_rate: Option<Vec<f64>>,
3022    extras: Extras,
3023    dropped_extras: Vec<(String, Extras)>,
3024}
3025
3026impl From<&VoltageSource> for SourceEmit {
3027    fn from(source: &VoltageSource) -> Self {
3028        Self {
3029            name: source.name.clone(),
3030            bus: source.bus.clone(),
3031            terminal_map: source.terminal_map.clone(),
3032            v_magnitude: source.v_magnitude.clone(),
3033            v_angle: source.v_angle.clone(),
3034            energy_cost_rate: source.energy_cost_rate.clone(),
3035            extras: source.extras.clone(),
3036            dropped_extras: Vec::new(),
3037        }
3038    }
3039}
3040
3041#[derive(Clone)]
3042struct PhaseSource {
3043    label: String,
3044    magnitude: f64,
3045    angle: f64,
3046    neutral: Option<String>,
3047}
3048
3049#[derive(Clone, Copy, PartialEq, Eq)]
3050enum PhaseArrangement {
3051    Zero,
3052    Quadrature,
3053    Positive,
3054    Negative,
3055    AntiPhase,
3056    Incoherent,
3057}
3058
3059fn bmopf_voltage_sources(net: &MulticonductorNetwork) -> Vec<SourceEmit> {
3060    let emitted: Vec<SourceEmit> = net.sources().iter().map(SourceEmit::from).collect();
3061    let bus_ids: BTreeMap<String, String> = net
3062        .buses()
3063        .iter()
3064        .map(|bus| (bus.id.to_ascii_lowercase(), bus.id.clone()))
3065        .collect();
3066    let mut by_bus: BTreeMap<String, Vec<usize>> = BTreeMap::new();
3067    for (i, source) in emitted.iter().enumerate() {
3068        by_bus
3069            .entry(source.bus.to_ascii_lowercase())
3070            .or_default()
3071            .push(i);
3072    }
3073
3074    let mut replacements = BTreeMap::new();
3075    let mut removed = BTreeSet::new();
3076    for (bus_key, indices) in by_bus.iter().filter(|(_, indices)| indices.len() > 1) {
3077        if let Some((keep, merged)) =
3078            merge_voltage_source_group(&emitted, indices, bus_ids.get(bus_key))
3079        {
3080            replacements.insert(keep, merged);
3081            removed.extend(indices.iter().copied().filter(|i| *i != keep));
3082        }
3083    }
3084
3085    emitted
3086        .into_iter()
3087        .enumerate()
3088        .filter_map(|(i, source)| {
3089            if removed.contains(&i) {
3090                None
3091            } else {
3092                Some(replacements.remove(&i).unwrap_or(source))
3093            }
3094        })
3095        .collect()
3096}
3097
3098fn merge_voltage_source_group(
3099    sources: &[SourceEmit],
3100    indices: &[usize],
3101    bus_id: Option<&String>,
3102) -> Option<(usize, SourceEmit)> {
3103    let mut sorted = indices.to_vec();
3104    sorted.sort_by(|a, b| sources[*a].name.cmp(&sources[*b].name));
3105
3106    let mut phases = Vec::new();
3107    let mut seen = BTreeSet::new();
3108    for index in &sorted {
3109        let source = &sources[*index];
3110        if source.energy_cost_rate.is_some() || source_has_bounds_or_cost(&source.extras) {
3111            return None;
3112        }
3113        let (rank, phase) = single_phase_source(source)?;
3114        if !seen.insert(rank) {
3115            return None;
3116        }
3117        phases.push((rank, phase));
3118    }
3119
3120    if phases.len() < 2 {
3121        return None;
3122    }
3123    phases.sort_by_key(|(rank, _)| *rank);
3124
3125    let neutral = phases.first()?.1.neutral.clone();
3126    if phases.iter().any(|(_, phase)| phase.neutral != neutral) {
3127        return None;
3128    }
3129
3130    match phase_arrangement(phases.iter().map(|(_, phase)| phase.angle)) {
3131        PhaseArrangement::Zero | PhaseArrangement::Positive | PhaseArrangement::Negative => {}
3132        PhaseArrangement::Quadrature
3133        | PhaseArrangement::AntiPhase
3134        | PhaseArrangement::Incoherent => {
3135            return None;
3136        }
3137    }
3138
3139    let keep = sorted
3140        .iter()
3141        .copied()
3142        .find(|i| sources[*i].name == "source")
3143        .unwrap_or(sorted[0]);
3144    let mut merged = sources[keep].clone();
3145    if let Some(bus_id) = bus_id {
3146        merged.bus.clone_from(bus_id);
3147    }
3148    merged.terminal_map = phases
3149        .iter()
3150        .map(|(_, phase)| phase.label.clone())
3151        .collect();
3152    merged.v_magnitude = phases.iter().map(|(_, phase)| phase.magnitude).collect();
3153    merged.v_angle = phases.iter().map(|(_, phase)| phase.angle).collect();
3154    if let Some(neutral) = neutral {
3155        merged.terminal_map.push(neutral);
3156        merged.v_magnitude.push(0.0);
3157        merged.v_angle.push(0.0);
3158    }
3159    merged.dropped_extras = sorted
3160        .iter()
3161        .copied()
3162        .filter(|i| *i != keep)
3163        .map(|i| (sources[i].name.clone(), sources[i].extras.clone()))
3164        .collect();
3165    Some((keep, merged))
3166}
3167
3168fn source_has_bounds_or_cost(extras: &Extras) -> bool {
3169    [
3170        "p_min",
3171        "p_max",
3172        "q_min",
3173        "q_max",
3174        "cost",
3175        "energy_cost_rate",
3176    ]
3177    .iter()
3178    .any(|key| extras.contains_key(*key))
3179}
3180
3181fn single_phase_source(source: &SourceEmit) -> Option<(usize, PhaseSource)> {
3182    let mut phase = None;
3183    let mut neutral = None;
3184    for (i, label) in source.terminal_map.iter().enumerate() {
3185        if let Some(rank) = phase_rank(label) {
3186            if phase.replace((rank, label.clone(), i)).is_some() {
3187                return None;
3188            }
3189        } else if neutral.replace(label.clone()).is_some() {
3190            return None;
3191        }
3192    }
3193    let (rank, label, index) = phase?;
3194    Some((
3195        rank,
3196        PhaseSource {
3197            label,
3198            magnitude: *source.v_magnitude.get(index)?,
3199            angle: *source.v_angle.get(index)?,
3200            neutral,
3201        },
3202    ))
3203}
3204
3205fn phase_rank(label: &str) -> Option<usize> {
3206    match label {
3207        "1" | "a" | "A" => Some(0),
3208        "2" | "b" | "B" => Some(1),
3209        "3" | "c" | "C" => Some(2),
3210        _ => None,
3211    }
3212}
3213
3214fn phase_arrangement(angles: impl IntoIterator<Item = f64>) -> PhaseArrangement {
3215    let angles: Vec<f64> = angles.into_iter().collect();
3216    if angles.len() < 2 {
3217        return PhaseArrangement::Incoherent;
3218    }
3219    if angles.len() == 2 {
3220        return separation_of_diff(angles[0] - angles[1]);
3221    }
3222    let mut arrangement = None;
3223    for i in 0..angles.len() {
3224        let next = (i + 1) % angles.len();
3225        let current = separation_of_diff(angles[i] - angles[next]);
3226        if current == PhaseArrangement::Incoherent {
3227            return PhaseArrangement::Incoherent;
3228        }
3229        if let Some(previous) = arrangement {
3230            if previous != current {
3231                return PhaseArrangement::Incoherent;
3232            }
3233        } else {
3234            arrangement = Some(current);
3235        }
3236    }
3237    arrangement.unwrap_or(PhaseArrangement::Incoherent)
3238}
3239
3240fn separation_of_diff(diff: f64) -> PhaseArrangement {
3241    let diff = wrap_pi(diff);
3242    let adiff = diff.abs();
3243    if adiff <= PI / 6.0 {
3244        PhaseArrangement::Zero
3245    } else if (adiff - FRAC_PI_2).abs() <= PI / 12.0 {
3246        PhaseArrangement::Quadrature
3247    } else if (adiff - TAU / 3.0).abs() <= PI / 6.0 {
3248        if diff > 0.0 {
3249            PhaseArrangement::Positive
3250        } else {
3251            PhaseArrangement::Negative
3252        }
3253    } else if (adiff - PI).abs() <= PI / 12.0 {
3254        PhaseArrangement::AntiPhase
3255    } else {
3256        PhaseArrangement::Incoherent
3257    }
3258}
3259
3260fn wrap_pi(angle: f64) -> f64 {
3261    let wrapped = (angle + PI).rem_euclid(TAU) - PI;
3262    if (wrapped + PI).abs() < f64::EPSILON {
3263        PI
3264    } else {
3265        wrapped
3266    }
3267}
3268
3269enum Kind {
3270    SinglePhase,
3271    /// Two windings already in the shared single_phase/center_tap shape,
3272    /// emitted under the named subtype.
3273    SinglePhaseShape(&'static str),
3274    /// A dss classified step voltage regulator, emitted under the
3275    /// `single_phase_autotransformer` subtype of the BMOPFTools schema
3276    /// extension.
3277    Autotransformer,
3278    /// One line to line leg of a dss classified open delta regulator bank;
3279    /// two legs merge into one `open_delta_regulator` object.
3280    OpenDeltaLeg,
3281    CenterTap,
3282    WyeDelta,
3283    DeltaWye,
3284    WyeWye3,
3285    NWinding,
3286    Unsupported(String),
3287}
3288
3289fn classify(t: &DistTransformer) -> Kind {
3290    // A network read from BMOPF records its subtype; trust it so writing
3291    // back reproduces the grouping (center tap reads as two windings).
3292    // An unknown or shape mismatched subtype falls through to the shape
3293    // based classification below.
3294    if let Some(sub) = t.extras.get("bmopf_subtype").and_then(|v| v.as_str()) {
3295        if t.windings.len() == 2 {
3296            match sub {
3297                "single_phase" => return Kind::SinglePhase,
3298                "center_tap" => return Kind::SinglePhaseShape("center_tap"),
3299                "wye_delta" => return Kind::WyeDelta,
3300                "delta_wye" => return Kind::DeltaWye,
3301                "single_phase_autotransformer" => return Kind::Autotransformer,
3302                "open_delta_regulator" => return Kind::OpenDeltaLeg,
3303                _ => {}
3304            }
3305        }
3306        if sub == "n_winding" && t.windings.len() >= 2 {
3307            return Kind::NWinding;
3308        }
3309    }
3310    let conns: Vec<DistWindingConn> = t.windings.iter().map(|w| w.conn).collect();
3311    match (t.phases, conns.as_slice()) {
3312        // single_phase covers the plain 1-phase unit in every conn pairing:
3313        // a delta winding here is one wired line to line (an open wye or
3314        // open delta leg, or both legs of a fixed tap open delta bank). The
3315        // single_phase shape holds it: two phase terminals, no conn
3316        // discriminator, and the line to line v_ref makes the per winding
3317        // impedance base v^2/s already right — which reads the same for one
3318        // delta winding or two.
3319        (
3320            1,
3321            [
3322                DistWindingConn::Wye | DistWindingConn::Delta,
3323                DistWindingConn::Wye | DistWindingConn::Delta,
3324            ],
3325        ) => Kind::SinglePhase,
3326        (
3327            1,
3328            [
3329                DistWindingConn::Wye,
3330                DistWindingConn::Wye,
3331                DistWindingConn::Wye,
3332            ],
3333        ) => {
3334            // The compact center-tap subtype has one shared secondary
3335            // leakage arm, so its two primary-to-secondary tests must
3336            // agree. Keep unequal tests (including explicit zero) in the
3337            // general pair table instead of silently symmetrizing them.
3338            let xhl = t.xsc_pct.first().copied().unwrap_or(0.0);
3339            let xht = t.xsc_pct.get(1).copied().unwrap_or(xhl);
3340            if (xhl - xht).abs() > 0.0 {
3341                Kind::NWinding
3342            } else {
3343                Kind::CenterTap
3344            }
3345        }
3346        (3, [DistWindingConn::Wye, DistWindingConn::Delta]) => Kind::WyeDelta,
3347        (3, [DistWindingConn::Delta, DistWindingConn::Wye]) => Kind::DeltaWye,
3348        // The decomposition indexes terminal_map[phase] and takes the last
3349        // entry as the neutral; anything else is not safely decomposable.
3350        (3, [DistWindingConn::Wye, DistWindingConn::Wye])
3351            if t.windings
3352                .iter()
3353                .all(|w| w.terminal_map.len() == t.phases + 1) =>
3354        {
3355            Kind::WyeWye3
3356        }
3357        (3, [DistWindingConn::Wye, DistWindingConn::Wye]) => Kind::Unsupported(
3358            "three phase wye-wye whose terminal maps do not list each phase plus a neutral".into(),
3359        ),
3360        (_, _) if t.windings.len() >= 3 => Kind::NWinding,
3361        _ => Kind::Unsupported(format!(
3362            "{} phase with {} windings ({:?})",
3363            t.phases,
3364            t.windings.len(),
3365            conns
3366        )),
3367    }
3368}
3369
3370/// Normalize a raw profile into BMOPF's multiplicative time-series shape.
3371/// PMD's source ID is provenance, while nonzero offset and `replace=true`
3372/// change profile semantics and cannot be represented by BMOPF.
3373#[cfg(test)]
3374fn normalized_bmopf_time_series(value: &Value) -> Option<(Value, Option<Value>)> {
3375    normalized_bmopf_time_series_for_source(value, false)
3376}
3377
3378fn normalized_bmopf_time_series_for_source(
3379    value: &Value,
3380    is_pmd: bool,
3381) -> Option<(Value, Option<Value>)> {
3382    let mut profile = value.as_object()?.clone();
3383    // Only complete, finite factors can become active BMOPF profiles.
3384    // Invalid or unsupported records remain verbatim in extras.
3385    let values = profile.get("values")?.as_array()?;
3386    if values.is_empty()
3387        || values
3388            .iter()
3389            .any(|value| value.as_f64().is_none_or(|value| !value.is_finite()))
3390        || profile
3391            .get("description")
3392            .is_some_and(|value| !value.is_string())
3393    {
3394        return None;
3395    }
3396    let steps = values.len();
3397    let source_id = profile.remove("source_id");
3398    let offset = profile.remove("offset");
3399    let replace = profile.remove("replace");
3400
3401    let offset_is_default = offset
3402        .as_ref()
3403        .is_none_or(|value| value.as_f64() == Some(0.0));
3404    // PMD defines replace=true when omitted, even if source_id and offset
3405    // are absent. Require an explicit false for every PMD-origin profile.
3406    let replace_is_default = if is_pmd {
3407        replace.as_ref().and_then(Value::as_bool) == Some(false)
3408    } else {
3409        match replace.as_ref() {
3410            Some(value) => value.as_bool() == Some(false),
3411            None => source_id.is_none() && offset.is_none(),
3412        }
3413    };
3414    // BMOPF accepts numeric offsets in seconds. PMD numeric axes are
3415    // expressed in hours; timestamp/string axes cannot be represented and
3416    // therefore make the complete profile source-only. Keep integer axes
3417    // exact where possible instead of routing them through f64.
3418    if let Some(time) = profile.get("time").cloned() {
3419        let normalized = normalize_bmopf_time_axis(&time, is_pmd)?;
3420        if normalized.as_array()?.len() != steps {
3421            return None;
3422        }
3423        profile.insert("time".into(), normalized);
3424    }
3425    let allowed = ["values", "time", "description"];
3426    if !offset_is_default
3427        || !replace_is_default
3428        || profile.keys().any(|key| !allowed.contains(&key.as_str()))
3429    {
3430        return None;
3431    }
3432
3433    let mut metadata = Map::new();
3434    if let Some(value) = source_id {
3435        metadata.insert("source_id".into(), value);
3436    }
3437    if let Some(value) = offset {
3438        metadata.insert("offset".into(), value);
3439    }
3440    if let Some(value) = replace {
3441        metadata.insert("replace".into(), value);
3442    }
3443    Some((
3444        Value::Object(profile),
3445        (!metadata.is_empty()).then_some(Value::Object(metadata)),
3446    ))
3447}
3448
3449/// Convert a profile time axis to the numeric-seconds representation used
3450/// by BMOPF. The time axis is optional; when present it must be a numeric array.
3451/// PMD axes are in hours, while native BMOPF axes are already in seconds.
3452fn normalize_bmopf_time_axis(time: &Value, from_pmd: bool) -> Option<Value> {
3453    let values = time.as_array()?;
3454    if values.is_empty() {
3455        return None;
3456    }
3457    let mut normalized = Vec::with_capacity(values.len());
3458    for value in values {
3459        let number = value.as_number()?;
3460        let seconds = if from_pmd {
3461            if let Some(hours) = number.as_u64() {
3462                serde_json::Number::from(hours.checked_mul(3_600)?)
3463            } else if let Some(hours) = number.as_i64() {
3464                serde_json::Number::from(hours.checked_mul(3_600)?)
3465            } else {
3466                let seconds = number.as_f64()? * 3_600.0;
3467                serde_json::Number::from_f64(seconds)?
3468            }
3469        } else {
3470            // Validate native BMOPF seconds without changing their JSON
3471            // representation or introducing a floating-point round trip.
3472            if !number.as_f64()?.is_finite() {
3473                return None;
3474            }
3475            number.clone()
3476        };
3477        if !seconds.as_f64()?.is_finite() {
3478            return None;
3479        }
3480        normalized.push(Value::Number(seconds));
3481    }
3482    // Conversion can collapse adjacent floating-point steps. Check the
3483    // emitted axis, keeping integer comparisons exact above f64's ceiling.
3484    let increasing = normalized
3485        .windows(2)
3486        .all(|pair| compare_time_steps(&pair[0], &pair[1]) == Some(std::cmp::Ordering::Less));
3487    increasing.then_some(Value::Array(normalized))
3488}
3489
3490fn bmopf_profiles_share_steps(left: &Value, right: &Value) -> bool {
3491    let count = |profile: &Value| {
3492        profile
3493            .get("values")
3494            .and_then(Value::as_array)
3495            .map(Vec::len)
3496    };
3497    count(left) == count(right)
3498        && match (left.get("time"), right.get("time")) {
3499            (None, None) => true,
3500            (Some(Value::Array(left)), Some(Value::Array(right))) => {
3501                left.len() == right.len()
3502                    && left
3503                        .iter()
3504                        .zip(right)
3505                        .all(|(left, right)| same_time_step(left, right))
3506            }
3507            _ => false,
3508        }
3509}
3510
3511// Time steps are identities, so use exact numeric comparisons, never a tolerance.
3512fn same_time_step(left: &Value, right: &Value) -> bool {
3513    compare_time_steps(left, right) == Some(std::cmp::Ordering::Equal)
3514}
3515
3516fn compare_time_steps(left: &Value, right: &Value) -> Option<std::cmp::Ordering> {
3517    if let (Some(left), Some(right)) = (left.as_i64(), right.as_i64()) {
3518        return Some(left.cmp(&right));
3519    }
3520    if let (Some(left), Some(right)) = (left.as_u64(), right.as_u64()) {
3521        return Some(left.cmp(&right));
3522    }
3523    let left_real = left.as_f64().filter(|value| value.is_finite())?;
3524    let right_real = right.as_f64().filter(|value| value.is_finite())?;
3525    let signed_real = |integer: i64, real: f64| {
3526        if integer < 0 {
3527            compare_unsigned_integer_real(integer.unsigned_abs(), -real).reverse()
3528        } else {
3529            compare_unsigned_integer_real(integer as u64, real)
3530        }
3531    };
3532    if let Some(left) = left.as_i64() {
3533        Some(signed_real(left, right_real))
3534    } else if let Some(left) = left.as_u64() {
3535        Some(compare_unsigned_integer_real(left, right_real))
3536    } else if let Some(right) = right.as_i64() {
3537        Some(signed_real(right, left_real).reverse())
3538    } else if let Some(right) = right.as_u64() {
3539        Some(compare_unsigned_integer_real(right, left_real).reverse())
3540    } else {
3541        left_real.partial_cmp(&right_real)
3542    }
3543}
3544
3545fn compare_unsigned_integer_real(integer: u64, real: f64) -> std::cmp::Ordering {
3546    use std::cmp::Ordering;
3547
3548    if real < 0.0 {
3549        return Ordering::Greater;
3550    }
3551    // u64::MAX rounds to the exclusive upper bound 2^64 as f64. Check
3552    // before casting so a saturating conversion cannot make them equal.
3553    if real >= u64::MAX as f64 {
3554        return Ordering::Less;
3555    }
3556    match integer.cmp(&(real as u64)) {
3557        Ordering::Equal if real.fract() > 0.0 => Ordering::Less,
3558        order => order,
3559    }
3560}
3561
3562/// Rebuild the value of an untyped object. One unnamed property alone is the
3563/// whole object as JSON text. Otherwise each named property is one field.
3564///
3565/// An unnamed property beside named ones has no field name, so this writer
3566/// cannot place it. It goes to `unplaced` for the caller to report, and the
3567/// named fields still reach the output; dropping the whole object over one
3568/// positional token would lose every field beside it.
3569fn raw_bmopf_value(u: &crate::model::UntypedObject, unplaced: &mut Vec<String>) -> Option<Value> {
3570    if let [(None, text)] = u.props.as_slice() {
3571        return serde_json::from_str(text).ok();
3572    }
3573    let mut o = Map::new();
3574    for (key, text) in &u.props {
3575        let Some(key) = key.as_ref() else {
3576            unplaced.push(text.clone());
3577            continue;
3578        };
3579        let value = serde_json::from_str(text).unwrap_or_else(|_| Value::String(text.clone()));
3580        o.insert(key.clone(), value);
3581    }
3582    (!o.is_empty()).then_some(Value::Object(o))
3583}
3584
3585fn extras_number(extras: &crate::model::Extras, key: &str) -> Option<f64> {
3586    let v = extras.get(key)?;
3587    v.as_f64()
3588        .or_else(|| v.as_i64().map(|v| v as f64))
3589        .or_else(|| v.as_str().and_then(|s| s.parse().ok()))
3590        .filter(|v| v.is_finite())
3591}
3592
3593fn tap_values(v: &Value) -> Option<Vec<f64>> {
3594    if let Some(items) = v.as_array() {
3595        let out: Vec<f64> = items.iter().filter_map(value_number).collect();
3596        Some(out)
3597    } else {
3598        value_number(v).map(|tap| vec![tap])
3599    }
3600}
3601
3602fn value_number(v: &Value) -> Option<f64> {
3603    v.as_f64()
3604        .or_else(|| v.as_i64().map(|v| v as f64))
3605        .or_else(|| v.as_str().and_then(|s| s.parse().ok()))
3606        .filter(|v| v.is_finite())
3607}
3608
3609fn split_no_load_extras(t: &mut DistTransformer, phases: usize) {
3610    let phases = phases.max(1) as f64;
3611    for key in ["g_no_load", "b_no_load"] {
3612        if let Some(v) = extras_number(&t.extras, key) {
3613            t.extras.insert(key.into(), json!(v / phases));
3614        }
3615    }
3616}
3617
3618fn center_tap_common_terminal(w2: &DistWinding, w3: &DistWinding) -> String {
3619    w2.terminal_map
3620        .iter()
3621        .find(|term| w3.terminal_map.contains(term))
3622        .cloned()
3623        .unwrap_or_default()
3624}
3625
3626fn center_tap_to_winding(
3627    w2: &DistWinding,
3628    w3: &DistWinding,
3629    common: &str,
3630    s_rating: f64,
3631    r_neutral: Option<f64>,
3632    x_neutral: Option<f64>,
3633) -> DistWinding {
3634    let terminal_map = center_tap_terminal_map(w2, w3, common);
3635    DistWinding {
3636        bus: w2.bus.clone(),
3637        terminal_map,
3638        conn: DistWindingConn::Wye,
3639        v_ref: w2.v_ref,
3640        s_rating,
3641        r_pct: w2.r_pct,
3642        tap: w2.tap,
3643        r_neutral,
3644        x_neutral,
3645    }
3646}
3647
3648fn center_tap_terminal_map(w2: &DistWinding, w3: &DistWinding, common: &str) -> Vec<String> {
3649    let mut hots: Vec<String> = Vec::new();
3650    for term in w2.terminal_map.iter().chain(&w3.terminal_map) {
3651        if term != common && !hots.contains(term) {
3652            hots.push(term.clone());
3653        }
3654    }
3655    let first = hots.first().cloned().unwrap_or_default();
3656    let second = hots.get(1).cloned().unwrap_or_default();
3657    vec![first, common.to_string(), second]
3658}
3659
3660fn center_tap_star_percentages(xsc_pct: &[f64]) -> (f64, f64) {
3661    let xhl = xsc_pct.first().copied().unwrap_or(0.0);
3662    let xht = xsc_pct.get(1).copied().unwrap_or(xhl);
3663    let xlt = xsc_pct.get(2).copied().unwrap_or(0.0);
3664    ((xhl + xht - xlt) / 2.0, (xhl + xlt - xht) / 2.0)
3665}
3666
3667fn winding_base(w: &DistWinding) -> Option<f64> {
3668    base_impedance(w.v_ref, w.s_rating)
3669}
3670
3671/// Base impedance `v^2 / s` in ohms, or None when the rating gives the
3672/// percent quantities no base. Dividing by a rating that is not positive
3673/// yields an infinity, and `num` then emits that infinity as a zero: a
3674/// zero-resistance and, worse, a zero-reactance transformer reads as a short
3675/// circuit. The schema leaves every series impedance field optional, so the
3676/// caller drops the field instead, and an absent field reads as unknown.
3677fn base_impedance(v_ref: f64, s: f64) -> Option<f64> {
3678    powerio_core::electrical::calc_impedance_base(v_ref, s)
3679}
3680
3681/// The `delta_roll` of a DELTA winding: the one delta orientation
3682/// ([`crate::transformer::calc_delta_direction`]), so a unit that states no
3683/// roll writes the orientation it has (`+1` for a BMOPF n-winding unit, as
3684/// BMOPFTools defaults it) and reads back unchanged. `None` for a WYE
3685/// winding or an orientation the model cannot state.
3686fn bmopf_delta_roll(t: &DistTransformer, idx: usize, w: &DistWinding) -> Option<i64> {
3687    if w.conn != DistWindingConn::Delta {
3688        return None;
3689    }
3690    crate::transformer::calc_delta_direction(t, idx)
3691        .ok()
3692        .map(i64::from)
3693}
3694
3695/// The phase and neutral label lists, from the bus terminal names. The rule
3696/// is the one the schema prescribes for an absent `terminal_conventions`
3697/// block: an `n` or `N` label is neutral, every other label is a phase.
3698/// Add deterministic producer provenance without replacing source metadata:
3699/// the proposal commit, the SHA-256 of the exact schema bytes, and the
3700/// immutable permalink they were retrieved from (`schema_retrieval_url`;
3701/// `schema_upstream_url` is the same permalink, kept for readers of 0.11
3702/// output), beside the canonical identity `meta.$schema` carries.
3703fn proposal_provenance(meta: &mut Map<String, Value>) {
3704    let record = json!({
3705        "producer": "powerio", "producer_version": env!("CARGO_PKG_VERSION"),
3706        "schema_status": "proposal",
3707        "schema_commit": super::BMOPF_PROPOSAL_COMMIT,
3708        "schema_sha256": super::BMOPF_PROPOSAL_SHA256,
3709        "schema_id": super::BMOPF_SCHEMA_ID,
3710        "schema_retrieval_url": super::bmopf_proposal_url(),
3711        "schema_upstream_url": super::bmopf_proposal_url()
3712    });
3713    let provenance = meta.entry("provenance").or_insert_with(|| json!({}));
3714    let Some(provenance) = provenance.as_object_mut() else {
3715        return;
3716    };
3717    let mut index = 0;
3718    loop {
3719        let key = if index == 0 {
3720            "powerio_bmopf".to_owned()
3721        } else {
3722            format!("powerio_bmopf_{index}")
3723        };
3724        match provenance.get(&key) {
3725            Some(existing) if existing == &record => break,
3726            Some(_) => index += 1,
3727            None => {
3728                provenance.insert(key, record);
3729                break;
3730            }
3731        }
3732    }
3733}
3734
3735/// Labels keep first-seen order and case-sensitive identity. Each label
3736/// takes the role the one terminal classification
3737/// ([`crate::model::DistBus::terminal_role`], over the network's terminal
3738/// conventions: the CIM wire convention for a network read from CIM or
3739/// MG-RAVENS) gives it: neutral when it is a
3740/// neutral on any bus, else earth when it is earth on any bus, else phase.
3741/// The `earth` list is written only when some label is earth.
3742fn authored_terminal_conventions(net: &MulticonductorNetwork) -> Option<Value> {
3743    use crate::model::TerminalRole;
3744    let named = |role: TerminalRole| -> BTreeSet<&String> {
3745        net.buses()
3746            .iter()
3747            .flat_map(|bus| {
3748                bus.terminals
3749                    .iter()
3750                    .filter(move |name| bus.terminal_role(name, net.terminal_conventions()) == role)
3751            })
3752            .collect()
3753    };
3754    let (neutral_names, earth_names) = (named(TerminalRole::Neutral), named(TerminalRole::Earth));
3755    let mut phase = Vec::new();
3756    let mut neutral = Vec::new();
3757    let mut earth = Vec::new();
3758    for bus in net.buses() {
3759        for term in &bus.terminals {
3760            let labels = if neutral_names.contains(term) {
3761                &mut neutral
3762            } else if earth_names.contains(term) {
3763                &mut earth
3764            } else {
3765                &mut phase
3766            };
3767            if !labels.contains(&term) {
3768                labels.push(term);
3769            }
3770        }
3771    }
3772    if phase.is_empty() && neutral.is_empty() && earth.is_empty() {
3773        return None;
3774    }
3775    let mut conventions = json!({"phase": phase, "neutral": neutral});
3776    if !earth.is_empty() {
3777        conventions["earth"] = json!(earth);
3778    }
3779    Some(conventions)
3780}
3781
3782fn config_str(c: Configuration) -> &'static str {
3783    match c {
3784        Configuration::Wye => "WYE",
3785        Configuration::Delta => "DELTA",
3786        Configuration::SinglePhase => "SINGLE_PHASE",
3787    }
3788}
3789
3790/// The schema's token for a limit stated per unit of its base: `PU`. The
3791/// model's `VA_FRACTION` names the same unit.
3792fn unit_token(token: Value) -> Value {
3793    if token == "VA_FRACTION" {
3794        json!("PU")
3795    } else {
3796        token
3797    }
3798}
3799
3800/// Whether a breakpoint list never decreases.
3801fn non_decreasing(values: &[f64]) -> bool {
3802    values.iter().all(|v| v.is_finite()) && values.windows(2).all(|w| w[0] <= w[1])
3803}
3804
3805fn json_enum<T: serde::Serialize>(value: T) -> Value {
3806    serde_json::to_value(value).expect("enum serializes to a string")
3807}
3808
3809#[cfg(test)]
3810mod tests {
3811    use super::*;
3812    use crate::model::{DistLoadVoltageModel, IbrPrimeMover, IbrTopology};
3813    use crate::testkit::parse_bmopf_str;
3814
3815    #[test]
3816    fn pmd_time_series_normalization_requires_neutral_options() {
3817        let source = json!({
3818            "values": [1.0, 0.5],
3819            "time": [0.0, 60.0],
3820            "source_id": "loadshape.ls1",
3821            "offset": 0.0,
3822            "replace": false
3823        });
3824        let (profile, metadata) = normalized_bmopf_time_series(&source).unwrap();
3825        assert_eq!(profile, json!({"values": [1.0, 0.5], "time": [0.0, 60.0]}));
3826        assert_eq!(
3827            metadata,
3828            Some(json!({
3829                "source_id": "loadshape.ls1",
3830                "offset": 0.0,
3831                "replace": false
3832            }))
3833        );
3834
3835        assert!(
3836            normalized_bmopf_time_series(&json!({
3837                "values": [1.0],
3838                "offset": 0.25
3839            }))
3840            .is_none(),
3841            "a nonzero offset changes profile semantics"
3842        );
3843        assert!(
3844            normalized_bmopf_time_series(&json!({
3845                "values": [1.0],
3846                "replace": true
3847            }))
3848            .is_none(),
3849            "replace=true cannot be represented by a multiplicative profile"
3850        );
3851
3852        assert!(
3853            normalized_bmopf_time_series(&json!({
3854                "source_id": "loadshape.ls1",
3855                "values": [1.0],
3856                "time": [0.0],
3857                "offset": 0.0
3858            }))
3859            .is_none(),
3860            "an omitted replace on a PMD loadshape inherits PMD's true default"
3861        );
3862        assert!(
3863            normalized_bmopf_time_series(&json!({
3864                "values": [1.0],
3865                "time": [0.0]
3866            }))
3867            .is_some(),
3868            "a native BMOPF profile without PMD-only options remains multiplicative"
3869        );
3870        assert!(
3871            normalized_bmopf_time_series_for_source(
3872                &json!({"values": [0.5, 1.0], "time": [0.0, 1.0]}),
3873                true,
3874            )
3875            .is_none(),
3876            "PMD defaults replace to true even when optional metadata is absent"
3877        );
3878        assert!(
3879            normalized_bmopf_time_series_for_source(
3880                &json!({"values": [0.5, 1.0], "time": [0.0, 1.0], "replace": false}),
3881                true,
3882            )
3883            .is_some(),
3884            "PMD profiles activate only with explicit replace=false"
3885        );
3886        assert!(
3887            normalized_bmopf_time_series_for_source(
3888                &json!({"values": [0.5, 1.0], "time": [0.0, 1.0], "replace": true}),
3889                true,
3890            )
3891            .is_none(),
3892            "PMD replace=true cannot be represented by BMOPF multiplicative profiles"
3893        );
3894        assert!(
3895            normalized_bmopf_time_series(&json!({"time": [0.0, 1.0]})).is_none(),
3896            "BMOPF requires the schema-mandated values property"
3897        );
3898        assert!(
3899            normalized_bmopf_time_series(&json!({
3900                "values": [1.0],
3901                "unrecognized": "field"
3902            }))
3903            .is_none(),
3904            "unknown profile properties must not leak into strict BMOPF JSON"
3905        );
3906    }
3907
3908    #[test]
3909    fn pmd_time_axis_normalization_is_exact_and_rejects_overflow() {
3910        assert_eq!(
3911            normalize_bmopf_time_axis(&json!([0, 1, 24]), true),
3912            Some(json!([0, 3600, 86400]))
3913        );
3914        assert_eq!(
3915            normalize_bmopf_time_axis(&json!([0.5, 1.25]), true),
3916            Some(json!([1800.0, 4500.0]))
3917        );
3918        assert_eq!(
3919            normalize_bmopf_time_axis(&json!([0, 3600]), false),
3920            Some(json!([0, 3600]))
3921        );
3922        // Preserve exact integer seconds beyond f64's integer precision and
3923        // beyond i64::MAX when the converted result still fits in u64.
3924        let hours = 3_000_000_000_000_001_u64;
3925        assert_eq!(
3926            normalize_bmopf_time_axis(&json!([0, hours]), true),
3927            Some(json!([0, hours * 3_600]))
3928        );
3929        let native = json!([9_007_199_254_740_992_u64, 9_007_199_254_740_993_u64]);
3930        assert_eq!(normalize_bmopf_time_axis(&native, false), Some(native));
3931        let mixed = json!([9_007_199_254_740_992.0, 9_007_199_254_740_993_u64]);
3932        assert_eq!(normalize_bmopf_time_axis(&mixed, false), Some(mixed));
3933        assert_eq!(
3934            normalize_bmopf_time_axis(&json!([-1, 0, 1]), true),
3935            Some(json!([-3600, 0, 3600]))
3936        );
3937        assert!(normalize_bmopf_time_axis(&json!([i64::MIN]), true).is_none());
3938        assert!(normalize_bmopf_time_axis(&json!([1e308]), true).is_none());
3939        assert!(
3940            normalize_bmopf_time_axis(&json!([u64::MAX]), true).is_none(),
3941            "overflowing hour-to-second conversion must remain source-only"
3942        );
3943        assert!(
3944            normalize_bmopf_time_axis(&json!(["2026-01-01T00:00:00Z"]), true).is_none(),
3945            "timestamp axes have no numeric BMOPF representation"
3946        );
3947    }
3948
3949    #[test]
3950    fn pmd_time_axes_are_normalized_to_bmopf_numeric_seconds() {
3951        let numeric = json!({
3952            "values": [0.5, 1.0],
3953            "time": [0.0, 1.0],
3954            "replace": false
3955        });
3956        let normalized = normalized_bmopf_time_series_for_source(&numeric, true).unwrap();
3957        assert_eq!(normalized.0["time"], json!([0.0, 3600.0]));
3958
3959        let timestamps = json!({
3960            "values": [0.5, 1.0],
3961            "time": ["2026-01-01T00:00:00Z"],
3962            "replace": false
3963        });
3964        assert!(
3965            normalized_bmopf_time_series_for_source(&timestamps, true).is_none(),
3966            "string PMD axes must remain source-only"
3967        );
3968        assert!(
3969            normalized_bmopf_time_series(&timestamps).is_none(),
3970            "BMOPF time axes must be numeric for non-PMD sources too"
3971        );
3972    }
3973
3974    #[test]
3975    fn profile_step_comparison_keeps_exact_integer_identity() {
3976        for (left, right) in [
3977            (json!(0), json!(0.0)),
3978            (json!(3600), json!(3600.0)),
3979            (
3980                json!(9_007_199_254_740_992_u64),
3981                json!(9_007_199_254_740_992.0),
3982            ),
3983            (json!(i64::MIN), json!(i64::MIN as f64)),
3984        ] {
3985            assert!(same_time_step(&left, &right), "{left} != {right}");
3986            assert!(same_time_step(&right, &left), "{right} != {left}");
3987        }
3988        for (left, right) in [
3989            (json!(0), json!(0.5)),
3990            (
3991                json!(9_007_199_254_740_992_u64),
3992                json!(9_007_199_254_740_993_u64),
3993            ),
3994            (
3995                json!(9_007_199_254_740_993_u64),
3996                json!(9_007_199_254_740_992.0),
3997            ),
3998            (json!(i64::MAX), json!(i64::MAX as f64)),
3999            (json!(u64::MAX), json!(u64::MAX as f64)),
4000        ] {
4001            assert!(!same_time_step(&left, &right), "{left} == {right}");
4002            assert!(!same_time_step(&right, &left), "{right} == {left}");
4003        }
4004    }
4005
4006    /// A dropped field's diagnostic code must never claim the field was
4007    /// kept, and a kept-under-extras diagnostic must never claim the field
4008    /// was dropped. Exercises the writer's own field-dropped and
4009    /// retained-source-only call sites directly, since the two only differ
4010    /// by which paths trigger each one.
4011    #[test]
4012    fn dropped_and_retained_bmopf_diagnostics_do_not_contradict_their_own_message() {
4013        let mut w = Writer {
4014            warnings: crate::diagnostics::Diagnostics::new(),
4015            dropped_extras: BTreeMap::new(),
4016            time_series_profiles: BTreeMap::new(),
4017            geometry_embedded: false,
4018        };
4019
4020        // A non-object control_profile extra and an ibr extra outside the
4021        // allowed set both take the field-dropped path.
4022        let mut profile = DistControlProfile::new("cp1");
4023        profile.extras.insert("weird".into(), json!(42));
4024        w.control_profile(&profile);
4025
4026        let mut ibr = DistIbr::new(
4027            "pv1",
4028            "b1",
4029            vec!["1".into(), "2".into(), "3".into()],
4030            IbrTopology::ThreeLeg,
4031            IbrPrimeMover::Pv,
4032            vec![1.0, 1.0, 1.0],
4033        );
4034        ibr.extras.insert("not_a_schema_field".into(), json!(1));
4035        w.ibr(&ibr);
4036
4037        // A time series profile BMOPF cannot represent takes the
4038        // retained-under-extras path.
4039        let mut extras = Map::new();
4040        w.normalize_time_series_for_emit("ts1", json!({"values": [1.0]}), &mut extras);
4041
4042        let records = w.warnings.records();
4043        let dropped: Vec<_> = records
4044            .iter()
4045            .filter(|d| d.code() == "EMIT.BMOPF.FIELD_DROPPED")
4046            .collect();
4047        let retained: Vec<_> = records
4048            .iter()
4049            .filter(|d| d.code() == "EMIT.BMOPF.RETAINED_SOURCE_ONLY")
4050            .collect();
4051        assert!(!dropped.is_empty(), "{records:?}");
4052        assert!(!retained.is_empty(), "{records:?}");
4053        for d in dropped {
4054            assert!(
4055                !d.message().contains("kept under extras"),
4056                "FIELD_DROPPED message claims the field was kept: {}",
4057                d.message()
4058            );
4059        }
4060        for d in retained {
4061            assert!(
4062                !d.message().contains("dropped"),
4063                "RETAINED_SOURCE_ONLY message claims the field was dropped: {}",
4064                d.message()
4065            );
4066        }
4067    }
4068
4069    #[test]
4070    fn load_voltage_models_round_trip_through_bmopf() {
4071        let text = r#"{
4072            "bus": {
4073                "b1": {"terminal_names": ["1", "2", "3", "4"], "perfectly_grounded_terminals": ["4"]}
4074            },
4075            "voltage_source": {
4076                "source": {
4077                    "bus": "b1", "terminal_map": ["1", "2", "3", "4"],
4078                    "v_magnitude": [7200.0, 7200.0, 7200.0, 0.0],
4079                    "v_angle": [0.0, -120.0, 120.0, 0.0]
4080                }
4081            },
4082            "load": {
4083                "zip": {
4084                    "bus": "b1", "terminal_map": ["1", "2", "3", "4"],
4085                    "configuration": "WYE", "p_nom": [1.0, 2.0, 3.0], "q_nom": [0.1, 0.2, 0.3],
4086                    "model": "zip", "v_nom": [7200.0, 7200.0, 7200.0],
4087                    "alpha_z": [0.2, 0.2, 0.2], "alpha_i": [0.3, 0.3, 0.3], "alpha_p": [0.5, 0.5, 0.5],
4088                    "beta_z": [0.1, 0.1, 0.1], "beta_i": [0.4, 0.4, 0.4], "beta_p": [0.5, 0.5, 0.5]
4089                },
4090                "exp": {
4091                    "bus": "b1", "terminal_map": ["1", "2", "3", "4"],
4092                    "configuration": "WYE", "p_nom": [1.0, 1.0, 1.0], "q_nom": [0.0, 0.0, 0.0],
4093                    "model": "exponential", "v_nom": [7200.0, 7200.0, 7200.0],
4094                    "gamma_p": [1.2, 1.2, 1.2], "gamma_q": [2.1, 2.1, 2.1]
4095                }
4096            }
4097        }"#;
4098        let net = parse_bmopf_str(text).unwrap();
4099        let zip = net.loads().iter().find(|l| l.name == "zip").unwrap();
4100        let exp = net.loads().iter().find(|l| l.name == "exp").unwrap();
4101        assert!(matches!(
4102            &zip.voltage_model,
4103            DistLoadVoltageModel::Zip { alpha_z, .. } if alpha_z == &vec![0.2, 0.2, 0.2]
4104        ));
4105        assert!(matches!(
4106            &exp.voltage_model,
4107            DistLoadVoltageModel::Exponential { gamma_q, .. } if gamma_q == &vec![2.1, 2.1, 2.1]
4108        ));
4109
4110        let out = emit_bmopf_json_text(&net);
4111        assert!(
4112            out.render_diagnostics().is_empty(),
4113            "{:?}",
4114            out.render_diagnostics()
4115        );
4116        let v: Value = serde_json::from_str(&out.text).unwrap();
4117        assert_eq!(
4118            v["load"]["zip"]["alpha_i"],
4119            serde_json::json!([0.3, 0.3, 0.3])
4120        );
4121        assert_eq!(
4122            v["load"]["exp"]["gamma_p"],
4123            serde_json::json!([1.2, 1.2, 1.2])
4124        );
4125    }
4126
4127    /// A model built without the reader caps must not force quadratic
4128    /// allocation out of linear-size input.
4129    #[test]
4130    fn oversized_model_dimensions_are_clamped_not_expanded() {
4131        use crate::model::{
4132            DistLineCode, DistShunt, DistTransformer, DistWinding, DistWindingConn,
4133        };
4134
4135        let mut net = crate::model::MulticonductorNetwork::default();
4136        // A linecode whose R rows imply a huge dimension while X is empty
4137        // would materialize dim x dim zeros for X.
4138        let mut lc = DistLineCode::new("big", Vec::new(), Vec::new());
4139        lc.r_series = vec![Vec::new(); 100_000];
4140        net.line_codes_mut().push(lc);
4141        // Same shape for a shunt's G/B pair.
4142        net.shunts_mut().push(DistShunt::new(
4143            "big",
4144            "b",
4145            Vec::new(),
4146            vec![Vec::new(); 100_000],
4147            Vec::new(),
4148        ));
4149        // A winding count beyond the cap would expand to ~n²/2 x_sc pairs.
4150        let winding = DistWinding::new("b", Vec::new(), DistWindingConn::Wye, 1.0, 1.0);
4151        net.transformers_mut().push(DistTransformer::new(
4152            "many",
4153            vec![winding; MAX_DIM + 6],
4154            Vec::new(),
4155            3,
4156        ));
4157
4158        let out = emit_bmopf_json_text(&net);
4159        let v: Value = serde_json::from_str(&out.text).unwrap();
4160        let count_keys = |m: &Value, prefix: &str| {
4161            m.as_object()
4162                .unwrap()
4163                .keys()
4164                .filter(|k| k.starts_with(prefix))
4165                .count()
4166        };
4167        assert_eq!(
4168            count_keys(&v["linecode"]["big"], "X_series_"),
4169            MAX_DIM * MAX_DIM
4170        );
4171        assert_eq!(count_keys(&v["shunt"]["big"], "B_"), MAX_DIM * MAX_DIM);
4172        assert_eq!(
4173            v["transformer"]["n_winding"]["many"]["x_sc"]
4174                .as_object()
4175                .unwrap()
4176                .len(),
4177            MAX_DIM * (MAX_DIM - 1) / 2
4178        );
4179        assert!(
4180            out.render_diagnostics()
4181                .iter()
4182                .any(|w| w.contains("exceeds the supported maximum")),
4183            "{:?}",
4184            out.render_diagnostics()
4185        );
4186    }
4187}