Skip to main content

powerio_dist/dss/
write.rs

1//! [`MulticonductorNetwork`] into OpenDSS `.dss` text.
2//!
3//! The canonical writer regenerates a solvable case from the typed model:
4//! a `Clear`/`Set DefaultBaseFrequency` header, the circuit with its
5//! source, linecodes in meters, elements with explicit bus dots (a
6//! terminal in the bus's perfectly grounded set emits as node 0, the exact
7//! inverse of the reader's materialization), the source `Set` options the
8//! writer does not derive itself, `Set VoltageBases`, `Calcvoltagebases`,
9//! and `Solve`. Element extras whose keys appear in the class property
10//! tables emit verbatim; everything else is reported.
11//!
12//! Floats print through Rust's shortest round trip formatting; OpenDSS
13//! reads the full precision back.
14
15use std::borrow::Cow;
16use std::collections::{BTreeMap, BTreeSet};
17use std::fmt::Write as _;
18
19use crate::convert::{TextEmission, TextSidecar};
20use crate::diagnostics::codes as C;
21use crate::model::{
22    ActivePowerReference, ConductorMatrix, Configuration, ControlVoltageReference, DistBus,
23    DistControlProfile, DistIbr, DistLineCode, DistLoad, DistLoadVoltageModel, DistTransformer,
24    DistWinding, DistWindingConn, Extras, IbrPrimeMover, IbrTopology, IbrVoltageAggregation,
25    MulticonductorNetwork, ReactivePowerReference, VoltVarControl, VoltWattControl,
26};
27
28use super::read::delta_edges;
29use super::{lex, prop};
30
31mod admittance_shunts;
32mod asymmetric_pair;
33mod common_return_shunts;
34mod current_form;
35mod ideal_switches;
36mod ideal_transformers;
37mod loads;
38mod safe_names;
39mod sources;
40mod storage;
41mod terminal_voltage;
42mod thevenin;
43
44/// Options for canonical OpenDSS output.
45#[derive(Clone, Debug, PartialEq)]
46#[non_exhaustive]
47pub struct DssEmitOptions {
48    /// Default voltage validity band emitted on loads that do not already
49    /// carry `vminpu` / `vmaxpu` extras.
50    pub default_load_voltage_bounds: Option<DssLoadVoltageBounds>,
51    /// Relative companion file named by the emitted `Buscoords` command.
52    /// `None` drops typed bus locations with a warning.
53    pub buscoords_filename: Option<String>,
54}
55
56impl Default for DssEmitOptions {
57    fn default() -> Self {
58        Self {
59            default_load_voltage_bounds: Some(DssLoadVoltageBounds::default()),
60            buscoords_filename: Some("buscoords.csv".to_owned()),
61        }
62    }
63}
64
65/// OpenDSS per unit load voltage validity band.
66#[derive(Clone, Copy, Debug, PartialEq)]
67#[non_exhaustive]
68pub struct DssLoadVoltageBounds {
69    pub vminpu: f64,
70    pub vmaxpu: f64,
71}
72
73impl Default for DssLoadVoltageBounds {
74    fn default() -> Self {
75        Self {
76            vminpu: 0.0,
77            vmaxpu: 2.0,
78        }
79    }
80}
81
82/// Emits canonical `.dss` text from the model.
83#[cfg(test)]
84pub(crate) fn emit_dss_text(net: &MulticonductorNetwork) -> TextEmission {
85    emit_dss_text_with_options(net, &DssEmitOptions::default())
86}
87
88/// Emits canonical `.dss` text from the model with explicit options.
89#[cfg(test)]
90pub(crate) fn emit_dss_text_with_options(
91    net: &MulticonductorNetwork,
92    options: &DssEmitOptions,
93) -> TextEmission {
94    emit_snapshot(net, options)
95}
96
97/// Validate the network as written, then emit it. The names dss cannot carry
98/// are replaced once; their findings go out with the emission.
99pub(crate) fn emit_validated_dss_text(
100    net: &MulticonductorNetwork,
101    options: &DssEmitOptions,
102) -> Result<TextEmission, powerio_core::Error> {
103    let mut warnings = crate::diagnostics::Diagnostics::new();
104    let net = safe_names::apply(net, &mut warnings);
105    validate_renamed(net.as_ref())?;
106    Ok(emit_renamed(net.as_ref(), warnings, options))
107}
108
109#[cfg(test)]
110pub(crate) fn validate_emission(net: &MulticonductorNetwork) -> Result<(), powerio_core::Error> {
111    // Validate the network as written: with the names dss cannot carry
112    // replaced, a bus id such as `Node 1` is representable. The replacement
113    // findings are recorded again when the writer runs.
114    let mut replacements = crate::diagnostics::Diagnostics::new();
115    let net = safe_names::apply(net, &mut replacements);
116    validate_renamed(net.as_ref())
117}
118
119/// Validate a network whose names are already the ones dss will carry.
120fn validate_renamed(net: &MulticonductorNetwork) -> Result<(), powerio_core::Error> {
121    sources::validate(net)
122        .map_err(|message| powerio_core::Error::new(&C::BUILD_DIST_ELECTRICAL_INCOMPLETE, message))
123}
124
125#[cfg(test)]
126fn emit_snapshot(net: &MulticonductorNetwork, options: &DssEmitOptions) -> TextEmission {
127    let mut warnings = crate::diagnostics::Diagnostics::new();
128    let net = safe_names::apply(net, &mut warnings);
129    emit_renamed(net.as_ref(), warnings, options)
130}
131
132/// Emit a network whose names are already the ones dss will carry, with the
133/// findings recorded so far leading the emission's own.
134fn emit_renamed(
135    net: &MulticonductorNetwork,
136    warnings: crate::diagnostics::Diagnostics,
137    options: &DssEmitOptions,
138) -> TextEmission {
139    let mut w = DssWriter {
140        out: String::new(),
141        sidecars: Vec::new(),
142        warnings,
143        options: options.clone(),
144        grounded: net
145            .buses()
146            .iter()
147            .map(|b| (b.id.to_ascii_lowercase(), b.grounded.clone()))
148            .collect(),
149        terminals: net
150            .buses()
151            .iter()
152            .map(|b| (b.id.to_ascii_lowercase(), b.terminals.clone()))
153            .collect(),
154        kv_estimate: estimate_bus_kv(net),
155        terminal_kv: terminal_voltage::estimate(net),
156        native_source_line: None,
157        native_source_code: None,
158    };
159    w.network(net);
160    TextEmission::new(w.out, w.sidecars, w.warnings)
161}
162
163#[cfg(test)]
164pub(super) fn emit_staged_sources(net: &MulticonductorNetwork) -> Result<TextEmission, String> {
165    sources::validate(net)?;
166    Ok(emit_snapshot(net, &DssEmitOptions::default()))
167}
168
169struct DssWriter {
170    out: String,
171    sidecars: Vec<TextSidecar>,
172    warnings: crate::diagnostics::Diagnostics,
173    options: DssEmitOptions,
174    /// Bus id (lowercase) → perfectly grounded terminal names.
175    grounded: BTreeMap<String, Vec<String>>,
176    /// Bus id (lowercase) → ordered terminal names.
177    terminals: BTreeMap<String, Vec<String>>,
178    /// Bus id (lowercase) → phase to neutral voltage estimate, volts.
179    kv_estimate: BTreeMap<String, f64>,
180    terminal_kv: terminal_voltage::TerminalVoltages,
181    native_source_line: Option<String>,
182    native_source_code: Option<String>,
183}
184
185#[derive(Clone, Copy)]
186struct ElementKv<'a> {
187    bus: &'a str,
188    phases: usize,
189    configuration: Configuration,
190    name: &'a str,
191    class: &'a str,
192    typed_kv: Option<f64>,
193}
194
195/// Phase to neutral voltage per bus, propagated from the sources through
196/// lines and switches (same level) and transformers (winding ratios). The
197/// estimate feeds load/capacitor `kv` and `Set VoltageBases` when the
198/// source format did not carry them.
199///
200/// Seeds follow the current typed source magnitudes. Retained source tokens
201/// must not override edits to those constraints. Transformer ratios use the
202/// voltage values reconstructed from emitted winding ratings.
203fn estimate_bus_kv(net: &MulticonductorNetwork) -> BTreeMap<String, f64> {
204    let mut kv: BTreeMap<String, f64> = BTreeMap::new();
205    for vs in net.sources() {
206        let vln = vs.v_magnitude.iter().copied().fold(0.0_f64, f64::max);
207        if vln > 0.0 {
208            kv.insert(vs.bus.to_ascii_lowercase(), vln);
209        }
210    }
211    // Per bus grounded terminal sets, to tell a line to neutral winding (a
212    // terminal tied to ground in its map) from a line to line one. Grounding
213    // and the terminal map both survive a BMOPF round trip, the wye/delta
214    // label does not, so this is what the transformer ratio keys on below.
215    let grounded: BTreeMap<String, &Vec<String>> = net
216        .buses()
217        .iter()
218        .map(|b| (b.id.to_ascii_lowercase(), &b.grounded))
219        .collect();
220    for _ in 0..net.buses().len() {
221        let mut changed = false;
222        for l in net.lines() {
223            let (f, t) = (
224                l.bus_from.to_ascii_lowercase(),
225                l.bus_to.to_ascii_lowercase(),
226            );
227            match (kv.get(&f).copied(), kv.get(&t).copied()) {
228                (Some(v), None) => {
229                    kv.insert(t, v);
230                    changed = true;
231                }
232                (None, Some(v)) => {
233                    kv.insert(f, v);
234                    changed = true;
235                }
236                _ => {}
237            }
238        }
239        for s in net.switches() {
240            let (f, t) = (
241                s.bus_from.to_ascii_lowercase(),
242                s.bus_to.to_ascii_lowercase(),
243            );
244            match (kv.get(&f).copied(), kv.get(&t).copied()) {
245                (Some(v), None) => {
246                    kv.insert(t, v);
247                    changed = true;
248                }
249                (None, Some(v)) => {
250                    kv.insert(f, v);
251                    changed = true;
252                }
253                _ => {}
254            }
255        }
256        for t in net.transformers() {
257            // Propagate by winding voltage ratio from any known winding bus.
258            // The bus map holds phase to neutral voltages, so each winding's
259            // v_ref is first reduced to that base. A winding's rating is the
260            // voltage across its two terminals: line to line when both are
261            // phases (a polyphase winding, or a single phase delta leg), line
262            // to neutral when one terminal is the bus's grounded neutral.
263            // Matched windings (wye-wye, three phase wye-delta) cancel the
264            // factor; only a mixed open delta leg (single phase wye to delta)
265            // shifts, where the old raw ratio was a sqrt(3) off.
266            let pn = |w: &DistWinding| {
267                let v = (w.v_ref / 1e3) * 1e3;
268                if winding_is_line_to_neutral(t.phases, w, |b| {
269                    grounded.get(b).map(|g| g.as_slice())
270                }) {
271                    v
272                } else {
273                    crate::electrical::calc_wye_phase_voltage(v)
274                }
275            };
276            let known: Option<(usize, f64)> = t
277                .windings
278                .iter()
279                .enumerate()
280                .find_map(|(i, w)| kv.get(&w.bus.to_ascii_lowercase()).map(|v| (i, *v)));
281            if let Some((i, v_known)) = known {
282                let pn_known = pn(&t.windings[i]);
283                if pn_known > 0.0 {
284                    for (j, w) in t.windings.iter().enumerate() {
285                        if j != i && !kv.contains_key(&w.bus.to_ascii_lowercase()) {
286                            kv.insert(w.bus.to_ascii_lowercase(), v_known * pn(w) / pn_known);
287                            changed = true;
288                        }
289                    }
290                }
291            }
292        }
293        if !changed {
294            break;
295        }
296    }
297    kv
298}
299
300/// A float in the shortest form Rust round trips. Negative zero canonicalizes
301/// to `0` so a `-x/denom` that lands on `-0.0` does not emit the literal `-0`.
302/// Whether a winding's voltage sits line to neutral rather than line to line:
303/// a single phase transformer whose winding lands on a grounded terminal of
304/// its bus. Both the bus voltage estimate and the `kv=` token derived from it
305/// read this rule, and they have to read the same one — a sqrt(3) disagreement
306/// between them emits a wrong `kv` with nothing to flag it.
307fn winding_is_line_to_neutral<'g>(
308    phases: usize,
309    w: &DistWinding,
310    grounded: impl Fn(&str) -> Option<&'g [String]>,
311) -> bool {
312    phases < 2
313        && grounded(&w.bus.to_ascii_lowercase())
314            .is_some_and(|g| w.terminal_map.iter().any(|tm| g.contains(tm)))
315}
316
317/// Whether a value states a usable magnitude: a rating, a voltage, or an
318/// ampacity a deck can carry. OpenDSS has no token for a nonfinite number, and
319/// a zero or negative one is not a nameplate. Every recovery differs — omit the
320/// property, derive from the bus estimate, drop the object — so this is the
321/// shared question, not the shared answer.
322fn is_positive_finite(v: f64) -> bool {
323    v.is_finite() && v > 0.0
324}
325
326/// The conductor count a dss element declares for `phases` on `conn`. A three
327/// phase delta has no neutral conductor; every other connection carries one.
328fn nconds_for(conn: &str, phases: usize) -> usize {
329    if conn == "delta" && phases == 3 {
330        phases
331    } else {
332        phases + 1
333    }
334}
335
336/// Drop the extras the emitted record already states in its own tokens, so
337/// `extras_tail` cannot write a second, stale copy of one.
338fn strip_emitted_extras(extras: &mut Extras, keys: &[&str]) {
339    for key in keys {
340        extras.remove(*key);
341    }
342}
343
344fn num(v: f64) -> String {
345    let v = if v == 0.0 { 0.0 } else { v };
346    format!("{v}")
347}
348
349/// Write one per-winding transformer property. The inline `(...)` form needs
350/// a token in every slot. A missing value thus moves the property to the
351/// per-winding `~ wdg=` edits, which can omit a winding.
352fn winding_array(
353    head: &mut String,
354    edits: &mut [String],
355    array_key: &str,
356    scalar_key: &str,
357    values: &[Option<f64>],
358) {
359    if values.iter().all(Option::is_some) {
360        let toks: Vec<String> = values.iter().map(|v| num(v.unwrap_or(0.0))).collect();
361        let _ = write!(head, " {array_key}=({})", toks.join(", "));
362    } else {
363        for (edit, v) in edits.iter_mut().zip(values) {
364            if let Some(v) = v {
365                let _ = write!(edit, " {scalar_key}={}", num(*v));
366            }
367        }
368    }
369}
370
371/// An extra as a number: the reader stashes written tokens as strings and
372/// materialized defaults as numbers.
373fn extras_f64(extras: &Extras, key: &str) -> Option<f64> {
374    let v = extras.get(key)?;
375    v.as_f64()
376        .or_else(|| v.as_str().and_then(|s| s.parse().ok()))
377        // A stashed `inf`/`NaN` token parses to a non-finite f64; reject it so
378        // it never reaches `num()` and emits a literal `inf`/`NaN` DSS token.
379        .filter(|f| f.is_finite())
380}
381
382fn extras_usize(extras: &Extras, key: &str) -> Option<usize> {
383    let v = extras.get(key)?;
384    v.as_u64()
385        .and_then(|u| usize::try_from(u).ok())
386        .or_else(|| v.as_str().and_then(|s| s.parse().ok()))
387        .or_else(|| {
388            v.as_f64()
389                .filter(|f| f.fract() == 0.0 && *f >= 0.0)
390                .map(|f| f as usize)
391        })
392}
393
394fn zipv_cutoff(value: Option<&serde_json::Value>) -> Option<f64> {
395    let text = value?.as_str()?;
396    lex::Value::new(text)
397        .to_vector(None)
398        .ok()
399        .and_then(|v| v.get(6).copied())
400        .filter(|v| v.is_finite())
401}
402
403/// Whether the dss tokenizer would split this name: its delimiters, quote
404/// pair characters, comment openers, and (in bus ids) the node dot.
405fn name_breaks_dss(name: &str, is_bus_id: bool) -> bool {
406    name.contains("//")
407        || name.chars().any(|c| {
408            // A line terminator does not shift a token, it ends the command
409            // and makes the rest of the name parse as a new dss object.
410            matches!(
411                c,
412                ' ' | '\t'
413                    | '\n'
414                    | '\r'
415                    | ','
416                    | '='
417                    | '!'
418                    | '"'
419                    | '\''
420                    | '('
421                    | ')'
422                    | '['
423                    | ']'
424                    | '{'
425                    | '}'
426            ) || (is_bus_id && c == '.')
427        })
428}
429
430/// A `key=value` value as dss text. A value the lexer scans back as one
431/// bare token emits bare; anything else wraps in the first quote pair
432/// whose closer is absent from the value. The lexer honors all five pairs,
433/// and its quoted scan runs to the closer without checking delimiters or
434/// comment openers, so the wrapper protects spaces, commas, `=`, `!`, and
435/// `//`. The choice depends only on the value: the reader strips the
436/// wrapper, so the next write sees the bare value and picks the same form.
437/// `false` means nothing reparses to the value — every closer appears in
438/// it and bare scanning splits it — and the caller must warn.
439pub(crate) fn dss_value_out(value: &str) -> (String, bool) {
440    // An empty value is never bare representable: `key=` makes the lexer
441    // eat the next token as the value. `()` strips back to the empty string.
442    if value.is_empty() {
443        return ("()".to_string(), true);
444    }
445    let mut scan = lex::Scanner::new(value, None);
446    let bare = scan.next_param().is_some_and(|p| {
447        p.name.is_none() && !p.value.quoted && p.value.text == value && scan.next_param().is_none()
448    });
449    if bare {
450        return (value.to_string(), true);
451    }
452    for (open, close) in [('(', ')'), ('[', ']'), ('{', '}'), ('"', '"'), ('\'', '\'')] {
453        if !value.contains(close) {
454            return (format!("{open}{value}{close}"), true);
455        }
456    }
457    (value.to_string(), false)
458}
459
460/// First row (self, mutual) of a series matrix extra, without consuming it.
461fn seq_parts(extras: &Extras, key: &str) -> Option<(f64, f64)> {
462    let row = extras.get(key)?.as_array()?.first()?.as_array()?;
463    let self_v = row.first()?.as_f64()?;
464    let mutual = row
465        .get(1)
466        .and_then(serde_json::Value::as_f64)
467        .unwrap_or(0.0);
468    Some((self_v, mutual))
469}
470
471impl DssWriter {
472    fn warn(&mut self, info: &'static crate::diagnostics::DiagnosticInfo, msg: impl Into<String>) {
473        self.warnings.push(info, msg);
474    }
475
476    /// The engine's bus fill rule gives every conductor the dot list does
477    /// not cover a default — nodes 1..=phases for the phase conductors,
478    /// ground for the rest — so a map shorter than the class's conductor
479    /// count comes back from a reparse one grounded neutral longer. The
480    /// first write of such a model is not a fixed point; the second is.
481    /// A map longer than the count is the more serious direction: dss reads
482    /// the node list positionally and drops what the record cannot address.
483    fn warn_map_arity(&mut self, class: &str, name: &str, map_len: usize, nconds: usize) {
484        if map_len < nconds {
485            self.warn(
486                &C::EMIT_DSS_VALUE_COLLAPSED,
487                format!(
488                    "{class} {name}: terminal map lists {map_len} of {nconds} conductors; \
489                 dss materializes a grounded neutral terminal and the reparsed model \
490                 gains one"
491                ),
492            );
493        } else if map_len > nconds {
494            self.warn(
495                &C::EMIT_DSS_VALUE_COLLAPSED,
496                format!(
497                    "{class} {name}: terminal map lists {map_len} conductors but the record \
498                 addresses {nconds}; dss discards the last {} and the model loses them",
499                    map_len - nconds
500                ),
501            );
502        }
503    }
504
505    /// The position of the bus's grounded terminal in `map`, when the bus
506    /// grounds exactly one terminal the map lists. dss reads a node list
507    /// positionally, so this conductor belongs last.
508    fn return_terminal_index(&self, bus: &str, map: &[String]) -> Option<usize> {
509        let grounded = self.grounded.get(&bus.to_ascii_lowercase())?;
510        let mut found = map
511            .iter()
512            .enumerate()
513            .filter(|(_, t)| grounded.contains(*t));
514        let (idx, _) = found.next()?;
515        found.next().is_none().then_some(idx)
516    }
517
518    /// The conductor index of a line or switch's unique grounded return when
519    /// it sits before the end and the endpoints agree on it (a conductor is
520    /// one wire, so both maps and every conductor indexed matrix move by the
521    /// same permutation). `None` when no reorder applies or the endpoints
522    /// disagree — the plain order warning stands for those.
523    fn endpoint_return_index(
524        &self,
525        bus_from: &str,
526        map_from: &[String],
527        bus_to: &str,
528        map_to: &[String],
529    ) -> Option<usize> {
530        let n = map_from.len();
531        if map_to.len() != n {
532            return None;
533        }
534        let from = self.return_terminal_index(bus_from, map_from);
535        let to = self.return_terminal_index(bus_to, map_to);
536        let k = match (from, to) {
537            (Some(a), Some(b)) if a == b => a,
538            (Some(a), None) => a,
539            (None, Some(b)) => b,
540            _ => return None,
541        };
542        (k + 1 != n).then_some(k)
543    }
544
545    /// The node list with its unique grounded return moved last, when it
546    /// sits elsewhere: dss reads a node list positionally with the return
547    /// last, and the classes that call this carry no per conductor data into
548    /// the record, so the reorder renames nothing. The reorder is declared.
549    /// Lines and switches must not call this — they index impedance matrices
550    /// by these maps, and use the paired permutation instead.
551    fn return_last(&mut self, class: &str, name: &str, bus: &str, map: &[String]) -> Vec<String> {
552        let Some(index) = self.return_terminal_index(bus, map) else {
553            return map.to_vec();
554        };
555        if index + 1 == map.len() {
556            return map.to_vec();
557        }
558        let mut reordered = map.to_vec();
559        let terminal = reordered.remove(index);
560        self.warn(
561            &C::EMIT_DSS_VALUE_SUBSTITUTED,
562            format!(
563                "{class} {name} on bus {bus}: grounded return `{terminal}` moved last in \
564                 the node list; dss reads the list positionally and this record carries \
565                 no per conductor data to keep in step"
566            ),
567        );
568        reordered.push(terminal);
569        reordered
570    }
571
572    /// Report a positional node list whose unique grounded return is not
573    /// last. The diagnostic is intentionally separate from [`Self::bus_ref`]:
574    /// lines and switches index their impedance matrices by these maps, so a
575    /// map-only repair would silently relabel their electrical data.
576    fn warn_terminal_order(
577        &mut self,
578        class: &str,
579        name: &str,
580        bus: &str,
581        endpoint: Option<&str>,
582        map: &[String],
583    ) {
584        let Some(index) = self.return_terminal_index(bus, map) else {
585            return;
586        };
587        if index + 1 == map.len() {
588            return;
589        }
590
591        let terminal = &map[index];
592        let position = index + 1;
593        let endpoint_text = endpoint.map_or(String::new(), |value| format!(" {value}"));
594        let mut details = serde_json::Map::new();
595        details.insert("class".into(), serde_json::json!(class));
596        details.insert("element_name".into(), serde_json::json!(name));
597        details.insert("bus".into(), serde_json::json!(bus));
598        if let Some(endpoint) = endpoint {
599            details.insert("endpoint".into(), serde_json::json!(endpoint));
600        }
601        details.insert("grounded_terminal".into(), serde_json::json!(terminal));
602        details.insert("position".into(), serde_json::json!(position));
603        details.insert("terminal_count".into(), serde_json::json!(map.len()));
604
605        let mut diagnostic = crate::diagnostics::Diagnostic::of(
606            &C::EMIT_DSS_TERMINAL_ORDER_UNREPRESENTABLE,
607            format!(
608                "{class} {name}{endpoint_text} on bus {bus}: grounded terminal `{terminal}` \
609                 is at 1-based position {position} of {}; dss requires the grounded return \
610                 last",
611                map.len()
612            ),
613        )
614        .with_details(details)
615        .expect("writer-built details stay within the record bounds");
616        crate::diagnostics::attach_target(&mut diagnostic, format!("{class} {name}"));
617        self.warnings.record(diagnostic);
618    }
619
620    fn line_out(&mut self, s: &str) {
621        self.out.push_str(s);
622        self.out.push('\n');
623    }
624
625    fn check_name(&mut self, class: &str, name: &str) {
626        if name_breaks_dss(name, false) {
627            self.warn(
628                &C::EMIT_DSS_VALUE_SUBSTITUTED,
629                format!(
630                    "{class} `{name}`: name contains characters dss cannot represent; \
631                 output will not reparse identically"
632                ),
633            );
634        }
635    }
636
637    /// `bus.1.2.0` syntax: terminals in the bus's perfectly grounded set
638    /// emit as node 0, the inverse of the reader's neutral naming. dss
639    /// nodes are positional integers, so a non numeric terminal name emits
640    /// as its 1 based position on the bus (the element map position when
641    /// the bus does not list it), reported, keeping the conductor structure
642    /// intact across the trip.
643    fn bus_ref(&mut self, bus: &str, map: &[String]) -> String {
644        let key = bus.to_ascii_lowercase();
645        if name_breaks_dss(bus, true) {
646            self.warn(
647                &C::EMIT_DSS_VALUE_SUBSTITUTED,
648                format!(
649                    "bus `{bus}`: id contains characters dss cannot represent; \
650                 output will not reparse identically"
651                ),
652            );
653        }
654        let grounded = self.grounded.get(&key).cloned();
655        let terminals = self.terminals.get(&key).cloned().unwrap_or_default();
656        let nodes: Vec<String> = map
657            .iter()
658            .enumerate()
659            .map(|(i, t)| {
660                if grounded.as_ref().is_some_and(|g| g.contains(t)) {
661                    "0".to_string()
662                } else if t.parse::<u32>().is_ok() {
663                    t.clone()
664                } else {
665                    let pos = terminals.iter().position(|x| x == t).unwrap_or(i) + 1;
666                    self.warn(
667                        &C::EMIT_DSS_VALUE_SUBSTITUTED,
668                        format!(
669                            "bus {bus}: terminal `{t}` is not a dss node number; \
670                         emitted as node {pos}, its position on the bus"
671                        ),
672                    );
673                    pos.to_string()
674                }
675            })
676            .collect();
677        if nodes.is_empty() {
678            bus.to_string()
679        } else {
680            format!("{bus}.{}", nodes.join("."))
681        }
682    }
683
684    /// Extras whose keys are dss properties of `class` emit as written;
685    /// the rest are reported per key.
686    fn extras_tail(&mut self, class: &str, name: &str, extras: &Extras) -> String {
687        let table = prop::class_by_name(class);
688        let mut tail = String::new();
689        for (key, value) in extras {
690            if matches!(
691                key.as_str(),
692                "bmopf_subtype"
693                    | "dss_autotrans_original"
694                    | "dss_autotrans_banks"
695                    | "dss_autotrans_contacts"
696            ) || key.starts_with("pmd_")
697            {
698                continue; // converter bookkeeping
699            }
700            // Load spectra are consulted only in non-fundamental harmonic
701            // mode (pinned Load.CalcLoadModelContribution), not power flow.
702            if class == "load" && key == "spectrum" {
703                self.warn(&C::EMIT_DSS_EXTRAS_DROPPED, format!(
704                    "load {name}: harmonic spectrum reference omitted from the static snapshot; its definition is not regenerated"
705                ));
706                continue;
707            }
708            // Canonical output is a static snapshot and does not regenerate
709            // loadshape objects. Replaying these references creates dangling
710            // native dependencies even when the snapshot never uses a shape.
711            if matches!(class, "load" | "generator" | "vsource")
712                && matches!(key.as_str(), "daily" | "yearly" | "duty")
713            {
714                self.warn(
715                    &C::EMIT_DSS_EXTRAS_DROPPED,
716                    format!(
717                        "{class} {name}: extra `{key}` loadshape reference omitted from the static snapshot; its definition is not regenerated"
718                    ),
719                );
720                continue;
721            }
722            let known = table.is_some_and(|t| t.props.contains(&key.as_str()));
723            let text = value
724                .as_str()
725                .map(ToString::to_string)
726                .or_else(|| value.as_f64().map(num))
727                .or_else(|| value.as_i64().map(|v| v.to_string()));
728            match (known, text) {
729                (true, Some(text)) => {
730                    let (out, representable) = dss_value_out(&text);
731                    if !representable {
732                        self.warn(&C::EMIT_DSS_EXTRAS_DROPPED, format!(
733                            "{class} {name}: extra `{key}` value `{text}` contains every \
734                             dss quote closer and splits when scanned bare; emitted as \
735                             written and a reparse will not see the same value"
736                        ));
737                    }
738                    let _ = write!(tail, " {key}={out}");
739                }
740                _ => self.warn(&C::EMIT_DSS_VALUE_SUBSTITUTED, format!(
741                    "{class} {name}: extra `{key}` is not a dss property; dropped from the output"
742                )),
743            }
744        }
745        tail
746    }
747
748    /// Lower triangle matrix text. Rows shorter than the triangle pad
749    /// with 0 instead of panicking, and the padding is reported.
750    fn matrix_arg(&mut self, m: &ConductorMatrix, what: &str) -> String {
751        let mut short = false;
752        let rows: Vec<String> = m
753            .iter()
754            .enumerate()
755            .map(|(i, row)| {
756                let take = row.len().min(i + 1);
757                let mut vals: Vec<String> = row[..take].iter().map(|v| num(*v)).collect();
758                if take < i + 1 {
759                    short = true;
760                    vals.resize(i + 1, "0".to_string());
761                }
762                vals.join(" ")
763            })
764            .collect();
765        if short {
766            self.warn(
767                &C::EMIT_DSS_VALUE_DEFAULTED,
768                format!(
769                    "{what}: matrix rows are shorter than the lower triangle; \
770                 missing entries emitted as 0"
771                ),
772            );
773        }
774        format!("({})", rows.join(" | "))
775    }
776
777    /// Consumes an rs/xs extras pair only when both first rows parse; a
778    /// half present or unusable pair stays in extras and is reported.
779    fn take_seq_pair(
780        &mut self,
781        extras: &mut Extras,
782        r_key: &str,
783        x_key: &str,
784        what: &str,
785    ) -> Option<((f64, f64), (f64, f64))> {
786        let r = seq_parts(extras, r_key);
787        let x = seq_parts(extras, x_key);
788        if let (Some(r), Some(x)) = (r, x) {
789            extras.remove(r_key);
790            extras.remove(x_key);
791            return Some((r, x));
792        }
793        if extras.contains_key(r_key) || extras.contains_key(x_key) {
794            let state = |key: &str, parsed: bool| {
795                if !extras.contains_key(key) {
796                    format!("`{key}` is missing")
797                } else if parsed {
798                    format!("`{key}` is usable")
799                } else {
800                    format!("`{key}` is not a numeric matrix")
801                }
802            };
803            self.warn(
804                &C::EMIT_DSS_EXTRAS_DROPPED,
805                format!(
806                    "{what}: series impedance extras unusable ({}, {}); left in extras",
807                    state(r_key, r.is_some()),
808                    state(x_key, x.is_some()),
809                ),
810            );
811        }
812        None
813    }
814
815    /// Emitted `phases=`: the reader's stash when present, otherwise
816    /// inferred from the terminal map shape. A delta map with 3 conductors
817    /// is 2 or 3 phase; without the stash the 3 phase reading wins, loudly.
818    fn element_phases(
819        &mut self,
820        extras: &Extras,
821        terminal_map: &[String],
822        configuration: Configuration,
823        class: &str,
824        name: &str,
825    ) -> usize {
826        if let Some(p) = extras_usize(extras, "phases") {
827            return p.max(1);
828        }
829        match configuration {
830            Configuration::Delta => match terminal_map.len() {
831                2 => 1,
832                3 => {
833                    self.warn(
834                        &C::EMIT_DSS_VALUE_DEFAULTED,
835                        format!(
836                            "{class} {name}: a delta terminal map with 3 conductors is 2 or 3 \
837                         phase and no phases record disambiguates; emitted phases=3"
838                        ),
839                    );
840                    3
841                }
842                n => {
843                    self.warn(
844                        &C::EMIT_DSS_VALUE_DEFAULTED,
845                        format!(
846                            "{class} {name}: a delta terminal map with {n} conductors has no \
847                         dss phases mapping; emitted phases={}",
848                            n.max(1)
849                        ),
850                    );
851                    n.max(1)
852                }
853            },
854            Configuration::Wye => terminal_map.len().saturating_sub(1).max(1),
855            _ => 1,
856        }
857    }
858
859    fn network(&mut self, net: &MulticonductorNetwork) {
860        self.line_out("Clear");
861        self.line_out(&format!(
862            "Set DefaultBaseFrequency={}",
863            num(net.base_frequency())
864        ));
865        self.out.push('\n');
866
867        self.source_elements(net);
868        self.line_codes(net);
869        self.lines(net);
870        self.switches(net);
871        self.transformers(net);
872        self.loads(net);
873        self.shunts(net);
874        self.capacitors(net);
875        self.generators(net);
876        self.ibrs(net);
877
878        for u in net.untyped_objects() {
879            self.warn(
880                &C::EMIT_DSS_RECORD_DROPPED,
881                format!(
882                    "{} {}: untyped object is not regenerated in canonical dss output",
883                    u.class, u.name
884                ),
885            );
886        }
887        for b in net.buses() {
888            self.bus_extras(b);
889        }
890
891        self.out.push('\n');
892        // Source options re-emit in stored order, except the keys this
893        // writer derives itself (the DefaultBaseFrequency header, the
894        // VoltageBases tail). Commands do not re-emit: their position in
895        // the script matters and the canonical element order does not
896        // preserve it, so each drop is reported instead.
897        for (key, value) in net.options() {
898            if key.is_empty() {
899                self.warn(
900                    &C::EMIT_DSS_VALUE_DEFAULTED,
901                    format!(
902                        "option `{value}` has no name; not regenerated in canonical dss output"
903                    ),
904                );
905                continue;
906            }
907            // The engine resolves Set names by first match in option table
908            // order (Command.cpp Getcommand → HashList FindAbbrev). Every
909            // prefix of "voltagebases" binds Voltagebases (it precedes the
910            // other v options), but prefixes of "defaultbasefrequency"
911            // shorter than "defaultb" bind DefaultDaily, so the frequency
912            // skip is bounded at the engine's unique resolution point.
913            // Calcvoltagebases is a command, never a Set option, so it does
914            // not belong here.
915            let key_lc = key.to_ascii_lowercase();
916            if matches!(super::frequency::option_position(&key_lc), 6 | 53 | 73) {
917                self.warn(&C::EMIT_DSS_RECORD_DROPPED, format!(
918                    "option {key}={value}: source frequency history is replaced by the typed snapshot frequency",
919                ));
920                continue;
921            }
922            if "voltagebases".starts_with(&key_lc)
923                || (key_lc.len() >= "defaultb".len() && "defaultbasefrequency".starts_with(&key_lc))
924            {
925                continue;
926            }
927            let (text, representable) = dss_value_out(value);
928            if !representable {
929                self.warn(
930                    &C::EMIT_DSS_VALUE_SUBSTITUTED,
931                    format!(
932                        "option `{key}`: value `{value}` contains every dss quote closer \
933                     and splits when scanned bare; emitted as written and a reparse \
934                     will not see the same value"
935                    ),
936                );
937            }
938            self.line_out(&format!("Set {key}={text}"));
939        }
940        for (verb, args) in net.commands() {
941            if verb.eq_ignore_ascii_case("calcvoltagebases") || verb.eq_ignore_ascii_case("solve") {
942                continue; // the tail emits these
943            }
944            let shown = if args.is_empty() {
945                verb.clone()
946            } else {
947                format!("{verb} {args}")
948            };
949            self.warn(
950                &C::EMIT_DSS_RECORD_DROPPED,
951                format!("command `{shown}` is not regenerated in canonical dss output"),
952            );
953        }
954        // Regenerated cases represent a fixed electrical snapshot. Source
955        // options cannot restart controls or override the materialized frequency.
956        self.line_out("Set Mode=Snapshot ControlMode=Off");
957        self.line_out(&format!("Set Frequency={}", num(net.base_frequency())));
958        let mut bases: Vec<f64> = self
959            .kv_estimate
960            .values()
961            .map(|v| crate::electrical::calc_wye_line_voltage(*v) / 1e3)
962            .collect();
963        bases.sort_by(f64::total_cmp);
964        bases.dedup_by(|a, b| (*a - *b).abs() < 1e-9);
965        if !bases.is_empty() {
966            let list: Vec<String> = bases.iter().map(|v| num(*v)).collect();
967            self.line_out(&format!("Set VoltageBases=[{}]", list.join(", ")));
968            self.line_out("Calcvoltagebases");
969        }
970        // Buscoords addresses the engine's bus list, which does not exist
971        // before the circuit and its equipment have been constructed.
972        if net.buses().iter().any(|bus| bus.location.is_some()) {
973            self.line_out("Makebuslist");
974        }
975        self.buscoords(net);
976        self.line_out("Solve");
977    }
978
979    fn bus_extras(&mut self, b: &DistBus) {
980        for key in b.extras.keys() {
981            if key == "x" || key == "y" {
982                continue; // legacy coordinate extras are superseded by `location`
983            }
984            self.warnings.push(
985                &C::EMIT_DSS_EXTRAS_DROPPED,
986                format!(
987                    "bus {}: extra `{key}` is not regenerated in canonical dss output",
988                    b.id
989                ),
990            );
991        }
992        for (field, present) in [
993            ("v_min", b.v_min.is_some() || b.v_min_phase.is_some()),
994            ("v_max", b.v_max.is_some() || b.v_max_phase.is_some()),
995            ("vpn_min", b.vpn_min.is_some()),
996            ("vpn_max", b.vpn_max.is_some()),
997            ("vpp_min", b.vpp_min.is_some()),
998            ("vpp_max", b.vpp_max.is_some()),
999            ("vpos_min", b.vpos_min.is_some()),
1000            ("vpos_max", b.vpos_max.is_some()),
1001            ("vneg_max", b.vneg_max.is_some()),
1002            ("vzero_max", b.vzero_max.is_some()),
1003            ("vn_max", b.vn_max.is_some()),
1004        ] {
1005            if present {
1006                self.warnings.push(
1007                    &C::EMIT_DSS_FIELD_DROPPED,
1008                    format!(
1009                        "bus {}: `{field}` voltage bounds have no dss expression; dropped",
1010                        b.id
1011                    ),
1012                );
1013            }
1014        }
1015    }
1016
1017    fn buscoords(&mut self, net: &MulticonductorNetwork) {
1018        let rows: Vec<(&DistBus, crate::geo::DistLocation)> = net
1019            .buses()
1020            .iter()
1021            .filter_map(|b| b.location.map(|location| (b, location)))
1022            .collect();
1023        if rows.is_empty() {
1024            return;
1025        }
1026        let Some(path) = self.options.buscoords_filename.clone() else {
1027            self.warn(
1028                &C::EMIT_DSS_FIELD_DROPPED,
1029                "typed bus locations have no OpenDSS buscoords filename; dropped",
1030            );
1031            return;
1032        };
1033        if path.is_empty() {
1034            self.warn(
1035                &C::EMIT_DSS_FIELD_DROPPED,
1036                "typed bus locations have an empty OpenDSS buscoords filename; dropped",
1037            );
1038            return;
1039        }
1040        let (path_out, path_representable) = dss_value_out(&path);
1041        if !path_representable {
1042            self.warn(&C::EMIT_DSS_VALUE_SUBSTITUTED, format!(
1043                "buscoords filename `{path}` contains every dss quote closer and splits when scanned bare; emitted as written and a reparse will not see the same value"
1044            ));
1045        }
1046
1047        let mut text = String::new();
1048        for (bus, location) in rows {
1049            if !location.x.is_finite() || !location.y.is_finite() {
1050                self.warn(
1051                    &C::EMIT_DSS_FIELD_DROPPED,
1052                    format!(
1053                        "bus {}: nonfinite location is not emitted to OpenDSS buscoords",
1054                        bus.id
1055                    ),
1056                );
1057                continue;
1058            }
1059            let (bus_out, bus_representable) = dss_value_out(&bus.id);
1060            if !bus_representable {
1061                self.warn(&C::EMIT_DSS_FIELD_DROPPED, format!(
1062                    "bus {}: id contains every dss quote closer and splits in buscoords; coordinates dropped",
1063                    bus.id
1064                ));
1065                continue;
1066            }
1067            let _ = writeln!(text, "{bus_out},{},{}", num(location.x), num(location.y));
1068        }
1069        if text.is_empty() {
1070            return;
1071        }
1072        self.line_out(&format!("Buscoords {path_out}"));
1073        self.sidecars.push(TextSidecar { path, text });
1074    }
1075
1076    fn source_elements(&mut self, net: &MulticonductorNetwork) {
1077        for source in net
1078            .sources()
1079            .iter()
1080            .filter(|s| s.energy_cost_rate.is_some())
1081        {
1082            self.warn(
1083                &C::EMIT_DSS_FIELD_DROPPED,
1084                format!(
1085                    "voltage source {}: energy_cost_rate has no target field",
1086                    source.name,
1087                ),
1088            );
1089        }
1090        self.exact_sources(net);
1091    }
1092
1093    fn line_codes(&mut self, net: &MulticonductorNetwork) {
1094        let omega_nf = std::f64::consts::TAU * net.base_frequency() * 1e-9;
1095        for c in net.line_codes() {
1096            if self
1097                .native_source_code
1098                .as_ref()
1099                .is_some_and(|name| name.eq_ignore_ascii_case(&c.name))
1100            {
1101                continue;
1102            }
1103            if sources::asymmetric(c) {
1104                self.warn(&C::EMIT_DSS_RECORD_DROPPED, format!(
1105                    "linecode {}: asymmetric library definition is not regenerated; instantiated line impedances use equivalent sources", c.name,
1106                ));
1107                if c.source.is_some() {
1108                    self.warn(
1109                        &C::EMIT_DSS_EXTRAS_DROPPED,
1110                        format!(
1111                            "linecode {}: matrix provenance `source` has no DSS field; dropped",
1112                            c.name,
1113                        ),
1114                    );
1115                }
1116                continue; // its complete impedance is emitted on a zero-EMF Vsource
1117            }
1118            self.emit_linecode(c, omega_nf);
1119        }
1120        // #307: a line whose unique grounded return is not the last conductor
1121        // reorders its node lists; the matrices its linecode carries are
1122        // indexed by that conductor order, so a permuted copy of the linecode
1123        // is emitted and the line references it — the map and the matrices
1124        // move together, and other lines keep the original.
1125        let mut permuted: std::collections::HashSet<(String, usize)> =
1126            std::collections::HashSet::new();
1127        for l in net.lines() {
1128            let Some(k) = self.endpoint_return_index(
1129                &l.bus_from,
1130                &l.terminal_map_from,
1131                &l.bus_to,
1132                &l.terminal_map_to,
1133            ) else {
1134                continue;
1135            };
1136            let Some(code) = net
1137                .line_codes()
1138                .iter()
1139                .find(|c| c.name.eq_ignore_ascii_case(&l.linecode))
1140            else {
1141                continue;
1142            };
1143            if sources::asymmetric(code) {
1144                continue;
1145            }
1146            if code.n_conductors != l.terminal_map_from.len()
1147                || !permuted.insert((code.name.to_ascii_lowercase(), k))
1148            {
1149                continue;
1150            }
1151            let perm = return_permutation(k, code.n_conductors);
1152            let mut clone = code.clone();
1153            clone.name = format!("{}_ret{k}", code.name);
1154            clone.r_series = permute_symmetric(&code.r_series, &perm);
1155            clone.x_series = permute_symmetric(&code.x_series, &perm);
1156            clone.g_from = permute_symmetric(&code.g_from, &perm);
1157            clone.b_from = permute_symmetric(&code.b_from, &perm);
1158            clone.g_to = permute_symmetric(&code.g_to, &perm);
1159            clone.b_to = permute_symmetric(&code.b_to, &perm);
1160            clone.i_max = code.i_max.as_ref().map(|v| permute_padded(v, &perm));
1161            clone.s_max = code.s_max.as_ref().map(|v| permute_padded(v, &perm));
1162            self.emit_linecode(&clone, omega_nf);
1163        }
1164        self.out.push('\n');
1165    }
1166
1167    fn emit_linecode(&mut self, c: &DistLineCode, omega_nf: f64) {
1168        {
1169            self.check_name("linecode", &c.name);
1170            let n = c.n_conductors;
1171            let what = format!("linecode {}", c.name);
1172            let mut s = format!("New Linecode.{} nphases={n} units=m", c.name);
1173            let rm = self.matrix_arg(&c.r_series, &what);
1174            let _ = write!(s, " rmatrix={rm}");
1175            let xm = self.matrix_arg(&c.x_series, &what);
1176            let _ = write!(s, " xmatrix={xm}");
1177            // cmatrix in nF per meter: each half is omega C / 2, so
1178            // C_nF = 2 b / (omega 1e-9).
1179            let c_nf: ConductorMatrix = c
1180                .b_from
1181                .iter()
1182                .map(|row| row.iter().map(|b| 2.0 * b / omega_nf).collect())
1183                .collect();
1184            let cm = self.matrix_arg(&c_nf, &what);
1185            let _ = write!(s, " cmatrix={cm}");
1186            match c.i_max.as_deref() {
1187                Some([amps, ..]) if amps.is_finite() => {
1188                    let _ = write!(s, " emergamps={}", num(*amps));
1189                }
1190                Some([_, ..]) => self.warn(
1191                    &C::EMIT_DSS_FIELD_DROPPED,
1192                    format!(
1193                        "linecode {}: first i_max entry is nonfinite (an unbounded \
1194                     conductor); emergamps not emitted",
1195                        c.name
1196                    ),
1197                ),
1198                Some([]) => self.warn(
1199                    &C::EMIT_DSS_FIELD_DROPPED,
1200                    format!("linecode {}: i_max is empty; emergamps not emitted", c.name),
1201                ),
1202                None => {}
1203            }
1204            if !c.g_from.iter().flatten().all(|&g| g == 0.0) {
1205                self.warn(
1206                    &C::EMIT_DSS_FIELD_DROPPED,
1207                    format!(
1208                        "linecode {}: shunt conductance has no dss linecode field; dropped",
1209                        c.name
1210                    ),
1211                );
1212            }
1213            if c.source.is_some() {
1214                self.warn(
1215                    &C::EMIT_DSS_EXTRAS_DROPPED,
1216                    format!(
1217                        "linecode {}: matrix provenance `source` has no dss field; dropped",
1218                        c.name
1219                    ),
1220                );
1221            }
1222            let mut extras = c.extras.clone();
1223            extras.remove("units"); // canonical output is in meters
1224            s.push_str(&self.extras_tail("linecode", &c.name, &extras));
1225            self.line_out(&s);
1226        }
1227    }
1228
1229    // One block per record family; splitting the reorder decision from the
1230    // emission would thread five locals through helpers.
1231    #[allow(clippy::too_many_lines)]
1232    fn lines(&mut self, net: &MulticonductorNetwork) {
1233        for l in net.lines() {
1234            if self.native_source_line.as_deref() == Some(l.name.as_str()) {
1235                continue;
1236            }
1237            if self.sequence_impedance_branch(net, l) {
1238                continue;
1239            }
1240            if self.current_form_line(net, l) {
1241                continue;
1242            }
1243            self.check_name("line", &l.name);
1244            // #307: with an agreed return conductor before the end and a
1245            // matching permuted linecode emitted, the node lists and the
1246            // matrices move together; otherwise the order warning stands.
1247            let reorder = self
1248                .endpoint_return_index(
1249                    &l.bus_from,
1250                    &l.terminal_map_from,
1251                    &l.bus_to,
1252                    &l.terminal_map_to,
1253                )
1254                .filter(|_| {
1255                    net.line_codes().iter().any(|c| {
1256                        c.name.eq_ignore_ascii_case(&l.linecode)
1257                            && c.n_conductors == l.terminal_map_from.len()
1258                    })
1259                });
1260            let (map_from, map_to, code_name);
1261            if let Some(k) = reorder {
1262                let perm = return_permutation(k, l.terminal_map_from.len());
1263                map_from = permute_names(&l.terminal_map_from, &perm);
1264                map_to = permute_names(&l.terminal_map_to, &perm);
1265                code_name = format!("{}_ret{k}", l.linecode);
1266                self.warn(
1267                    &C::EMIT_DSS_VALUE_SUBSTITUTED,
1268                    format!(
1269                        "line {}: grounded return moved last in both node lists; \
1270                         linecode `{code_name}` carries the matrices permuted in step",
1271                        l.name
1272                    ),
1273                );
1274            } else {
1275                self.warn_terminal_order(
1276                    "line",
1277                    &l.name,
1278                    &l.bus_from,
1279                    Some("bus1"),
1280                    &l.terminal_map_from,
1281                );
1282                self.warn_terminal_order(
1283                    "line",
1284                    &l.name,
1285                    &l.bus_to,
1286                    Some("bus2"),
1287                    &l.terminal_map_to,
1288                );
1289                map_from = l.terminal_map_from.clone();
1290                map_to = l.terminal_map_to.clone();
1291                code_name = l.linecode.clone();
1292            }
1293            let phases = l.terminal_map_from.len();
1294            let mut s = format!(
1295                "New Line.{} bus1={} bus2={} phases={phases} linecode={} length={} units=m",
1296                l.name,
1297                self.bus_ref(&l.bus_from, &map_from),
1298                self.bus_ref(&l.bus_to, &map_to),
1299                code_name,
1300                self.checked_num(l.length, 1.0, &format!("line {}: length", l.name)),
1301            );
1302            let mut extras = l.extras.clone();
1303            extras.remove("units"); // canonical output is in meters
1304            let line_i_max = match reorder {
1305                Some(k) => l
1306                    .i_max
1307                    .as_ref()
1308                    .map(|v| permute_padded(v, &return_permutation(k, l.terminal_map_from.len()))),
1309                None => l.i_max.clone(),
1310            };
1311            // `i_max` maps to `emergamps`, as it does on a linecode. The
1312            // typed field wins over a token kept in extras.
1313            match line_i_max.as_deref() {
1314                Some([amps, rest @ ..]) if is_positive_finite(*amps) => {
1315                    extras.remove("emergamps");
1316                    let _ = write!(s, " emergamps={}", num(*amps));
1317                    // The dss Line has one emergamps for all phases. Compare
1318                    // exactly: any difference makes the token wrong for a phase.
1319                    #[allow(clippy::float_cmp)]
1320                    let uneven = rest.iter().any(|a| *a != *amps);
1321                    if uneven {
1322                        self.warn(
1323                            &C::EMIT_DSS_VALUE_COLLAPSED,
1324                            format!(
1325                                "line {}: i_max is not equal on all phases; emergamps \
1326                             holds the first phase only",
1327                                l.name
1328                            ),
1329                        );
1330                    }
1331                }
1332                Some([_, ..]) => self.warn(
1333                    &C::EMIT_DSS_FIELD_DROPPED,
1334                    format!(
1335                        "line {}: first i_max entry is nonfinite (an unbounded \
1336                     conductor); emergamps not emitted",
1337                        l.name
1338                    ),
1339                ),
1340                Some([]) => self.warn(
1341                    &C::EMIT_DSS_FIELD_DROPPED,
1342                    format!("line {}: i_max is empty; emergamps not emitted", l.name),
1343                ),
1344                None => {}
1345            }
1346            if l.s_max.is_some() {
1347                // dss Line carries current ratings only; an apparent power
1348                // limit is a different quantity and is not folded into
1349                // emergamps. The typed field drops, declared.
1350                self.warn(
1351                    &C::EMIT_DSS_FIELD_DROPPED,
1352                    format!(
1353                        "line {}: `s_max` is an apparent power limit and dss Line \
1354                         states current ratings only; dropped",
1355                        l.name
1356                    ),
1357                );
1358            }
1359            s.push_str(&self.extras_tail("line", &l.name, &extras));
1360            self.line_out(&s);
1361        }
1362        self.out.push('\n');
1363    }
1364
1365    fn switches(&mut self, net: &MulticonductorNetwork) {
1366        let mut used = ideal_transformers::used_names(net);
1367        for sw in net.switches() {
1368            self.check_name("line", &sw.name);
1369            // #307: a switch is ideal — no conductor indexed matrices — so an
1370            // agreed return conductor reorders both node lists together.
1371            let reorder = self.endpoint_return_index(
1372                &sw.bus_from,
1373                &sw.terminal_map_from,
1374                &sw.bus_to,
1375                &sw.terminal_map_to,
1376            );
1377            let (map_from, map_to);
1378            if let Some(k) = reorder {
1379                let perm = return_permutation(k, sw.terminal_map_from.len());
1380                map_from = permute_names(&sw.terminal_map_from, &perm);
1381                map_to = permute_names(&sw.terminal_map_to, &perm);
1382                self.warn(
1383                    &C::EMIT_DSS_VALUE_SUBSTITUTED,
1384                    format!(
1385                        "switch {}: grounded return moved last in both node lists; \
1386                         the switch carries no per conductor data to keep in step",
1387                        sw.name
1388                    ),
1389                );
1390            } else {
1391                self.warn_terminal_order(
1392                    "switch",
1393                    &sw.name,
1394                    &sw.bus_from,
1395                    Some("bus1"),
1396                    &sw.terminal_map_from,
1397                );
1398                self.warn_terminal_order(
1399                    "switch",
1400                    &sw.name,
1401                    &sw.bus_to,
1402                    Some("bus2"),
1403                    &sw.terminal_map_to,
1404                );
1405                map_from = sw.terminal_map_from.clone();
1406                map_to = sw.terminal_map_to.clone();
1407            }
1408            let mut mapped = sw.clone();
1409            mapped.terminal_map_from.clone_from(&map_from);
1410            mapped.terminal_map_to.clone_from(&map_to);
1411            if self.ideal_closed_switch(&mapped, &mut used) {
1412                continue;
1413            }
1414            let phases = sw.terminal_map_from.len();
1415            let mut s = format!(
1416                "New Line.{} bus1={} bus2={} phases={phases} switch=y",
1417                sw.name,
1418                self.bus_ref(&sw.bus_from, &map_from),
1419                self.bus_ref(&sw.bus_to, &map_to),
1420            );
1421            if sw.open && sw.extras.is_empty() {
1422                // A disconnected ideal contact has no line-charging shunts.
1423                s.push_str(" c1=0 c0=0 enabled=no");
1424            }
1425            match sw.i_max.as_deref() {
1426                Some([amps, ..]) if amps.is_finite() => {
1427                    let _ = write!(s, " emergamps={}", num(*amps));
1428                }
1429                Some([_, ..]) => self.warn(
1430                    &C::EMIT_DSS_FIELD_DROPPED,
1431                    format!(
1432                        "line {}: first i_max entry is nonfinite (an unbounded \
1433                     conductor); emergamps not emitted",
1434                        sw.name
1435                    ),
1436                ),
1437                Some([]) => self.warn(
1438                    &C::EMIT_DSS_FIELD_DROPPED,
1439                    format!("line {}: i_max is empty; emergamps not emitted", sw.name),
1440                ),
1441                None => {}
1442            }
1443            // A switch that came through the ENGINEERING model carries its
1444            // total series matrices; sequence overrides reproduce them over
1445            // the forced 0.001 length (the engine's switch dummy values
1446            // would otherwise apply).
1447            let mut extras = sw.extras.clone();
1448            let what = format!("line {}", sw.name);
1449            if let Some(((rs, rm), (xs, xm))) =
1450                self.take_seq_pair(&mut extras, "pmd_rs", "pmd_xs", &what)
1451            {
1452                let (r1, r0) = crate::sequence::calc_sequence_from_phase(rs, rm);
1453                let (x1, x0) = crate::sequence::calc_sequence_from_phase(xs, xm);
1454                let _ = write!(
1455                    s,
1456                    " c0=0 c1=0 r0={} r1={} x0={} x1={}",
1457                    num(r0 / 0.001),
1458                    num(r1 / 0.001),
1459                    num(x0 / 0.001),
1460                    num(x1 / 0.001)
1461                );
1462            }
1463            s.push_str(&self.extras_tail("line", &sw.name, &extras));
1464            self.line_out(&s);
1465            self.line_out(&format!(
1466                "New SwtControl.{}_state SwitchedObj=Line.{} Action={}",
1467                sw.name,
1468                sw.name,
1469                if sw.open { "open" } else { "close" },
1470            ));
1471        }
1472        self.out.push('\n');
1473    }
1474
1475    fn transformers(&mut self, net: &MulticonductorNetwork) {
1476        let mut used = ideal_transformers::used_names(net);
1477        for original in net.transformers() {
1478            let projected = self.ideal_transformer(original, &mut used);
1479            let t = projected.as_ref().unwrap_or(original);
1480            self.check_name("transformer", &t.name);
1481            let nw = t.windings.len();
1482            let buses: Vec<String> = t
1483                .windings
1484                .iter()
1485                .map(|w| self.bus_ref(&w.bus, &w.terminal_map))
1486                .collect();
1487            let conns: Vec<&str> = t
1488                .windings
1489                .iter()
1490                .map(|w| match w.conn {
1491                    DistWindingConn::Wye => "wye",
1492                    DistWindingConn::Delta => "delta",
1493                })
1494                .collect();
1495            let kvs: Vec<Option<f64>> = t
1496                .windings
1497                .iter()
1498                .enumerate()
1499                .map(|(idx, w)| self.winding_kv(t, idx, w))
1500                .collect();
1501            let kvas: Vec<Option<f64>> = t
1502                .windings
1503                .iter()
1504                .enumerate()
1505                .map(|(idx, w)| {
1506                    if is_positive_finite(w.s_rating) {
1507                        Some(w.s_rating / 1e3)
1508                    } else {
1509                        self.warn(
1510                            &C::EMIT_DSS_VALUE_DEFAULTED,
1511                            format!(
1512                                "transformer {}: winding {} has no usable rating; kva not \
1513                             emitted (the OpenDSS default applies)",
1514                                t.name,
1515                                idx + 1
1516                            ),
1517                        );
1518                        None
1519                    }
1520                })
1521                .collect();
1522            let rs: Vec<String> = t
1523                .windings
1524                .iter()
1525                .enumerate()
1526                .map(|(idx, w)| {
1527                    let what = format!("transformer {}: winding {} %r", t.name, idx + 1);
1528                    self.checked_num(w.r_pct, 0.0, &what)
1529                })
1530                .collect();
1531            let taps: Vec<String> = t.windings.iter().map(|w| num(w.tap)).collect();
1532            let mut s = format!(
1533                "New Transformer.{} phases={} windings={nw} buses=({}) conns=({})",
1534                t.name,
1535                t.phases,
1536                buses.join(", "),
1537                conns.join(", "),
1538            );
1539            let mut edits: Vec<String> = vec![String::new(); nw];
1540            winding_array(&mut s, &mut edits, "kvs", "kv", &kvs);
1541            winding_array(&mut s, &mut edits, "kvas", "kva", &kvas);
1542            let _ = write!(s, " %Rs=({}) taps=({})", rs.join(", "), taps.join(", "));
1543            self.transformer_reactances(t, &mut s);
1544            let mut extras = t.extras.clone();
1545            // Winding resistances are authoritative; replaying the derived
1546            // total would overwrite unequal first/second winding values.
1547            extras.remove("%loadloss");
1548            // Typed reactances determine output after an IR load or mutation.
1549            if t.xsc_pct.len() == nw * (nw - 1) / 2 {
1550                extras.remove("xscarray");
1551            }
1552            if let Some((loss, imag)) = crate::model::transformer_no_load_percentages(t) {
1553                extras.remove("no_load_shunt");
1554                extras.insert("%noloadloss".into(), serde_json::json!(loss));
1555                extras.insert("%imag".into(), serde_json::json!(imag));
1556            }
1557            s.push_str(&self.extras_tail("transformer", &t.name, &extras));
1558            self.line_out(&s);
1559            for (idx, w) in t.windings.iter().enumerate() {
1560                if let Some(r) = w.r_neutral {
1561                    let _ = write!(edits[idx], " rneut={}", num(r));
1562                }
1563                if let Some(x) = w.x_neutral {
1564                    let _ = write!(edits[idx], " xneut={}", num(x));
1565                }
1566            }
1567            for (idx, edit) in edits.iter().enumerate() {
1568                if !edit.is_empty() {
1569                    self.line_out(&format!("~ wdg={}{edit}", idx + 1));
1570                }
1571            }
1572        }
1573        self.out.push('\n');
1574    }
1575
1576    /// Emit the complete pair table for four or more windings.
1577    fn transformer_reactances(&mut self, t: &DistTransformer, output: &mut String) {
1578        let nw = t.windings.len();
1579        // A scalar XHL, XHT or XLT of zero is trapped to the OpenDSS default
1580        // (7, 35 and 30 percent) by the native setter. The complete array sets
1581        // an actual zero without adding leakage.
1582        if nw == 2 && t.xsc_pct.as_slice() == [0.0] {
1583            output.push_str(" xscarray=(0)");
1584        } else if nw <= 3 && t.xsc_pct.len() >= 3 {
1585            let (xhl, xht) = (t.xsc_pct[0], t.xsc_pct[1]);
1586            let xlt = self.star_xlt(t);
1587            #[allow(clippy::float_cmp)] // Only an exact zero is trapped.
1588            if xhl == 0.0 || xht == 0.0 || xlt == 0.0 {
1589                let _ = write!(
1590                    output,
1591                    " xscarray=({}, {}, {})",
1592                    num(xhl),
1593                    num(xht),
1594                    num(xlt)
1595                );
1596            } else {
1597                let _ = write!(
1598                    output,
1599                    " xhl={} xht={} xlt={}",
1600                    num(xhl),
1601                    num(xht),
1602                    num(xlt)
1603                );
1604            }
1605        } else if nw > 3 {
1606            let expected = nw * (nw - 1) / 2;
1607            if t.xsc_pct.len() != expected {
1608                self.warn(
1609                    &C::EMIT_DSS_VALUE_DEFAULTED,
1610                    format!("transformer {}: xsc_pct has {} values; expected {expected}; OpenDSS defaults apply to absent pairs", t.name, t.xsc_pct.len()),
1611                );
1612            }
1613            let values: Vec<_> = t.xsc_pct.iter().map(|x| num(*x)).collect();
1614            let _ = write!(output, " xscarray=({})", values.join(", "));
1615        } else if let Some(xhl) = t.xsc_pct.first() {
1616            let _ = write!(output, " xhl={}", num(*xhl));
1617        } else {
1618            // OpenDSS traps a scalar xhl=0 to its 7 percent default, so this
1619            // deck states the default leakage rather than a zero.
1620            self.warn(
1621                &C::EMIT_DSS_VALUE_DEFAULTED,
1622                format!(
1623                    "transformer {}: xsc_pct is empty; emitted xhl=0, which OpenDSS reads as its default of 7 percent",
1624                    t.name
1625                ),
1626            );
1627            output.push_str(" xhl=0");
1628        }
1629    }
1630
1631    /// The `xlt=` value for a three winding record. dss cannot solve a star
1632    /// whose third arm is zero: the two secondary legs collapse to about half
1633    /// voltage and read unequal under balanced load, and the solution
1634    /// converges without an error. A source that lumps the whole leakage on
1635    /// the primary arm states exactly that, so the split from the OpenDSS
1636    /// center tap example, `xlt = 2/3 xhl` at `xhl = xht`, substitutes.
1637    fn star_xlt(&mut self, t: &DistTransformer) -> f64 {
1638        let (xhl, xht, xlt) = (t.xsc_pct[0], t.xsc_pct[1], t.xsc_pct[2]);
1639        if xlt > 0.0 && xlt.is_finite() {
1640            return xlt;
1641        }
1642        #[allow(clippy::float_cmp)]
1643        let lumped_on_primary = xhl == xht && xhl > 0.0 && xhl.is_finite();
1644        if !lumped_on_primary {
1645            self.warn(
1646                &C::EMIT_DSS_VALUE_SUBSTITUTED,
1647                format!(
1648                    "transformer {}: xlt={} is not a reactance dss can solve, and the \
1649                 other two arms do not determine a replacement; emitted as stated",
1650                    t.name,
1651                    num(xlt)
1652                ),
1653            );
1654            return xlt;
1655        }
1656        let repaired = 2.0 / 3.0 * xhl;
1657        self.warn(
1658            &C::EMIT_DSS_VALUE_COLLAPSED,
1659            format!(
1660                "transformer {}: the source puts the whole leakage on the primary arm, \
1661             leaving xlt={}; dss solves that star as a collapsed secondary, so \
1662             xlt={} went out instead, holding xhl={}",
1663                t.name,
1664                num(xlt),
1665                num(repaired),
1666                num(xhl)
1667            ),
1668        );
1669        repaired
1670    }
1671
1672    /// The winding `kv=` value in kV, or `None` if no value is available.
1673    /// A BMOPF transformer without `v_nom_from`/`v_nom_to` reads as
1674    /// `v_ref = NaN`, and OpenDSS refuses a deck that holds a `NaN` token.
1675    /// The fallback is the bus voltage estimate, scaled to the voltage across
1676    /// the two winding terminals: line to neutral for a single phase winding
1677    /// on a grounded terminal, line to line in all other cases.
1678    fn winding_kv(
1679        &mut self,
1680        t: &crate::model::DistTransformer,
1681        idx: usize,
1682        w: &DistWinding,
1683    ) -> Option<f64> {
1684        if is_positive_finite(w.v_ref) {
1685            return Some(w.v_ref / 1e3);
1686        }
1687        let bus = w.bus.to_ascii_lowercase();
1688        let line_to_neutral =
1689            winding_is_line_to_neutral(t.phases, w, |b| self.grounded.get(b).map(Vec::as_slice));
1690        let Some(v_pn) = self.kv_estimate.get(&bus).copied() else {
1691            self.warn(
1692                &C::EMIT_DSS_VALUE_DEFAULTED,
1693                format!(
1694                    "transformer {}: winding {} has no rated voltage and bus `{}` has \
1695                 no voltage estimate; kv not emitted (the OpenDSS default applies)",
1696                    t.name,
1697                    idx + 1,
1698                    w.bus
1699                ),
1700            );
1701            return None;
1702        };
1703        let kv = if line_to_neutral {
1704            v_pn
1705        } else {
1706            crate::electrical::calc_wye_line_voltage(v_pn)
1707        } / 1e3;
1708        self.warn(
1709            &C::EMIT_DSS_FIELD_DROPPED,
1710            format!(
1711                "transformer {}: winding {} has no rated voltage; kv={} derived \
1712             from the bus `{}` voltage estimate",
1713                t.name,
1714                idx + 1,
1715                num(kv),
1716                w.bus
1717            ),
1718        );
1719        Some(kv)
1720    }
1721
1722    /// Split unequal branch powers or voltage laws into native one-phase
1723    /// loads. Wye branches retain their return; delta branches follow the
1724    /// ordered terminal pairs, including the closing edge of a delta bank.
1725    fn load_parts<'l>(&mut self, l: &'l DistLoad) -> Vec<Cow<'l, DistLoad>> {
1726        let return_index = (l.configuration != Configuration::Delta)
1727            .then(|| self.return_terminal_index(&l.bus, &l.terminal_map))
1728            .flatten();
1729        let misordered = return_index.is_some_and(|i| i + 1 != l.terminal_map.len());
1730        if !loads::needs_split(l) && !misordered {
1731            return vec![Cow::Borrowed(l)];
1732        }
1733        let Some(maps) = loads::branch_maps(l, return_index) else {
1734            // Public emission rejects this shape before writing any output.
1735            self.warn(
1736                &C::EMIT_DSS_VALUE_COLLAPSED,
1737                format!(
1738                    "load {}: branch powers do not align with its terminal map",
1739                    l.name
1740                ),
1741            );
1742            return vec![Cow::Borrowed(l)];
1743        };
1744        maps.into_iter()
1745            .enumerate()
1746            .map(|(i, map)| {
1747                let mut part = l.clone();
1748                part.name = format!("{}_{}", l.name, map[0]);
1749                part.terminal_map = map;
1750                part.p_nom = vec![l.p_nom[i]];
1751                part.q_nom = vec![l.q_nom[i]];
1752                part.voltage_model = loads::phase_model(&l.voltage_model, i);
1753                // Whole-bank voltage and power-factor spellings must not override
1754                // the selected branch's typed values.
1755                for key in ["conn", "kv", "pf"] {
1756                    part.extras.remove(key);
1757                }
1758                part.extras.insert("phases".into(), 1.into());
1759                Cow::Owned(part)
1760            })
1761            .collect()
1762    }
1763
1764    fn loads(&mut self, net: &MulticonductorNetwork) {
1765        let mut names: BTreeSet<_> = net
1766            .loads()
1767            .iter()
1768            .map(|load| load.name.to_ascii_lowercase())
1769            .collect();
1770        for load in net.loads() {
1771            for mut part in self.load_parts(load) {
1772                if let Cow::Owned(ref mut part) = part {
1773                    let base = part.name.clone();
1774                    let mut suffix = 2;
1775                    while !names.insert(part.name.to_ascii_lowercase()) {
1776                        part.name = format!("{base}_{suffix}");
1777                        suffix += 1;
1778                    }
1779                }
1780                self.write_load(&part);
1781            }
1782        }
1783        self.out.push('\n');
1784    }
1785
1786    /// One `New Load.<name>` record. A [`DistLoad`] emits one of these, or one
1787    /// per phase when [`Self::load_parts`] split it.
1788    fn write_load(&mut self, l: &DistLoad) {
1789        if matches!(
1790            l.voltage_model,
1791            DistLoadVoltageModel::BoundedConstantPower { .. }
1792        ) {
1793            self.write_static_storage(l);
1794            return;
1795        }
1796        self.check_name("load", &l.name);
1797        let phases =
1798            self.element_phases(&l.extras, &l.terminal_map, l.configuration, "load", &l.name);
1799        let conn = self.element_conn(&l.extras, l.configuration, &l.bus, &l.terminal_map);
1800        // The reader's nconds: a 3 phase delta has no neutral conductor,
1801        // every other connection carries phases + 1.
1802        let nconds = nconds_for(conn, phases);
1803        self.warn_map_arity("load", &l.name, l.terminal_map.len(), nconds);
1804        let kw: f64 = l.p_nom.iter().sum::<f64>() / 1e3;
1805        let kvar: f64 = l.q_nom.iter().sum::<f64>() / 1e3;
1806        let typed_kv = self.load_nominal_kv(&l.voltage_model, phases, l.configuration, &l.name);
1807        // Full branch arrays are authoritative after a typed edit. Preserve
1808        // legacy scalar voltage hints for formats that store the bank kV.
1809        let typed_branch_kv = (l.voltage_model.v_nom().len() == l.p_nom.len())
1810            .then_some(typed_kv)
1811            .flatten();
1812        let kv = typed_branch_kv.unwrap_or_else(|| {
1813            self.element_kv(
1814                &l.extras,
1815                ElementKv {
1816                    bus: &l.bus,
1817                    phases,
1818                    configuration: l.configuration,
1819                    name: &l.name,
1820                    class: "load",
1821                    typed_kv,
1822                },
1823            )
1824        });
1825        let mut extras = l.extras.clone();
1826        strip_emitted_extras(&mut extras, &["kv", "phases", "conn"]);
1827        // q that came from a power factor goes back as pf=, so the
1828        // engine recomputes its own kvar bit for bit.
1829        let reactive = match extras.remove("pf").and_then(|v| v.as_f64()) {
1830            Some(pf) => format!("pf={}", num(pf)),
1831            None => format!("kvar={}", num(kvar)),
1832        };
1833        let mut s = format!(
1834            "New Load.{} bus1={} phases={phases} conn={conn} kv={} kw={} {reactive}",
1835            l.name,
1836            self.bus_ref(&l.bus, &l.terminal_map),
1837            num(kv),
1838            num(kw),
1839        );
1840        self.write_load_voltage_model(l, &mut extras, &mut s);
1841        self.add_default_load_voltage_bounds(&mut extras);
1842        s.push_str(&self.extras_tail("load", &l.name, &extras));
1843        self.line_out(&s);
1844    }
1845
1846    fn write_load_voltage_model(&mut self, l: &DistLoad, extras: &mut Extras, s: &mut String) {
1847        let retained_model = extras.remove("model");
1848        let retained_zipv = extras.remove("zipv");
1849        let nominal_model = l.voltage_model.without_voltage_bounds();
1850        let bounded_cutoff = load_voltage_bounds(&l.voltage_model, extras);
1851        match &nominal_model {
1852            DistLoadVoltageModel::ConstantPower { .. } => {
1853                if bounded_cutoff.is_none()
1854                    && let Some(model) = retained_model
1855                {
1856                    extras.insert("model".into(), model);
1857                }
1858            }
1859            DistLoadVoltageModel::ConstantImpedance { .. } => {
1860                s.push_str(" model=2");
1861            }
1862            DistLoadVoltageModel::ConstantCurrent { .. } => {
1863                s.push_str(" model=5");
1864            }
1865            DistLoadVoltageModel::Zip {
1866                alpha_z,
1867                alpha_i,
1868                alpha_p,
1869                beta_z,
1870                beta_i,
1871                beta_p,
1872                ..
1873            } => {
1874                s.push_str(" model=8");
1875                if let (Some(az), Some(ai), Some(ap), Some(bz), Some(bi), Some(bp)) = (
1876                    alpha_z.first(),
1877                    alpha_i.first(),
1878                    alpha_p.first(),
1879                    beta_z.first(),
1880                    beta_i.first(),
1881                    beta_p.first(),
1882                ) {
1883                    let cutoff = bounded_cutoff
1884                        .unwrap_or_else(|| zipv_cutoff(retained_zipv.as_ref()).unwrap_or(0.0));
1885                    let _ = write!(
1886                        s,
1887                        " zipv=({}, {}, {}, {}, {}, {}, {})",
1888                        num(*az),
1889                        num(*ai),
1890                        num(*ap),
1891                        num(*bz),
1892                        num(*bi),
1893                        num(*bp),
1894                        num(cutoff)
1895                    );
1896                }
1897            }
1898            DistLoadVoltageModel::BoundedZip { .. }
1899            | DistLoadVoltageModel::BoundedExponential { .. }
1900            | DistLoadVoltageModel::BoundedConstantPower { .. } => {
1901                unreachable!("bounds handled above")
1902            }
1903            DistLoadVoltageModel::Exponential {
1904                gamma_p, gamma_q, ..
1905            } if matches!(
1906                l.voltage_model,
1907                DistLoadVoltageModel::BoundedExponential { .. }
1908            ) =>
1909            {
1910                extras.remove("cvrwatts");
1911                extras.remove("cvrvars");
1912                let _ = write!(
1913                    s,
1914                    " model=4 cvrwatts={} cvrvars={}",
1915                    num(gamma_p[0]),
1916                    num(gamma_q[0])
1917                );
1918            }
1919            DistLoadVoltageModel::Exponential { .. } => {
1920                self.warn(&C::EMIT_DSS_VALUE_SUBSTITUTED, format!(
1921                    "load {}: exponential voltage model has no OpenDSS load model code; emitted constant power",
1922                    l.name
1923                ));
1924            }
1925        }
1926    }
1927
1928    fn add_default_load_voltage_bounds(&self, extras: &mut Extras) {
1929        if let Some(bounds) = self.options.default_load_voltage_bounds {
1930            if bounds.vminpu == 0.0 {
1931                // Vminpu=0 alone leaves the native Vlowpu=.5 impedance fallback.
1932                // Unbounded P/I laws must retain their behavior below that threshold.
1933                extras.entry("vlowpu".into()).or_insert_with(|| 0.0.into());
1934            }
1935            extras
1936                .entry("vminpu".into())
1937                .or_insert_with(|| bounds.vminpu.into());
1938            extras
1939                .entry("vmaxpu".into())
1940                .or_insert_with(|| bounds.vmaxpu.into());
1941        }
1942    }
1943
1944    /// `kv` for a load or capacitor: the recorded value when the source
1945    /// carried one, otherwise the propagated bus estimate.
1946    /// [`num`] for a value a payload can spell as `null`. OpenDSS has no token
1947    /// for a nonfinite number — `NaN` and `inf` in a deck are a parse failure
1948    /// downstream, not a value — so an unusable one is reported and replaced
1949    /// with the neutral value, as the BMOPF writer does (#288).
1950    fn checked_num(&mut self, v: f64, fallback: f64, what: &str) -> String {
1951        if v.is_finite() {
1952            return num(v);
1953        }
1954        self.warn(
1955            &C::EMIT_DSS_VALUE_SUBSTITUTED,
1956            format!("{what}: {v} has no dss spelling; emitted {}", num(fallback)),
1957        );
1958        num(fallback)
1959    }
1960
1961    fn element_kv(&mut self, extras: &Extras, ctx: ElementKv<'_>) -> f64 {
1962        if let Some(v) = extras.get("kv") {
1963            match v
1964                .as_f64()
1965                .or_else(|| v.as_str().and_then(|s| s.parse().ok()))
1966            {
1967                Some(kv) => return kv,
1968                None => self.warn(
1969                    &C::EMIT_DSS_VALUE_DEFAULTED,
1970                    format!(
1971                        "{} {}: kv extra `{v}` does not parse as a number; \
1972                     using the bus voltage estimate",
1973                        ctx.class, ctx.name
1974                    ),
1975                ),
1976            }
1977        }
1978        if let Some(kv) = ctx.typed_kv {
1979            return kv;
1980        }
1981        if let Some(vln) = self.kv_estimate.get(&ctx.bus.to_ascii_lowercase()).copied() {
1982            // OpenDSS convention: line to line for 2 and 3 phase, line to
1983            // neutral for single phase.
1984            let v = if ctx.phases >= 2 || ctx.configuration == Configuration::Delta {
1985                crate::electrical::calc_wye_line_voltage(vln)
1986            } else {
1987                vln
1988            };
1989            v / 1e3
1990        } else {
1991            self.warn(
1992                &C::EMIT_DSS_VALUE_DEFAULTED,
1993                format!(
1994                    "{} {}: no kv in the source and no bus voltage estimate; \
1995                 emitted 12.47",
1996                    ctx.class, ctx.name
1997                ),
1998            );
1999            12.47
2000        }
2001    }
2002
2003    fn load_nominal_kv(
2004        &mut self,
2005        model: &DistLoadVoltageModel,
2006        phases: usize,
2007        configuration: Configuration,
2008        name: &str,
2009    ) -> Option<f64> {
2010        let v_nom = model.v_nom();
2011        let v_phase = v_nom.first().copied().filter(|v| is_positive_finite(*v))?;
2012        if v_nom
2013            .iter()
2014            .any(|v| (*v - v_phase).abs() > 1e-9 * v.abs().max(v_phase.abs()).max(1.0))
2015        {
2016            self.warn(&C::EMIT_DSS_VALUE_COLLAPSED, format!(
2017                "load {name}: nonuniform nominal voltage array has no OpenDSS scalar kv; emitted the first value"
2018            ));
2019        }
2020        let v = if phases >= 2 && configuration == Configuration::Wye {
2021            crate::electrical::calc_wye_line_voltage(v_phase)
2022        } else {
2023            v_phase
2024        };
2025        Some(v / 1e3)
2026    }
2027
2028    /// Emitted `conn=`: delta for typed delta, for a stashed DSS delta token,
2029    /// and for a single phase two terminal map that does not include a grounded
2030    /// return conductor.
2031    fn element_conn(
2032        &self,
2033        extras: &Extras,
2034        configuration: Configuration,
2035        bus: &str,
2036        terminal_map: &[String],
2037    ) -> &'static str {
2038        let stash_delta = extras
2039            .get("conn")
2040            .and_then(|v| v.as_str())
2041            .is_some_and(|t| {
2042                t.to_ascii_lowercase().starts_with('d') || t.eq_ignore_ascii_case("ll")
2043            });
2044        let has_grounded_return = self
2045            .grounded
2046            .get(&bus.to_ascii_lowercase())
2047            .is_some_and(|g| terminal_map.iter().any(|t| g.contains(t)));
2048        match configuration {
2049            Configuration::Delta => "delta",
2050            Configuration::SinglePhase
2051                if stash_delta || (terminal_map.len() == 2 && !has_grounded_return) =>
2052            {
2053                "delta"
2054            }
2055            _ => "wye",
2056        }
2057    }
2058
2059    fn write_impedance_shunt(&mut self, sh: &crate::model::DistShunt, phases: usize) {
2060        self.check_name("reactor", &sh.name);
2061        let Some((conductance, susceptance)) = first_diag_admittance(&sh.g, &sh.b, phases) else {
2062            self.warn(&C::EMIT_DSS_RECORD_DROPPED, format!(
2063                "shunt {}: conductance matrix has no diagonal admittance; dropped from the output",
2064                sh.name
2065            ));
2066            return;
2067        };
2068        if has_off_diagonal(&sh.g) || has_off_diagonal(&sh.b) {
2069            self.warn(
2070                &C::EMIT_DSS_VALUE_COLLAPSED,
2071                format!(
2072                    "shunt {}: off diagonal admittance has no scalar reactor expression; \
2073                 only the first diagonal admittance is regenerated",
2074                    sh.name
2075                ),
2076            );
2077        }
2078        if !uniform_diag_admittance(&sh.g, &sh.b, phases, conductance, susceptance) {
2079            self.warn(
2080                &C::EMIT_DSS_VALUE_COLLAPSED,
2081                format!(
2082                    "shunt {}: diagonal admittances differ; only the first diagonal \
2083                 admittance is regenerated",
2084                    sh.name
2085                ),
2086            );
2087        }
2088        let denom = conductance * conductance + susceptance * susceptance;
2089        if !denom.is_finite() || denom <= 0.0 {
2090            self.warn(
2091                &C::EMIT_DSS_RECORD_DROPPED,
2092                format!(
2093                    "shunt {}: invalid grounding admittance; dropped from the output",
2094                    sh.name
2095                ),
2096            );
2097            return;
2098        }
2099        let resistance = conductance / denom;
2100        let reactance = -susceptance / denom;
2101        let mut extras = sh.extras.clone();
2102        strip_shunt_extras(&mut extras);
2103        let ground = vec!["0".to_string(); phases.max(1)];
2104        let mut line = format!(
2105            "New Reactor.{} bus1={} bus2={} phases={} r={} x={}",
2106            sh.name,
2107            self.bus_ref(&sh.bus, &sh.terminal_map),
2108            self.bus_ref(&sh.bus, &ground),
2109            phases.max(1),
2110            num(resistance),
2111            num(reactance),
2112        );
2113        line.push_str(&self.extras_tail("reactor", &sh.name, &extras));
2114        self.line_out(&line);
2115    }
2116
2117    fn shunt_phases(
2118        &mut self,
2119        sh: &crate::model::DistShunt,
2120        conn_delta: bool,
2121        inferred_phases: usize,
2122    ) -> usize {
2123        if let Some(p) = extras_usize(&sh.extras, "phases") {
2124            p.max(1)
2125        } else if conn_delta {
2126            self.element_phases(
2127                &sh.extras,
2128                &sh.terminal_map,
2129                Configuration::Delta,
2130                "shunt",
2131                &sh.name,
2132            )
2133        } else {
2134            inferred_phases
2135        }
2136    }
2137
2138    fn write_kvar_shunt(&mut self, sh: &crate::model::DistShunt, phases: usize, conn_delta: bool) {
2139        // Scan every diagonal conductor, not just the first `phases` of them: a
2140        // delta bank's conductor count exceeds its stashed `phases`, and a
2141        // sign-flipped diagonal past that bound must still set the class.
2142        let (b_max, b_min) = (0..sh.b.len())
2143            .map(|idx| diag_at(&sh.b, idx))
2144            .fold((0.0_f64, 0.0_f64), |(mx, mn), v| (mx.max(v), mn.min(v)));
2145        let (class, b_phase) = if b_max > 0.0 {
2146            ("capacitor", b_max)
2147        } else if b_min < 0.0 {
2148            ("reactor", b_min)
2149        } else {
2150            self.warn(
2151                &C::EMIT_DSS_RECORD_DROPPED,
2152                format!(
2153                    "shunt {}: no nonzero susceptance; dropped from the output",
2154                    sh.name
2155                ),
2156            );
2157            return;
2158        };
2159        if b_max > 0.0 && b_min < 0.0 {
2160            self.warn(
2161                &C::EMIT_DSS_FIELD_DROPPED,
2162                format!(
2163                    "shunt {}: diagonal mixes capacitive and inductive phases; only the \
2164                 {class} phases are regenerated",
2165                    sh.name
2166                ),
2167            );
2168        }
2169        self.check_name(class, &sh.name);
2170        let off_diag = has_off_diagonal(&sh.b);
2171        if off_diag && !conn_delta {
2172            self.warn(
2173                &C::EMIT_DSS_VALUE_COLLAPSED,
2174                format!(
2175                    "shunt {}: off diagonal susceptance has no {class} expression; \
2176                 only the diagonal is regenerated",
2177                    sh.name
2178                ),
2179            );
2180        }
2181        let edges = if conn_delta {
2182            delta_edges(sh.terminal_map.len(), phases)
2183        } else {
2184            Vec::new()
2185        };
2186        if conn_delta && edges.is_empty() {
2187            self.warn(&C::EMIT_DSS_RECORD_DROPPED, format!(
2188                "shunt {}: delta terminal map has no branch expression; dropped from the output",
2189                sh.name
2190            ));
2191            return;
2192        }
2193        if conn_delta && delta_branch_susceptance(&sh.b, &edges, sh.terminal_map.len()).is_none() {
2194            self.warn(
2195                &C::EMIT_DSS_VALUE_COLLAPSED,
2196                format!(
2197                    "shunt {}: delta susceptance matrix has no scalar {class} expression; \
2198                 only the average branch susceptance is regenerated",
2199                    sh.name
2200                ),
2201            );
2202        }
2203        let configuration = if conn_delta {
2204            Configuration::Delta
2205        } else {
2206            Configuration::Wye
2207        };
2208        let kv = self.element_kv(
2209            &sh.extras,
2210            ElementKv {
2211                bus: &sh.bus,
2212                phases,
2213                configuration,
2214                name: &sh.name,
2215                class,
2216                typed_kv: None,
2217            },
2218        );
2219        let kvar = shunt_kvar(sh, phases, conn_delta, &edges, b_phase, kv);
2220        let mut extras = sh.extras.clone();
2221        strip_shunt_extras(&mut extras);
2222        let conn = if conn_delta { "delta" } else { "wye" };
2223        let decl = if class == "reactor" {
2224            "Reactor"
2225        } else {
2226            "Capacitor"
2227        };
2228        let mut line = format!(
2229            "New {decl}.{} bus1={} phases={phases} conn={conn} kv={} kvar={}",
2230            sh.name,
2231            self.bus_ref(&sh.bus, &sh.terminal_map),
2232            num(kv),
2233            num(kvar),
2234        );
2235        line.push_str(&self.extras_tail(class, &sh.name, &extras));
2236        self.line_out(&line);
2237    }
2238
2239    /// Typed BMOPF capacitor banks (#266). A bank states its rating and its
2240    /// nameplate voltage, which is what an OpenDSS `Capacitor` takes, so the
2241    /// conversion is a unit change and the terminal spelling: `v_nom` is line
2242    /// to line for the three phase configurations and across the terminals for
2243    /// `SINGLE_PHASE`, which is the `kv` convention the reader applies coming
2244    /// back the other way.
2245    ///
2246    /// The untyped [`DistShunt`](crate::model::DistShunt) B matrix keeps its
2247    /// own path ([`Self::write_kvar_shunt`]): it carries phase geometry a
2248    /// scalar rating cannot state.
2249    fn capacitors(&mut self, net: &MulticonductorNetwork) {
2250        for c in net.capacitors() {
2251            if !is_positive_finite(c.q_rated) {
2252                self.warn(
2253                    &C::EMIT_DSS_VALUE_SUBSTITUTED,
2254                    format!(
2255                        "capacitor {}: rating {} is not a positive number; dropped from the output",
2256                        c.name, c.q_rated
2257                    ),
2258                );
2259                continue;
2260            }
2261            self.check_name("capacitor", &c.name);
2262            let node_map = self.return_last("capacitor", &c.name, &c.bus, &c.terminal_map);
2263            let phases = self.element_phases(
2264                &c.extras,
2265                &c.terminal_map,
2266                c.configuration,
2267                "capacitor",
2268                &c.name,
2269            );
2270            let conn = self.element_conn(&c.extras, c.configuration, &c.bus, &c.terminal_map);
2271            let nconds = nconds_for(conn, phases);
2272            self.warn_map_arity("capacitor", &c.name, c.terminal_map.len(), nconds);
2273            let typed_kv = is_positive_finite(c.v_nom).then(|| c.v_nom / 1e3);
2274            if typed_kv.is_none() {
2275                self.warn(
2276                    &C::EMIT_DSS_VALUE_SUBSTITUTED,
2277                    format!(
2278                        "capacitor {}: nominal voltage {} is not a positive number; \
2279                     using the bus voltage estimate",
2280                        c.name, c.v_nom
2281                    ),
2282                );
2283            }
2284            let kv = self.element_kv(
2285                &c.extras,
2286                ElementKv {
2287                    bus: &c.bus,
2288                    phases,
2289                    configuration: c.configuration,
2290                    name: &c.name,
2291                    class: "capacitor",
2292                    typed_kv,
2293                },
2294            );
2295            let mut extras = c.extras.clone();
2296            strip_emitted_extras(&mut extras, &["kv", "phases", "conn", "kvar"]);
2297            let mut line = format!(
2298                "New Capacitor.{} bus1={} phases={phases} conn={conn} kv={} kvar={}",
2299                c.name,
2300                self.bus_ref(&c.bus, &node_map),
2301                num(kv),
2302                num(c.q_rated / 1e3),
2303            );
2304            line.push_str(&self.extras_tail("capacitor", &c.name, &extras));
2305            self.line_out(&line);
2306        }
2307    }
2308
2309    fn shunts(&mut self, net: &MulticonductorNetwork) {
2310        for (index, sh) in net.shunts().iter().enumerate() {
2311            if self.common_return_shunt(net, sh) || self.full_admittance_shunt(net, sh, index) {
2312                continue;
2313            }
2314            let stashed_delta = shunt_stashed_delta(sh);
2315            let inferred_phases =
2316                extras_usize(&sh.extras, "phases").unwrap_or_else(|| sh.terminal_map.len().max(1));
2317            let conn_delta = stashed_delta
2318                || looks_like_delta_shunt(&sh.b, sh.terminal_map.len(), inferred_phases);
2319            let phases = self.shunt_phases(sh, conn_delta, inferred_phases);
2320            if has_nonzero(&sh.g) {
2321                self.write_impedance_shunt(sh, phases);
2322            } else {
2323                self.write_kvar_shunt(sh, phases, conn_delta);
2324            }
2325        }
2326        self.out.push('\n');
2327    }
2328
2329    fn generators(&mut self, net: &MulticonductorNetwork) {
2330        for g in net.generators() {
2331            self.check_name("generator", &g.name);
2332            let node_map = self.return_last("generator", &g.name, &g.bus, &g.terminal_map);
2333            let phases = extras_usize(&g.extras, "phases")
2334                .or_else(|| {
2335                    let count = [
2336                        Some(g.p_nom.as_slice()),
2337                        g.p_min.as_deref(),
2338                        g.p_max.as_deref(),
2339                        g.q_min.as_deref(),
2340                        g.q_max.as_deref(),
2341                    ]
2342                    .into_iter()
2343                    .flatten()
2344                    .map(<[f64]>::len)
2345                    .max()
2346                    .unwrap_or(0);
2347                    (count > 0).then_some(count)
2348                })
2349                .unwrap_or_else(|| {
2350                    self.element_phases(
2351                        &g.extras,
2352                        &g.terminal_map,
2353                        g.configuration,
2354                        "generator",
2355                        &g.name,
2356                    )
2357                })
2358                .max(1);
2359            let conn = self.element_conn(&g.extras, g.configuration, &g.bus, &g.terminal_map);
2360            let nconds = nconds_for(conn, phases);
2361            self.warn_map_arity("generator", &g.name, g.terminal_map.len(), nconds);
2362            let kw: f64 = g.p_nom.iter().sum::<f64>() / 1e3;
2363            let kvar: f64 = g.q_nom.iter().sum::<f64>() / 1e3;
2364            let kv = self.element_kv(
2365                &g.extras,
2366                ElementKv {
2367                    bus: &g.bus,
2368                    phases,
2369                    configuration: g.configuration,
2370                    name: &g.name,
2371                    class: "generator",
2372                    typed_kv: (phases == 1)
2373                        .then(|| terminal_voltage::get(&self.terminal_kv, &g.bus, &g.terminal_map))
2374                        .flatten(),
2375                },
2376            );
2377            let mut s = format!(
2378                "New Generator.{} bus1={} phases={phases} conn={conn} kv={} kw={} kvar={}",
2379                g.name,
2380                self.bus_ref(&g.bus, &node_map),
2381                num(kv),
2382                num(kw),
2383                num(kvar),
2384            );
2385            if let Some(q) = &g.q_max {
2386                let _ = write!(s, " maxkvar={}", num(q.iter().sum::<f64>() / 1e3));
2387            }
2388            if let Some(q) = &g.q_min {
2389                let _ = write!(s, " minkvar={}", num(q.iter().sum::<f64>() / 1e3));
2390            }
2391            if g.cost.is_some() {
2392                self.warn(
2393                    &C::EMIT_DSS_FIELD_DROPPED,
2394                    format!(
2395                        "generator {}: generation cost has no dss field; dropped",
2396                        g.name
2397                    ),
2398                );
2399            }
2400            // Rating fields need a separate kVA mapping; dropping them
2401            // stays loud in the meantime.
2402            for (key, present) in [("s_max", g.s_max.is_some()), ("i_max", g.i_max.is_some())] {
2403                if present {
2404                    self.warn(
2405                        &C::EMIT_DSS_FIELD_DROPPED,
2406                        format!(
2407                            "generator {}: `{key}` has no dss Generator field mapping yet; dropped",
2408                            g.name
2409                        ),
2410                    );
2411                }
2412            }
2413            let mut extras = g.extras.clone();
2414            if !extras.contains_key("vminpu") || !extras.contains_key("vmaxpu") {
2415                extras.entry("vminpu".into()).or_insert(0.0.into());
2416                extras.entry("vmaxpu".into()).or_insert(2.0.into());
2417                self.warn(
2418                    &C::EMIT_DSS_VALUE_SUBSTITUTED,
2419                    format!("generator {}: missing voltage bounds use 0..2 pu for the declared power law; OpenDSS switches to constant impedance above the emitted vmaxpu", g.name),
2420                );
2421            }
2422            strip_emitted_extras(&mut extras, &["kv", "phases", "conn"]);
2423            s.push_str(&self.generator_extras(&g.name, extras));
2424            self.line_out(&s);
2425        }
2426    }
2427
2428    fn generator_extras(&mut self, name: &str, mut extras: Extras) -> String {
2429        // Native UserData is an immediate call into the loaded library;
2430        // alphabetic extras order discards it before UserModel exists.
2431        let user_data = extras.remove("userdata");
2432        let mut tail = self.extras_tail("generator", name, &extras);
2433        if let Some(data) = user_data {
2434            tail.push_str(&self.extras_tail(
2435                "generator",
2436                name,
2437                &[("userdata".into(), data)].into(),
2438            ));
2439        }
2440        tail
2441    }
2442
2443    fn ibrs(&mut self, net: &MulticonductorNetwork) {
2444        for ibr in net.ibrs() {
2445            self.check_name("pvsystem", &ibr.name);
2446            if ibr_is_fixed_dispatch(ibr) {
2447                self.write_fixed_ibr_generator(ibr);
2448            } else {
2449                self.write_pvsystem(ibr, net);
2450            }
2451        }
2452        for ibr in net.ibrs() {
2453            if !ibr_is_fixed_dispatch(ibr) {
2454                self.write_ibr_controls(ibr, net);
2455            }
2456        }
2457        if !net.ibrs().is_empty() {
2458            self.out.push('\n');
2459        }
2460    }
2461
2462    fn write_fixed_ibr_generator(&mut self, ibr: &DistIbr) {
2463        let node_map = self.return_last("ibr", &ibr.name, &ibr.bus, &ibr.terminal_map);
2464        let phases = ibr_phases(ibr);
2465        let configuration = ibr_configuration(ibr);
2466        let conn = self.element_conn(&ibr.extras, configuration, &ibr.bus, &ibr.terminal_map);
2467        let kv = self.ibr_kv(ibr, phases, configuration, "generator");
2468        let kw = ibr
2469            .p_min
2470            .as_ref()
2471            .map_or(0.0, |p| p.iter().sum::<f64>() / 1e3);
2472        let kvar = ibr
2473            .q_min
2474            .as_ref()
2475            .map_or(0.0, |q| q.iter().sum::<f64>() / 1e3);
2476        let mut line = format!(
2477            "New Generator.{} bus1={} phases={phases} conn={conn} kv={} kw={} kvar={} model=1 vminpu=0 vmaxpu=2",
2478            ibr.name,
2479            self.bus_ref(&ibr.bus, &node_map),
2480            num(kv),
2481            num(kw),
2482            num(kvar),
2483        );
2484        if let Some(q) = &ibr.q_max {
2485            let _ = write!(line, " maxkvar={}", num(q.iter().sum::<f64>() / 1e3));
2486        }
2487        if let Some(q) = &ibr.q_min {
2488            let _ = write!(line, " minkvar={}", num(q.iter().sum::<f64>() / 1e3));
2489        }
2490        self.warn_ibr_dss_drops(ibr);
2491        self.line_out(&line);
2492    }
2493
2494    fn write_pvsystem(&mut self, ibr: &DistIbr, net: &MulticonductorNetwork) {
2495        let node_map = self.return_last("ibr", &ibr.name, &ibr.bus, &ibr.terminal_map);
2496        let phases = ibr_phases(ibr);
2497        let configuration = ibr_configuration(ibr);
2498        let conn = self.element_conn(&ibr.extras, configuration, &ibr.bus, &ibr.terminal_map);
2499        let kv = self.ibr_kv(ibr, phases, configuration, "pvsystem");
2500        let kva = ibr.s_max.iter().sum::<f64>() / 1e3;
2501        let pmpp = ibr
2502            .p_avail
2503            .or_else(|| ibr.p_max.as_ref().map(|p| p.iter().sum()))
2504            .unwrap_or(0.0)
2505            / 1e3;
2506        let mut line = format!(
2507            "New PVSystem.{} bus1={} phases={phases} conn={conn} kv={} kVA={} Pmpp={} irradiance=1 %Pmpp=100 WattPriority=No VarFollowInverter=Yes",
2508            ibr.name,
2509            self.bus_ref(&ibr.bus, &node_map),
2510            num(kv),
2511            num(kva),
2512            num(pmpp),
2513        );
2514        if let Some(q) = &ibr.q_max {
2515            let _ = write!(line, " kvarMax={}", num(q.iter().sum::<f64>() / 1e3));
2516        }
2517        if let Some(q) = &ibr.q_min {
2518            let _ = write!(
2519                line,
2520                " kvarMaxAbs={}",
2521                num(q.iter().map(|v| v.abs()).sum::<f64>() / 1e3)
2522            );
2523        }
2524        if let Some(profile) = ibr_profile(ibr, net) {
2525            if let Some(pf) = &profile.power_factor {
2526                let _ = write!(line, " pf={}", num(pf.pf));
2527            }
2528            if let Some(vv) = &profile.volt_var {
2529                if let Some(v) = vv.p_min_for_q {
2530                    let _ = write!(line, " %PminNoVars={}", num(v));
2531                }
2532                if let Some(v) = vv.p_min_for_q_max {
2533                    let _ = write!(line, " %PminkvarMax={}", num(v));
2534                }
2535            }
2536        }
2537        self.warn_ibr_dss_drops(ibr);
2538        self.line_out(&line);
2539    }
2540
2541    fn write_ibr_controls(&mut self, ibr: &DistIbr, net: &MulticonductorNetwork) {
2542        let Some(profile) = ibr_profile(ibr, net) else {
2543            if let Some(name) = &ibr.control_profile {
2544                self.warn(
2545                    &C::EMIT_DSS_RECORD_DROPPED,
2546                    format!(
2547                        "ibr {}: control_profile `{name}` not found; no InvControl emitted",
2548                        ibr.name
2549                    ),
2550                );
2551            }
2552            return;
2553        };
2554        let phases = ibr_phases(ibr);
2555        let configuration = ibr_configuration(ibr);
2556        let kv = self.ibr_kv(ibr, phases, configuration, "pvsystem");
2557        let base_v = if phases >= 2 && configuration != Configuration::Delta {
2558            crate::electrical::calc_wye_phase_voltage(kv * 1e3)
2559        } else {
2560            kv * 1e3
2561        };
2562        let mut curves = Vec::new();
2563        let mut has_vv = false;
2564        let mut has_vw = false;
2565        if let Some(vv) = &profile.volt_var
2566            && let Some(curve) = self.volt_var_curve(ibr, vv, base_v)
2567        {
2568            curves.push(curve);
2569            has_vv = true;
2570        }
2571        if let Some(vw) = &profile.volt_watt
2572            && let Some(curve) = self.volt_watt_curve(ibr, vw, base_v)
2573        {
2574            curves.push(curve);
2575            has_vw = true;
2576        }
2577        for line in &curves {
2578            self.line_out(line);
2579        }
2580        if !has_vv && !has_vw {
2581            return;
2582        }
2583        let mon = self.control_mon_voltage(ibr, profile);
2584        let inv_name = format!("ivc_{}", ibr.name);
2585        self.check_name("invcontrol", &inv_name);
2586        let mut line = format!(
2587            "New InvControl.{inv_name} DERList=[PVSystem.{}] voltage_curvex_ref=rated monVoltageCalc={mon}",
2588            ibr.name
2589        );
2590        match (has_vv, has_vw) {
2591            (true, true) => {
2592                let _ = write!(
2593                    line,
2594                    " CombiMode=VV_VW vvc_curve1=vv_{} voltwatt_curve=vw_{}",
2595                    ibr.name, ibr.name
2596                );
2597                if let Some(vv) = &profile.volt_var {
2598                    let _ = write!(
2599                        line,
2600                        " RefReactivePower={}",
2601                        reactive_reference(vv.q_ref.unwrap_or(ReactivePowerReference::VarMax))
2602                    );
2603                }
2604                if let Some(vw) = &profile.volt_watt {
2605                    let _ = write!(
2606                        line,
2607                        " VoltwattYAxis={}",
2608                        active_reference(vw.p_ref.unwrap_or(ActivePowerReference::SMax))
2609                    );
2610                }
2611            }
2612            (true, false) => {
2613                line.push_str(" mode=VOLTVAR");
2614                let _ = write!(line, " vvc_curve1=vv_{}", ibr.name);
2615                if let Some(vv) = &profile.volt_var {
2616                    let _ = write!(
2617                        line,
2618                        " RefReactivePower={}",
2619                        reactive_reference(vv.q_ref.unwrap_or(ReactivePowerReference::VarMax))
2620                    );
2621                }
2622            }
2623            (false, true) => {
2624                line.push_str(" mode=VOLTWATT");
2625                let _ = write!(line, " voltwatt_curve=vw_{}", ibr.name);
2626                if let Some(vw) = &profile.volt_watt {
2627                    let _ = write!(
2628                        line,
2629                        " VoltwattYAxis={}",
2630                        active_reference(vw.p_ref.unwrap_or(ActivePowerReference::SMax))
2631                    );
2632                }
2633            }
2634            (false, false) => {}
2635        }
2636        self.line_out(&line);
2637    }
2638
2639    fn volt_var_curve(
2640        &mut self,
2641        ibr: &DistIbr,
2642        vv: &VoltVarControl,
2643        base_v: f64,
2644    ) -> Option<String> {
2645        self.check_control_reference(ibr, vv.voltage_reference)?;
2646        if !matches!(
2647            vv.q_unit,
2648            None | Some(crate::model::ReactivePowerUnit::VaFraction)
2649        ) {
2650            self.warn(
2651                &C::EMIT_DSS_FIELD_DROPPED,
2652                format!(
2653                    "ibr {}: volt_var q_unit is absolute VAR; DSS export only maps VA_FRACTION",
2654                    ibr.name
2655                ),
2656            );
2657            return None;
2658        }
2659        if vv.breakpoints.len() < 4 || vv.q_limits.len() < 2 || base_v <= 0.0 {
2660            self.warn(
2661                &C::EMIT_DSS_RECORD_DROPPED,
2662                format!(
2663                    "ibr {}: volt_var profile is incomplete; no XYcurve emitted",
2664                    ibr.name
2665                ),
2666            );
2667            return None;
2668        }
2669        let xs: Vec<String> = vv
2670            .breakpoints
2671            .iter()
2672            .take(4)
2673            .map(|v| num(v / base_v))
2674            .collect();
2675        let ys = [num(vv.q_limits[1]), num(0.0), num(0.0), num(vv.q_limits[0])];
2676        Some(format!(
2677            "New XYcurve.vv_{} npts=4 Xarray=[{}] Yarray=[{}]",
2678            ibr.name,
2679            xs.join(" "),
2680            ys.join(" ")
2681        ))
2682    }
2683
2684    fn volt_watt_curve(
2685        &mut self,
2686        ibr: &DistIbr,
2687        vw: &VoltWattControl,
2688        base_v: f64,
2689    ) -> Option<String> {
2690        self.check_control_reference(ibr, vw.voltage_reference)?;
2691        if !matches!(
2692            vw.p_unit,
2693            None | Some(crate::model::ActivePowerUnit::VaFraction)
2694        ) {
2695            self.warn(
2696                &C::EMIT_DSS_FIELD_DROPPED,
2697                format!(
2698                    "ibr {}: volt_watt p_unit is absolute W; DSS export only maps VA_FRACTION",
2699                    ibr.name
2700                ),
2701            );
2702            return None;
2703        }
2704        if vw.breakpoints.len() < 2 || vw.p_limits.len() < 2 || base_v <= 0.0 {
2705            self.warn(
2706                &C::EMIT_DSS_RECORD_DROPPED,
2707                format!(
2708                    "ibr {}: volt_watt profile is incomplete; no XYcurve emitted",
2709                    ibr.name
2710                ),
2711            );
2712            return None;
2713        }
2714        let xs: Vec<String> = vw
2715            .breakpoints
2716            .iter()
2717            .take(2)
2718            .map(|v| num(v / base_v))
2719            .collect();
2720        let ys = [num(vw.p_limits[1]), num(vw.p_limits[0])];
2721        Some(format!(
2722            "New XYcurve.vw_{} npts=2 Xarray=[{}] Yarray=[{}]",
2723            ibr.name,
2724            xs.join(" "),
2725            ys.join(" ")
2726        ))
2727    }
2728
2729    fn check_control_reference(
2730        &mut self,
2731        ibr: &DistIbr,
2732        reference: Option<ControlVoltageReference>,
2733    ) -> Option<()> {
2734        match reference.unwrap_or(ControlVoltageReference::PnPerPhase) {
2735            ControlVoltageReference::PgPerPhase | ControlVoltageReference::PgAveraged => Some(()),
2736            ControlVoltageReference::PnPerPhase | ControlVoltageReference::PnAveraged => {
2737                self.warn(&C::EMIT_DSS_VALUE_SUBSTITUTED, format!(
2738                    "ibr {}: PN voltage control is approximated by OpenDSS phase-to-ground InvControl",
2739                    ibr.name
2740                ));
2741                Some(())
2742            }
2743            ControlVoltageReference::PpPerPhase | ControlVoltageReference::PpAveraged => {
2744                self.warn(&C::EMIT_DSS_RECORD_DROPPED, format!(
2745                    "ibr {}: PP voltage control is not representable by OpenDSS InvControl; skipped",
2746                    ibr.name
2747                ));
2748                None
2749            }
2750        }
2751    }
2752
2753    fn control_mon_voltage(&mut self, ibr: &DistIbr, profile: &DistControlProfile) -> &'static str {
2754        let reference = profile
2755            .volt_var
2756            .as_ref()
2757            .and_then(|vv| vv.voltage_reference)
2758            .or_else(|| {
2759                profile
2760                    .volt_watt
2761                    .as_ref()
2762                    .and_then(|vw| vw.voltage_reference)
2763            })
2764            .unwrap_or(ControlVoltageReference::PnPerPhase);
2765        let averaged = matches!(
2766            ibr.voltage_aggregation,
2767            Some(IbrVoltageAggregation::Average)
2768        ) || matches!(
2769            reference,
2770            ControlVoltageReference::PgAveraged
2771                | ControlVoltageReference::PnAveraged
2772                | ControlVoltageReference::PpAveraged
2773        );
2774        if !averaged && ibr_phases(ibr) > 1 {
2775            self.warn(
2776                &C::EMIT_DSS_FIELD_DROPPED,
2777                format!(
2778                    "ibr {}: per phase InvControl needs split PVSystems; emitted AVG monitor",
2779                    ibr.name
2780                ),
2781            );
2782        }
2783        "AVG"
2784    }
2785
2786    fn ibr_kv(
2787        &mut self,
2788        ibr: &DistIbr,
2789        phases: usize,
2790        configuration: Configuration,
2791        class: &'static str,
2792    ) -> f64 {
2793        self.element_kv(
2794            &ibr.extras,
2795            ElementKv {
2796                bus: &ibr.bus,
2797                phases,
2798                configuration,
2799                name: &ibr.name,
2800                class,
2801                typed_kv: (phases == 1)
2802                    .then(|| terminal_voltage::get(&self.terminal_kv, &ibr.bus, &ibr.terminal_map))
2803                    .flatten(),
2804            },
2805        )
2806    }
2807
2808    fn warn_ibr_dss_drops(&mut self, ibr: &DistIbr) {
2809        for key in ibr.extras.keys() {
2810            if matches!(key.as_str(), "kv" | "phases") {
2811                continue;
2812            }
2813            self.warn(
2814                &C::EMIT_DSS_FIELD_DROPPED,
2815                format!(
2816                    "ibr {}: `{key}` has no OpenDSS export mapping; dropped",
2817                    ibr.name
2818                ),
2819            );
2820        }
2821        if ibr.i_max.is_some() {
2822            self.warn(
2823                &C::EMIT_DSS_FIELD_DROPPED,
2824                format!(
2825                    "ibr {}: i_max has no OpenDSS PVSystem current limit field; dropped",
2826                    ibr.name
2827                ),
2828            );
2829        }
2830        if !matches!(ibr.prime_mover, IbrPrimeMover::Pv | IbrPrimeMover::Generic) {
2831            self.warn(&C::EMIT_DSS_FIELD_DROPPED, format!(
2832                "ibr {}: prime_mover {:?} has no dedicated OpenDSS export path; emitted with the generic inverter mapping",
2833                ibr.name, ibr.prime_mover
2834            ));
2835        }
2836    }
2837}
2838
2839/// Drop the shunt keys the writer regenerates from the typed model so a stale
2840/// copy is not re-emitted in the extras tail.
2841fn strip_shunt_extras(extras: &mut Extras) {
2842    for key in ["kv", "kvar", "phases", "conn"] {
2843        extras.remove(key);
2844    }
2845}
2846
2847fn ibr_is_fixed_dispatch(ibr: &DistIbr) -> bool {
2848    ibr.control_profile.is_none()
2849        && matches!((&ibr.p_min, &ibr.p_max), (Some(a), Some(b)) if a == b)
2850        && matches!((&ibr.q_min, &ibr.q_max), (Some(a), Some(b)) if a == b)
2851}
2852
2853fn ibr_profile<'a>(
2854    ibr: &DistIbr,
2855    net: &'a MulticonductorNetwork,
2856) -> Option<&'a DistControlProfile> {
2857    let name = ibr.control_profile.as_ref()?;
2858    net.control_profiles()
2859        .iter()
2860        .find(|profile| profile.name.eq_ignore_ascii_case(name))
2861}
2862
2863fn ibr_phases(ibr: &DistIbr) -> usize {
2864    // Ratings are per electrical phase; topology identifies the connection,
2865    // and a wye terminal map includes a return conductor. In particular a
2866    // two-phase wye inverter has three terminals but only two phase ratings.
2867    if !ibr.s_max.is_empty() {
2868        return ibr.s_max.len();
2869    }
2870    match ibr.topology {
2871        IbrTopology::SinglePhase => 1,
2872        IbrTopology::ThreeLeg | IbrTopology::FourLeg => 3,
2873    }
2874}
2875
2876fn ibr_configuration(ibr: &DistIbr) -> Configuration {
2877    match ibr.topology {
2878        IbrTopology::SinglePhase => Configuration::SinglePhase,
2879        IbrTopology::ThreeLeg => Configuration::Delta,
2880        IbrTopology::FourLeg => Configuration::Wye,
2881    }
2882}
2883
2884fn reactive_reference(reference: ReactivePowerReference) -> &'static str {
2885    match reference {
2886        ReactivePowerReference::VarMax => "VARMAX",
2887        ReactivePowerReference::VarAvailable => "VARAVAL_WATTS",
2888    }
2889}
2890
2891fn active_reference(reference: ActivePowerReference) -> &'static str {
2892    match reference {
2893        ActivePowerReference::SMax => "KVARATINGPU",
2894        ActivePowerReference::PAvailable => "PAVAILABLEPU",
2895        ActivePowerReference::PMax => "PMPPPU",
2896    }
2897}
2898
2899fn has_nonzero(m: &ConductorMatrix) -> bool {
2900    m.iter().flatten().any(|&v| v != 0.0)
2901}
2902
2903fn has_off_diagonal(m: &ConductorMatrix) -> bool {
2904    m.iter()
2905        .enumerate()
2906        .any(|(i, row)| row.iter().enumerate().any(|(j, &v)| i != j && v != 0.0))
2907}
2908
2909/// The permutation that moves conductor `k` last.
2910fn return_permutation(k: usize, n: usize) -> Vec<usize> {
2911    (0..n).filter(|&i| i != k).chain([k]).collect()
2912}
2913
2914/// Symmetric densified read of a possibly lower triangular matrix, permuted:
2915/// entry `(i, j)` of the result is the stated `(perm[i], perm[j])` value,
2916/// read from either triangle.
2917fn permute_symmetric(m: &ConductorMatrix, perm: &[usize]) -> ConductorMatrix {
2918    let at = |i: usize, j: usize| {
2919        m.get(i)
2920            .and_then(|row| row.get(j))
2921            .copied()
2922            .or_else(|| m.get(j).and_then(|row| row.get(i)).copied())
2923            .unwrap_or(0.0)
2924    };
2925    perm.iter()
2926        .map(|&i| perm.iter().map(|&j| at(i, j)).collect())
2927        .collect()
2928}
2929
2930/// A terminal name list permuted.
2931fn permute_names(map: &[String], perm: &[usize]) -> Vec<String> {
2932    perm.iter().map(|&i| map[i].clone()).collect()
2933}
2934
2935/// A per conductor vector permuted, short vectors padded as unbounded.
2936fn permute_padded(v: &[f64], perm: &[usize]) -> Vec<f64> {
2937    perm.iter()
2938        .map(|&i| v.get(i).copied().unwrap_or(f64::INFINITY))
2939        .collect()
2940}
2941
2942fn diag_at(m: &ConductorMatrix, i: usize) -> f64 {
2943    m.get(i).and_then(|row| row.get(i)).copied().unwrap_or(0.0)
2944}
2945
2946fn matrix_scale(m: &ConductorMatrix) -> f64 {
2947    m.iter().flatten().fold(0.0_f64, |acc, &v| acc.max(v.abs()))
2948}
2949
2950fn close(a: f64, b: f64, scale: f64) -> bool {
2951    (a - b).abs() <= 1e-12_f64.max(scale * 1e-9)
2952}
2953
2954fn first_diag_admittance(
2955    g: &ConductorMatrix,
2956    b: &ConductorMatrix,
2957    phases: usize,
2958) -> Option<(f64, f64)> {
2959    (0..phases.max(1)).find_map(|i| {
2960        let gi = diag_at(g, i);
2961        let bi = diag_at(b, i);
2962        (gi != 0.0 || bi != 0.0).then_some((gi, bi))
2963    })
2964}
2965
2966fn uniform_diag_admittance(
2967    g: &ConductorMatrix,
2968    b: &ConductorMatrix,
2969    phases: usize,
2970    g0: f64,
2971    b0: f64,
2972) -> bool {
2973    let scale = matrix_scale(g)
2974        .max(matrix_scale(b))
2975        .max(g0.abs())
2976        .max(b0.abs());
2977    (0..phases.max(1)).all(|i| close(diag_at(g, i), g0, scale) && close(diag_at(b, i), b0, scale))
2978}
2979
2980fn shunt_stashed_delta(sh: &crate::model::DistShunt) -> bool {
2981    sh.extras
2982        .get("conn")
2983        .and_then(|v| v.as_str())
2984        .is_some_and(|t| t.to_ascii_lowercase().starts_with('d') || t.eq_ignore_ascii_case("ll"))
2985}
2986
2987fn mat_at(m: &ConductorMatrix, i: usize, j: usize) -> f64 {
2988    m.get(i).and_then(|row| row.get(j)).copied().unwrap_or(0.0)
2989}
2990
2991fn looks_like_delta_shunt(b: &ConductorMatrix, terminals: usize, phases: usize) -> bool {
2992    if terminals < 2 || !has_off_diagonal(b) {
2993        return false;
2994    }
2995    let edges = delta_edges(terminals, phases);
2996    delta_branch_susceptance(b, &edges, terminals).is_some()
2997}
2998
2999fn delta_branch_abs(b: &ConductorMatrix, edges: &[(usize, usize)]) -> Option<f64> {
3000    if edges.is_empty() {
3001        return None;
3002    }
3003    // Average over every edge (a missing entry contributes 0), so the divisor
3004    // matches the `edges.len()` that `shunt_kvar` multiplies back in; counting
3005    // only present entries would over-scale the regenerated kvar on a ragged
3006    // matrix.
3007    let total: f64 = edges
3008        .iter()
3009        .map(|&(i, j)| {
3010            b.get(i)
3011                .and_then(|row| row.get(j))
3012                .copied()
3013                .unwrap_or(0.0)
3014                .abs()
3015        })
3016        .sum();
3017    Some(total / edges.len() as f64)
3018}
3019
3020fn delta_branch_susceptance(
3021    b: &ConductorMatrix,
3022    edges: &[(usize, usize)],
3023    terminals: usize,
3024) -> Option<f64> {
3025    if terminals < 2 || edges.is_empty() {
3026        return None;
3027    }
3028    let scale = matrix_scale(b);
3029    if scale == 0.0 {
3030        return None;
3031    }
3032    let first = edges[0];
3033    let branch = -mat_at(b, first.0, first.1);
3034    if branch == 0.0 {
3035        return None;
3036    }
3037    let scale = scale.max(branch.abs());
3038    for (i, row) in b.iter().enumerate() {
3039        for (j, &value) in row.iter().enumerate() {
3040            if (i >= terminals || j >= terminals) && !close(value, 0.0, scale) {
3041                return None;
3042            }
3043        }
3044    }
3045    for i in 0..terminals {
3046        let incident = edges
3047            .iter()
3048            .filter(|&&(from, to)| from == i || to == i)
3049            .count() as f64;
3050        for j in 0..terminals {
3051            let linked = edges
3052                .iter()
3053                .any(|&(from, to)| (from == i && to == j) || (from == j && to == i));
3054            let expected = if i == j {
3055                incident * branch
3056            } else if linked {
3057                -branch
3058            } else {
3059                0.0
3060            };
3061            if !close(mat_at(b, i, j), expected, scale) {
3062                return None;
3063            }
3064        }
3065    }
3066    Some(branch)
3067}
3068
3069fn shunt_kvar(
3070    sh: &crate::model::DistShunt,
3071    phases: usize,
3072    conn_delta: bool,
3073    edges: &[(usize, usize)],
3074    b_phase: f64,
3075    kv: f64,
3076) -> f64 {
3077    let v_ref = super::read::bank_coil_voltage(kv, phases, conn_delta);
3078    if let Some(saved) = extras_f64(&sh.extras, "kvar")
3079        && super::read::kvar_shunt_matrix(
3080            &sh.terminal_map,
3081            phases,
3082            conn_delta,
3083            saved,
3084            v_ref,
3085            b_phase.signum(),
3086        )
3087        .as_ref()
3088            == Some(&sh.b)
3089    {
3090        // Retain the exact rating only while it still describes every matrix
3091        // entry. An edit to typed B must not be overwritten by stale metadata.
3092        return saved;
3093    }
3094    let (b_coil, coils) = if conn_delta {
3095        (
3096            delta_branch_abs(&sh.b, edges).unwrap_or(b_phase.abs()),
3097            edges.len(),
3098        )
3099    } else {
3100        (b_phase.abs(), phases)
3101    };
3102    crate::electrical::calc_rated_power(b_coil, v_ref) * coils as f64 / 1e3
3103}
3104
3105fn load_voltage_bounds(model: &DistLoadVoltageModel, extras: &mut Extras) -> Option<f64> {
3106    if let DistLoadVoltageModel::BoundedExponential {
3107        v_low_pu,
3108        v_min_pu,
3109        v_max_pu,
3110        ..
3111    } = model
3112    {
3113        extras.insert("vlowpu".into(), (*v_low_pu).into());
3114        extras.insert("vminpu".into(), (*v_min_pu).into());
3115        extras.insert("vmaxpu".into(), (*v_max_pu).into());
3116        return Some(0.0);
3117    }
3118    if let DistLoadVoltageModel::BoundedZip {
3119        v_low_pu,
3120        v_min_pu,
3121        v_max_pu,
3122        cutoff_pu,
3123        ..
3124    } = model
3125    {
3126        extras.insert("vlowpu".into(), (*v_low_pu).into());
3127        extras.insert("vminpu".into(), (*v_min_pu).into());
3128        extras.insert("vmaxpu".into(), (*v_max_pu).into());
3129        Some(*cutoff_pu)
3130    } else {
3131        None
3132    }
3133}
3134
3135#[cfg(test)]
3136mod tests {
3137    use super::*;
3138    use crate::model::MulticonductorNetworkTables;
3139    use crate::model::{
3140        ControlVoltageReference, DistControlProfile, DistGenerator, DistIbr, DistLine,
3141        DistLineCode, DistLoad, DistShunt, DistSwitch, DistTransformer, DistWinding, IbrPrimeMover,
3142        IbrTopology, ReactivePowerReference, ReactivePowerUnit, VoltVarControl, VoltageSource,
3143    };
3144    use crate::testkit::parse_dss_str;
3145
3146    #[test]
3147    #[ignore = "writes diagnostic native replay files; requires pinned external four-wire inputs"]
3148    fn export_generator_user_model_native_probe() {
3149        let input = std::path::PathBuf::from(std::env::var("POWERIO_MOTOR_INPUT").unwrap());
3150        let output = std::path::PathBuf::from(std::env::var("POWERIO_MOTOR_OUTPUT").unwrap());
3151        std::fs::create_dir(&output).unwrap();
3152        let name = "Kersting4wireIndMotor.dss";
3153        let net = parse_dss_str(&std::fs::read_to_string(input.join(name)).unwrap());
3154        assert!(!crate::audit_electrical_readiness(&net).is_ready());
3155        // Deliberately exercise only the low-level writer. Public canonical
3156        // emission remains blocked until the motor law is typed; this probe
3157        // diagnoses source-property replay, never feeder qualification.
3158        std::fs::write(output.join(name), emit_dss_text(&net).text).unwrap();
3159    }
3160
3161    fn strings(v: &[&str]) -> Vec<String> {
3162        v.iter().map(ToString::to_string).collect()
3163    }
3164
3165    fn bus(id: &str, terminals: &[&str], grounded: &[&str]) -> DistBus {
3166        DistBus {
3167            id: id.into(),
3168            terminals: strings(terminals),
3169            grounded: strings(grounded),
3170            ..DistBus::default()
3171        }
3172    }
3173
3174    /// A source bus and a secondary spelled the way a center tapped service
3175    /// is: two hot terminals with the grounded return between them.
3176    fn center_tap_service(vln: f64) -> (DistBus, VoltageSource, DistBus) {
3177        let (mut source, vs) = three_phase_source(vln);
3178        source.id = "sb".into();
3179        (source, vs, bus("lv", &["p1", "n", "p2"], &["n"]))
3180    }
3181
3182    fn three_phase_source(vln: f64) -> (DistBus, VoltageSource) {
3183        let third = 2.0 * std::f64::consts::FRAC_PI_3;
3184        (
3185            bus("sb", &["1", "2", "3", "4"], &["4"]),
3186            VoltageSource {
3187                reference_terminal: None,
3188                name: "source".into(),
3189                bus: "sb".into(),
3190                terminal_map: strings(&["1", "2", "3", "4"]),
3191                v_magnitude: vec![vln, vln, vln, 0.0],
3192                v_angle: vec![0.0, -third, third, 0.0],
3193                energy_cost_rate: None,
3194                extras: Extras::new(),
3195            },
3196        )
3197    }
3198
3199    fn load_on(bus: &str, map: &[&str], configuration: Configuration) -> DistLoad {
3200        let phases = map.len();
3201        DistLoad {
3202            name: "ld".into(),
3203            bus: bus.into(),
3204            terminal_map: strings(map),
3205            configuration,
3206            p_nom: vec![1e3; phases],
3207            q_nom: vec![0.0; phases],
3208            voltage_model: DistLoadVoltageModel::ConstantPower { v_nom: Vec::new() },
3209            extras: Extras::from([("kv".to_string(), serde_json::json!("0.4"))]),
3210        }
3211    }
3212
3213    fn terminal_order_network(map: &[&str]) -> MulticonductorNetwork {
3214        let (source_bus, source) = three_phase_source(240.0);
3215        let element_map = strings(map);
3216
3217        let capacitor = crate::model::DistCapacitor::new(
3218            "cap",
3219            "lv",
3220            element_map.clone(),
3221            Configuration::SinglePhase,
3222            1_000.0,
3223            240.0,
3224        );
3225        let mut generator = DistGenerator::new(
3226            "gen",
3227            "lv",
3228            element_map.clone(),
3229            Configuration::SinglePhase,
3230            vec![1_000.0],
3231            vec![0.0],
3232        );
3233        generator
3234            .extras
3235            .insert("kv".into(), serde_json::json!(0.24));
3236
3237        let mut fixed_ibr = DistIbr::new(
3238            "fixed_ibr",
3239            "lv",
3240            element_map.clone(),
3241            IbrTopology::SinglePhase,
3242            IbrPrimeMover::Pv,
3243            vec![1_000.0],
3244        );
3245        fixed_ibr.p_min = Some(vec![1_000.0]);
3246        fixed_ibr.p_max = Some(vec![1_000.0]);
3247        fixed_ibr.q_min = Some(vec![0.0]);
3248        fixed_ibr.q_max = Some(vec![0.0]);
3249        fixed_ibr
3250            .extras
3251            .insert("kv".into(), serde_json::json!(0.24));
3252
3253        let mut pv_ibr = DistIbr::new(
3254            "pv_ibr",
3255            "lv",
3256            element_map.clone(),
3257            IbrTopology::SinglePhase,
3258            IbrPrimeMover::Pv,
3259            vec![1_000.0],
3260        );
3261        pv_ibr.p_avail = Some(1_000.0);
3262        pv_ibr.extras.insert("kv".into(), serde_json::json!(0.24));
3263
3264        MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
3265            name: Some("terminal_order".into()),
3266            base_frequency: 60.0,
3267            buses: vec![source_bus, bus("lv", map, &["n"])],
3268            sources: vec![source],
3269            lines: vec![DistLine::new(
3270                "l1",
3271                "lv",
3272                "lv",
3273                element_map.clone(),
3274                element_map.clone(),
3275                "lc",
3276                1.0,
3277            )],
3278            switches: vec![DistSwitch::new(
3279                "sw1",
3280                "lv",
3281                "lv",
3282                element_map.clone(),
3283                element_map,
3284                false,
3285            )],
3286            generators: vec![generator],
3287            ibrs: vec![fixed_ibr, pv_ibr],
3288            capacitors: vec![capacitor],
3289            ..MulticonductorNetworkTables::default()
3290        })
3291    }
3292
3293    fn terminal_order_diagnostics(
3294        out: &crate::convert::TextEmission,
3295    ) -> Vec<&crate::diagnostics::Diagnostic> {
3296        out.diagnostics
3297            .iter()
3298            .filter(|d| d.code() == C::EMIT_DSS_TERMINAL_ORDER_UNREPRESENTABLE.code)
3299            .collect()
3300    }
3301
3302    fn roundtrip(net: &MulticonductorNetwork) -> (String, String) {
3303        let first = emit_dss_text(net);
3304        let second = emit_dss_text(&parse_dss_str(&first.text));
3305        (first.text, second.text)
3306    }
3307
3308    #[test]
3309    fn constant_power_loads_get_wide_voltage_bounds_by_default() {
3310        let (b, vs) = three_phase_source(2400.0);
3311        let load = load_on("sb", &["1"], Configuration::Wye);
3312        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
3313            base_frequency: 60.0,
3314            buses: vec![b],
3315            sources: vec![vs],
3316            loads: vec![load],
3317            ..MulticonductorNetworkTables::default()
3318        });
3319        let out = emit_dss_text(&net);
3320        let line = out.text.lines().find(|l| l.contains("Load.ld")).unwrap();
3321        assert!(line.contains("vminpu=0"), "{line}");
3322        assert!(line.contains("vlowpu=0"), "{line}");
3323        assert!(line.contains("vmaxpu=2"), "{line}");
3324    }
3325
3326    #[test]
3327    fn explicit_load_voltage_bounds_are_preserved() {
3328        let (b, vs) = three_phase_source(2400.0);
3329        let mut load = load_on("sb", &["1"], Configuration::Wye);
3330        load.extras.insert("vminpu".into(), serde_json::json!(0.8));
3331        load.extras.insert("vmaxpu".into(), serde_json::json!(1.2));
3332        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
3333            base_frequency: 60.0,
3334            buses: vec![b],
3335            sources: vec![vs],
3336            loads: vec![load],
3337            ..MulticonductorNetworkTables::default()
3338        });
3339        let out = emit_dss_text(&net);
3340        let line = out.text.lines().find(|l| l.contains("Load.ld")).unwrap();
3341        assert!(line.contains("vminpu=0.8"), "{line}");
3342        assert!(line.contains("vmaxpu=1.2"), "{line}");
3343    }
3344
3345    #[test]
3346    fn default_load_voltage_bounds_can_be_disabled() {
3347        let (b, vs) = three_phase_source(2400.0);
3348        let load = load_on("sb", &["1"], Configuration::Wye);
3349        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
3350            base_frequency: 60.0,
3351            buses: vec![b],
3352            sources: vec![vs],
3353            loads: vec![load],
3354            ..MulticonductorNetworkTables::default()
3355        });
3356        let options = DssEmitOptions {
3357            default_load_voltage_bounds: None,
3358            ..DssEmitOptions::default()
3359        };
3360        let out = emit_dss_text_with_options(&net, &options);
3361        let line = out.text.lines().find(|l| l.contains("Load.ld")).unwrap();
3362        assert!(!line.contains("vminpu="), "{line}");
3363        assert!(!line.contains("vmaxpu="), "{line}");
3364    }
3365
3366    #[test]
3367    fn voltage_bases_survive_the_sqrt_round_trip() {
3368        // basekv = vln*sqrt(3)/1e3 then vln' = basekv*1e3/sqrt(3) is not a
3369        // float fixed point for this PMD shaped value. Both writes must
3370        // preserve the electrical voltage base within rounding precision.
3371        let vln = 9_336.235_056_420_312_f64;
3372        let basekv = vln * 3f64.sqrt() / 1e3;
3373        assert!(
3374            (basekv * 1e3 / 3f64.sqrt()).to_bits() != vln.to_bits(),
3375            "test value no longer reproduces the drift"
3376        );
3377        let (b, vs) = three_phase_source(vln);
3378        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
3379            name: Some("t".into()),
3380            base_frequency: 60.0,
3381            buses: vec![b],
3382            sources: vec![vs],
3383            ..MulticonductorNetworkTables::default()
3384        });
3385        let (first, second) = roundtrip(&net);
3386        assert!(first.contains("Set VoltageBases="), "{first}");
3387        let bases = |text: &str| {
3388            text.lines()
3389                .find_map(|line| line.strip_prefix("Set VoltageBases=["))
3390                .unwrap()
3391                .trim_end_matches(']')
3392                .parse::<f64>()
3393                .unwrap()
3394        };
3395        assert!((bases(&first) - basekv).abs() < 1e-12);
3396        assert!((bases(&second) - basekv).abs() < 1e-12);
3397    }
3398
3399    #[test]
3400    fn load_phases_prefer_the_reader_stash() {
3401        let (b, vs) = three_phase_source(2400.0);
3402        let mut load = load_on("sb", &["1", "2", "3"], Configuration::Delta);
3403        load.extras.insert("phases".into(), serde_json::json!("2"));
3404        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
3405            base_frequency: 60.0,
3406            buses: vec![b],
3407            sources: vec![vs],
3408            loads: vec![load],
3409            ..MulticonductorNetworkTables::default()
3410        });
3411        let out = emit_dss_text(&net);
3412        let line = out.text.lines().find(|l| l.contains("Load.ld")).unwrap();
3413        assert!(line.contains("phases=2 conn=delta"), "{line}");
3414        // The stash must not double emit through the extras tail.
3415        assert_eq!(line.matches("phases=").count(), 1, "{line}");
3416        assert!(
3417            !out.render_diagnostics()
3418                .iter()
3419                .any(|w| w.contains("2 or 3 phase"))
3420        );
3421    }
3422
3423    #[test]
3424    fn ambiguous_delta_keeps_three_phases_loudly() {
3425        let (b, vs) = three_phase_source(2400.0);
3426        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
3427            base_frequency: 60.0,
3428            buses: vec![b],
3429            sources: vec![vs],
3430            loads: vec![load_on("sb", &["1", "2", "3"], Configuration::Delta)],
3431            ..MulticonductorNetworkTables::default()
3432        });
3433        let out = emit_dss_text(&net);
3434        let line = out.text.lines().find(|l| l.contains("Load.ld")).unwrap();
3435        assert!(line.contains("phases=3 conn=delta"), "{line}");
3436        assert!(
3437            out.render_diagnostics()
3438                .iter()
3439                .any(|w| w.contains("2 or 3 phase")),
3440            "{:?}",
3441            out.render_diagnostics()
3442        );
3443    }
3444
3445    #[test]
3446    fn single_phase_delta_emits_conn_delta() {
3447        let (b, vs) = three_phase_source(2400.0);
3448        // Two conductor delta typed as Delta: phases=1 conn=delta.
3449        let two_wire = load_on("sb", &["1", "2"], Configuration::Delta);
3450        // The reader types 1 phase delta as SinglePhase; the stashed conn
3451        // token carries the delta.
3452        let mut stashed = load_on("sb", &["1", "2"], Configuration::SinglePhase);
3453        stashed.name = "ld2".into();
3454        stashed
3455            .extras
3456            .insert("conn".into(), serde_json::json!("delta"));
3457        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
3458            base_frequency: 60.0,
3459            buses: vec![b],
3460            sources: vec![vs],
3461            loads: vec![two_wire, stashed],
3462            ..MulticonductorNetworkTables::default()
3463        });
3464        let out = emit_dss_text(&net);
3465        let l1 = out.text.lines().find(|l| l.contains("Load.ld ")).unwrap();
3466        assert!(l1.contains("phases=1 conn=delta"), "{l1}");
3467        let l2 = out.text.lines().find(|l| l.contains("Load.ld2 ")).unwrap();
3468        assert!(l2.contains("phases=1 conn=delta"), "{l2}");
3469        assert_eq!(l2.matches("conn=").count(), 1, "{l2}");
3470    }
3471
3472    #[test]
3473    fn unrepresentable_names_are_replaced_and_reported() {
3474        let (b, vs) = three_phase_source(2400.0);
3475        let mut load = load_on("sb", &["1", "2", "3", "4"], Configuration::Wye);
3476        load.name = "load 1".into();
3477        let mut net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
3478            name: Some("my circuit".into()),
3479            base_frequency: 60.0,
3480            buses: vec![b, bus("a=b", &["1"], &[])],
3481            sources: vec![vs],
3482            loads: vec![load],
3483            ..MulticonductorNetworkTables::default()
3484        });
3485        net.lines_mut().push(DistLine {
3486            name: "l1".into(),
3487            bus_from: "sb".into(),
3488            bus_to: "a=b".into(),
3489            terminal_map_from: strings(&["1"]),
3490            terminal_map_to: strings(&["1"]),
3491            linecode: "lc".into(),
3492            length: 1.0,
3493            route: None,
3494            i_max: None,
3495            s_max: None,
3496            extras: Extras::new(),
3497        });
3498        let out = emit_dss_text(&net);
3499        let rendered = out.render_diagnostics();
3500        for (old, new) in [
3501            ("load 1", "load_1"),
3502            ("my circuit", "my_circuit"),
3503            ("a=b", "a_b"),
3504        ] {
3505            assert!(
3506                rendered.iter().any(|w| w.contains(&format!("`{old}`"))
3507                    && w.contains(&format!("written as `{new}`"))),
3508                "{old}: {rendered:?}"
3509            );
3510        }
3511        assert!(
3512            !rendered.iter().any(|w| w.contains("cannot represent")),
3513            "{rendered:?}"
3514        );
3515        // Every reference uses the replacement.
3516        assert!(out.text.contains("New Circuit.my_circuit "), "{}", out.text);
3517        assert!(out.text.contains("New Load.load_1 "), "{}", out.text);
3518        assert!(out.text.contains("bus2=a_b.1 "), "{}", out.text);
3519        assert!(!out.text.contains("a=b"), "{}", out.text);
3520    }
3521
3522    #[test]
3523    fn unequal_per_phase_i_max_warns_that_emergamps_holds_one_phase() {
3524        let (b, vs) = three_phase_source(2400.0);
3525        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
3526            base_frequency: 60.0,
3527            buses: vec![b, bus("b2", &["1", "2", "3"], &[])],
3528            sources: vec![vs],
3529            lines: vec![DistLine {
3530                name: "l1".into(),
3531                bus_from: "sb".into(),
3532                bus_to: "b2".into(),
3533                terminal_map_from: strings(&["1", "2", "3"]),
3534                terminal_map_to: strings(&["1", "2", "3"]),
3535                linecode: "lc".into(),
3536                length: 1.0,
3537                route: None,
3538                i_max: Some(vec![400.0, 300.0, 200.0]),
3539                s_max: None,
3540                extras: Extras::new(),
3541            }],
3542            ..MulticonductorNetworkTables::default()
3543        });
3544        let out = emit_dss_text(&net);
3545        let line = out.text.lines().find(|l| l.contains("Line.l1 ")).unwrap();
3546        assert!(line.contains("emergamps=400"), "{line}");
3547        assert!(
3548            out.render_diagnostics()
3549                .iter()
3550                .any(|w| w.contains("line l1") && w.contains("not equal on all phases")),
3551            "{:?}",
3552            out.render_diagnostics()
3553        );
3554    }
3555
3556    #[test]
3557    fn line_level_i_max_emits_emergamps_and_s_max_drops_with_a_warning() {
3558        let (b, vs) = three_phase_source(2400.0);
3559        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
3560            base_frequency: 60.0,
3561            buses: vec![b, bus("b2", &["1"], &[])],
3562            sources: vec![vs],
3563            lines: vec![DistLine {
3564                name: "l1".into(),
3565                bus_from: "sb".into(),
3566                bus_to: "b2".into(),
3567                terminal_map_from: strings(&["1"]),
3568                terminal_map_to: strings(&["1"]),
3569                linecode: "lc".into(),
3570                length: 1.0,
3571                route: None,
3572                i_max: Some(vec![400.0]),
3573                s_max: Some(vec![600.0]),
3574                extras: Extras::new(),
3575            }],
3576            ..MulticonductorNetworkTables::default()
3577        });
3578        let out = emit_dss_text(&net);
3579        let line = out.text.lines().find(|l| l.contains("Line.l1 ")).unwrap();
3580        assert!(line.contains("emergamps=400"), "{line}");
3581        assert!(
3582            !out.render_diagnostics()
3583                .iter()
3584                .any(|w| w.contains("line l1") && w.contains("i_max")),
3585            "{:?}",
3586            out.render_diagnostics()
3587        );
3588        assert!(
3589            out.render_diagnostics()
3590                .iter()
3591                .any(|w| w.contains("line l1") && w.contains("s_max") && w.contains("dropped")),
3592            "{:?}",
3593            out.render_diagnostics()
3594        );
3595    }
3596
3597    #[test]
3598    fn line_level_emergamps_round_trips_as_i_max() {
3599        let src = "Clear\n\
3600                   New Circuit.c1 basekv=12.47 pu=1 angle=0 phases=3 bus1=sb.1.2.3\n\
3601                   New Linecode.lc nphases=3 r1=0.1 x1=0.2 emergamps=600\n\
3602                   New Line.l1 bus1=sb.1.2.3 bus2=b2.1.2.3 phases=3 linecode=lc \
3603                   length=10 units=m emergamps=250\n\
3604                   New Line.l2 bus1=b2.1.2.3 bus2=b3.1.2.3 phases=3 linecode=lc \
3605                   length=10 units=m\n";
3606        let net = parse_dss_str(src);
3607        let l1 = net.lines().iter().find(|l| l.name == "l1").unwrap();
3608        assert_eq!(l1.i_max.as_deref(), Some(&[250.0, 250.0, 250.0][..]));
3609        assert!(!l1.extras.contains_key("emergamps"), "{:?}", l1.extras);
3610        // The line carries the linecode rating copied at assignment time.
3611        let l2 = net.lines().iter().find(|l| l.name == "l2").unwrap();
3612        assert_eq!(l2.i_max.as_deref(), Some(&[600.0, 600.0, 600.0][..]));
3613
3614        let (first, second) = roundtrip(&net);
3615        let line = first.lines().find(|l| l.contains("Line.l1 ")).unwrap();
3616        assert!(line.contains("emergamps=250"), "{line}");
3617        assert_eq!(line.matches("emergamps=").count(), 1, "{line}");
3618        let line2 = first.lines().find(|l| l.contains("Line.l2 ")).unwrap();
3619        assert!(line2.contains("emergamps=600"), "{line2}");
3620        let restored = parse_dss_str(&second);
3621        assert_eq!(
3622            restored
3623                .lines()
3624                .iter()
3625                .find(|l| l.name == "l1")
3626                .unwrap()
3627                .i_max,
3628            l1.i_max
3629        );
3630        assert_eq!(
3631            restored
3632                .lines()
3633                .iter()
3634                .find(|l| l.name == "l2")
3635                .unwrap()
3636                .i_max,
3637            l2.i_max
3638        );
3639    }
3640
3641    #[test]
3642    fn unrated_switch_round_trips_without_a_default_rating() {
3643        // `switch=yes` leaves an unstated emergency rating unstated, so the
3644        // canonical deck states none and the reread line has no limit (#762).
3645        let src = "Clear\n\
3646                   New Circuit.c1 basekv=12.47 pu=1 angle=0 phases=3 bus1=sb.1.2.3\n\
3647                   New Linecode.lc nphases=3 r1=0.1 x1=0.2\n\
3648                   New Line.bare bus1=sb.1.2.3 bus2=b2.1.2.3 phases=3 switch=yes\n\
3649                   New Line.coded bus1=b2.1.2.3 bus2=b3.1.2.3 phases=3 switch=yes \
3650                   linecode=lc\n";
3651        let net = parse_dss_str(src);
3652        let i_max = |net: &MulticonductorNetwork, name: &str| {
3653            net.lines()
3654                .iter()
3655                .find(|l| l.name == name)
3656                .unwrap()
3657                .i_max
3658                .clone()
3659        };
3660        assert_eq!(i_max(&net, "bare"), None);
3661        assert_eq!(i_max(&net, "coded"), None);
3662        let (first, second) = roundtrip(&net);
3663        for name in ["bare", "coded"] {
3664            let line = first
3665                .lines()
3666                .find(|l| l.contains(&format!("Line.{name} ")))
3667                .unwrap();
3668            assert!(!line.contains("emergamps="), "{line}");
3669        }
3670        let restored = parse_dss_str(&second);
3671        assert_eq!(i_max(&restored, "bare"), None);
3672        assert_eq!(i_max(&restored, "coded"), None);
3673    }
3674
3675    #[test]
3676    fn unparsable_line_emergamps_refuses_partial_network_and_retains_source() {
3677        let src = "Clear\n\
3678                   New Circuit.c1 basekv=12.47 pu=1 angle=0 phases=3 bus1=sb.1.2.3\n\
3679                   New Linecode.lc nphases=3 r1=0.1 x1=0.2\n\
3680                   New Line.l1 bus1=sb.1.2.3 bus2=b2.1.2.3 phases=3 linecode=lc \
3681                   length=10 units=m emergamps=@amps\n";
3682        let error =
3683            crate::parse(powerio_core::Source::from_memory("bad.dss", src.as_bytes()).unwrap())
3684                .unwrap_err();
3685        assert!(
3686            error
3687                .diagnostics()
3688                .iter()
3689                .any(|d| d.code() == C::READ_DSS_LINE_UNRESOLVED.code)
3690        );
3691        assert_eq!(
3692            error
3693                .retained_source()
3694                .unwrap()
3695                .primary_buffer()
3696                .unwrap()
3697                .bytes(),
3698            src.as_bytes()
3699        );
3700    }
3701
3702    #[test]
3703    fn unparseable_kv_extra_warns_instead_of_silently_substituting() {
3704        let (b, vs) = three_phase_source(2400.0);
3705        let mut load = load_on("sb", &["1", "2", "3", "4"], Configuration::Wye);
3706        load.extras.insert("kv".into(), serde_json::json!("@kv"));
3707        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
3708            base_frequency: 60.0,
3709            buses: vec![b],
3710            sources: vec![vs],
3711            loads: vec![load],
3712            ..MulticonductorNetworkTables::default()
3713        });
3714        let out = emit_dss_text(&net);
3715        assert!(
3716            out.render_diagnostics()
3717                .iter()
3718                .any(|w| w.contains("@kv") && w.contains("does not parse")),
3719            "{:?}",
3720            out.render_diagnostics()
3721        );
3722        // The estimate substitutes: 2400*sqrt(3)/1e3 line to line.
3723        let line = out.text.lines().find(|l| l.contains("Load.ld")).unwrap();
3724        assert!(
3725            line.contains(&format!("kv={}", num(2400.0 * 3f64.sqrt() / 1e3))),
3726            "{line}"
3727        );
3728    }
3729
3730    #[test]
3731    fn options_reemit_and_commands_warn() {
3732        let src = "Clear\n\
3733                   New Circuit.c1 basekv=12.47 pu=1 angle=0 phases=3 bus1=sb\n\
3734                   Set mode=snapshot\n\
3735                   Set controlmode=OFF\n\
3736                   Disable Line.l1\n\
3737                   Set VoltageBases=[12.47]\n\
3738                   Calcvoltagebases\n\
3739                   Solve\n";
3740        let out = emit_dss_text(&parse_dss_str(src));
3741        assert!(out.text.contains("Set mode=snapshot"), "{}", out.text);
3742        assert!(out.text.contains("Set controlmode=OFF"), "{}", out.text);
3743        // The writer derives these; the stored options must not double them.
3744        assert_eq!(out.text.matches("Set VoltageBases").count(), 1);
3745        assert_eq!(out.text.matches("Calcvoltagebases").count(), 1);
3746        assert_eq!(out.text.matches("DefaultBaseFrequency").count(), 1);
3747        assert!(!out.text.to_lowercase().contains("disable"));
3748        assert!(
3749            out.render_diagnostics()
3750                .iter()
3751                .any(|w| w.contains("disable Line.l1") && w.contains("not regenerated")),
3752            "{:?}",
3753            out.render_diagnostics()
3754        );
3755        // Solve and Calcvoltagebases re-derive; no warning claims they drop.
3756        assert!(
3757            !out.render_diagnostics()
3758                .iter()
3759                .any(|w| w.contains("`solve`"))
3760        );
3761        let again = emit_dss_text(&parse_dss_str(&out.text));
3762        assert!(again.text.contains("Set controlmode=OFF"));
3763        assert_eq!(
3764            parse_dss_str(&again.text).base_frequency().to_bits(),
3765            60.0_f64.to_bits()
3766        );
3767    }
3768
3769    #[test]
3770    fn non_numeric_terminal_positionalizes() {
3771        let mut load = load_on("b1", &["a", "n"], Configuration::Wye);
3772        load.extras.insert("kv".into(), serde_json::json!("0.23"));
3773        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
3774            base_frequency: 60.0,
3775            buses: vec![bus("b1", &["a", "n"], &["n"])],
3776            loads: vec![load],
3777            ..MulticonductorNetworkTables::default()
3778        });
3779        let (first, second) = roundtrip(&net);
3780        let line = first.lines().find(|l| l.contains("Load.ld")).unwrap();
3781        assert!(line.contains("bus1=b1.1.0"), "{line}");
3782        let out = emit_dss_text(&net);
3783        assert!(
3784            out.render_diagnostics()
3785                .iter()
3786                .any(|w| w.contains("`a`") && w.contains("position")),
3787            "{:?}",
3788            out.render_diagnostics()
3789        );
3790        let restored = parse_dss_str(&second);
3791        assert_eq!(restored.loads()[0].terminal_map, ["1", "4"]);
3792    }
3793
3794    #[test]
3795    fn untyped_thevenin_extra_is_diagnosed_without_changing_ideal_source() {
3796        let (b, mut vs) = three_phase_source(2400.0);
3797        vs.extras
3798            .insert("rs".into(), serde_json::json!([[1.0, 0.1], [0.1, 1.0]]));
3799        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
3800            base_frequency: 60.0,
3801            buses: vec![b],
3802            sources: vec![vs],
3803            ..MulticonductorNetworkTables::default()
3804        });
3805        let out = emit_dss_text(&net);
3806        assert!(!out.text.contains("z1="), "{}", out.text);
3807        assert!(
3808            out.render_diagnostics()
3809                .iter()
3810                .any(|w| w.contains("extra rs")
3811                    && w.contains("not part of the typed ideal voltage constraint")),
3812            "{:?}",
3813            out.render_diagnostics()
3814        );
3815    }
3816
3817    #[test]
3818    fn unusable_switch_sequence_extras_warn() {
3819        let (b, vs) = three_phase_source(2400.0);
3820        let sw = DistSwitch {
3821            name: "sw1".into(),
3822            bus_from: "sb".into(),
3823            bus_to: "b2".into(),
3824            terminal_map_from: strings(&["1", "2", "3"]),
3825            terminal_map_to: strings(&["1", "2", "3"]),
3826            open: false,
3827            i_max: Some(Vec::new()),
3828            extras: Extras::from([("pmd_rs".to_string(), serde_json::json!("oops"))]),
3829        };
3830        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
3831            base_frequency: 60.0,
3832            buses: vec![b, bus("b2", &["1", "2", "3"], &[])],
3833            sources: vec![vs],
3834            switches: vec![sw],
3835            ..MulticonductorNetworkTables::default()
3836        });
3837        let out = emit_dss_text(&net);
3838        let switch = out
3839            .text
3840            .lines()
3841            .find(|line| line.starts_with("New Line.sw1 "))
3842            .unwrap();
3843        assert!(!switch.contains("r0="), "{switch}");
3844        assert!(
3845            out.render_diagnostics()
3846                .iter()
3847                .any(|w| w.contains("pmd_rs") && w.contains("not a numeric matrix")),
3848            "{:?}",
3849            out.render_diagnostics()
3850        );
3851        assert!(
3852            out.render_diagnostics()
3853                .iter()
3854                .any(|w| w.contains("i_max is empty")),
3855            "{:?}",
3856            out.render_diagnostics()
3857        );
3858    }
3859
3860    #[test]
3861    fn malformed_matrix_is_rejected_before_emission() {
3862        let (b, vs) = three_phase_source(2400.0);
3863        let lc = DistLineCode {
3864            name: "lc1".into(),
3865            n_conductors: 2,
3866            r_series: vec![vec![1.0], vec![0.5]], // second row short
3867            x_series: vec![vec![1.0, 0.0], vec![0.0, 1.0]],
3868            g_from: vec![vec![0.0; 2]; 2],
3869            b_from: vec![vec![0.0; 2]; 2],
3870            g_to: vec![vec![0.0; 2]; 2],
3871            b_to: vec![vec![0.0; 2]; 2],
3872            i_max: Some(Vec::new()),
3873            s_max: None,
3874            source: None,
3875            extras: Extras::new(),
3876        };
3877        let t = DistTransformer {
3878            name: "t1".into(),
3879            windings: vec![
3880                DistWinding {
3881                    bus: "sb".into(),
3882                    terminal_map: strings(&["1", "2"]),
3883                    conn: DistWindingConn::Wye,
3884                    v_ref: 2400.0,
3885                    s_rating: 25e3,
3886                    r_pct: 0.5,
3887                    tap: 1.0,
3888                    r_neutral: None,
3889                    x_neutral: None,
3890                },
3891                DistWinding {
3892                    bus: "b2".into(),
3893                    terminal_map: strings(&["1", "2"]),
3894                    conn: DistWindingConn::Wye,
3895                    v_ref: 240.0,
3896                    s_rating: 25e3,
3897                    r_pct: 0.5,
3898                    tap: 1.0,
3899                    r_neutral: None,
3900                    x_neutral: None,
3901                },
3902            ],
3903            xsc_pct: Vec::new(),
3904            phases: 1,
3905            extras: Extras::new(),
3906        };
3907        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
3908            base_frequency: 60.0,
3909            buses: vec![b, bus("b2", &["1", "2"], &[])],
3910            sources: vec![vs],
3911            line_codes: vec![lc],
3912            transformers: vec![t],
3913            ..MulticonductorNetworkTables::default()
3914        });
3915        let error = validate_emission(&net).unwrap_err();
3916        assert!(
3917            error.to_string().contains("MATRIX.SHAPE_MISMATCH"),
3918            "{error}"
3919        );
3920    }
3921
3922    #[test]
3923    fn a_rated_capacitor_bank_writes_as_a_dss_capacitor() {
3924        // #266 item 1: `q_rated` at `v_nom` is what an OpenDSS Capacitor takes,
3925        // so the conversion is a unit change and the terminal spelling. The
3926        // bank used to be dropped with a warning.
3927        let (b, vs) = three_phase_source(2400.0);
3928        let cap = crate::model::DistCapacitor::new(
3929            "c1",
3930            "sb",
3931            strings(&["1", "2", "3", "n"]),
3932            Configuration::Wye,
3933            600e3,
3934            4160.0,
3935        );
3936        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
3937            base_frequency: 60.0,
3938            buses: vec![b],
3939            sources: vec![vs],
3940            capacitors: vec![cap],
3941            ..MulticonductorNetworkTables::default()
3942        });
3943        let out = emit_dss_text(&net);
3944        let line = out
3945            .text
3946            .lines()
3947            .find(|l| l.contains("Capacitor.c1"))
3948            .unwrap_or_else(|| panic!("no capacitor emitted: {}", out.text));
3949        assert!(line.contains("kvar=600"), "{line}");
3950        assert!(line.contains("kv=4.16"), "{line}");
3951        assert!(line.contains("phases=3"), "{line}");
3952        assert!(
3953            !out.render_diagnostics()
3954                .iter()
3955                .any(|w| w.contains("dropped")),
3956            "{:?}",
3957            out.render_diagnostics()
3958        );
3959
3960        // And it comes back: the reader lowers a dss Capacitor to a shunt B
3961        // matrix, so the bank survives as susceptance carrying the same vars.
3962        let back = parse_dss_str(&out.text);
3963        assert_eq!(back.shunts().len(), 1, "{}", out.text);
3964    }
3965
3966    #[test]
3967    fn an_unbalanced_load_splits_into_one_load_per_phase() {
3968        // #266 item 2: a dss Load divides kw evenly across its phases, so one
3969        // balanced object keeps the total and loses the profile. Splitting
3970        // keeps both, and a balanced load still emits as one object.
3971        let (b, vs) = three_phase_source(2400.0);
3972        let mut unbalanced = DistLoad::new(
3973            "l1",
3974            "sb",
3975            strings(&["1", "2", "3", "n"]),
3976            Configuration::Wye,
3977            vec![1e3, 2e3, 3e3],
3978            vec![100.0, 200.0, 300.0],
3979        );
3980        unbalanced.extras.insert("kv".into(), 4.16.into());
3981        let balanced = DistLoad::new(
3982            "l2",
3983            "sb",
3984            strings(&["1", "2", "3", "n"]),
3985            Configuration::Wye,
3986            vec![1e3, 1e3, 1e3],
3987            vec![100.0, 100.0, 100.0],
3988        );
3989        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
3990            base_frequency: 60.0,
3991            buses: vec![b],
3992            sources: vec![vs],
3993            loads: vec![unbalanced, balanced],
3994            ..MulticonductorNetworkTables::default()
3995        });
3996        let out = emit_dss_text(&net);
3997        let loads: Vec<&str> = out
3998            .text
3999            .lines()
4000            .filter(|l| l.contains("New Load."))
4001            .collect();
4002        assert_eq!(loads.len(), 4, "{}", out.text);
4003        for (name, kw, kvar) in [
4004            ("l1_1", "1", "0.1"),
4005            ("l1_2", "2", "0.2"),
4006            ("l1_3", "3", "0.3"),
4007        ] {
4008            let line = loads
4009                .iter()
4010                .find(|l| l.contains(&format!("New Load.{name} ")))
4011                .unwrap_or_else(|| panic!("no {name}: {}", out.text));
4012            assert!(line.contains(&format!("kw={kw} ")), "{line}");
4013            assert!(line.contains(&format!("kvar={kvar}")), "{line}");
4014            assert!(line.contains("phases=1"), "{line}");
4015            // The whole-bank kv extra does not carry to a single phase part.
4016            assert!(!line.contains("kv=4.16"), "{line}");
4017        }
4018        assert_eq!(
4019            loads.iter().filter(|l| l.contains("New Load.l2 ")).count(),
4020            1,
4021            "a balanced load stays one object: {}",
4022            out.text
4023        );
4024    }
4025
4026    #[test]
4027    fn a_center_tap_load_splits_onto_its_two_legs() {
4028        // PowerIO.jl#79. A center tapped service maps as `[p1, n, p2]`, and
4029        // dss reads a node list positionally, so one record over that map
4030        // states the wrong node pair and drops the conductors it cannot
4031        // address. The powers are equal, so the imbalance split never fires.
4032        let (b, vs, lv) = center_tap_service(11000.0);
4033        let l = DistLoad {
4034            name: "ld".into(),
4035            bus: "lv".into(),
4036            terminal_map: strings(&["p1", "n", "p2"]),
4037            configuration: Configuration::Wye,
4038            p_nom: vec![1304.0, 1304.0],
4039            q_nom: vec![978.0, 978.0],
4040            voltage_model: DistLoadVoltageModel::ConstantImpedance { v_nom: Vec::new() },
4041            extras: Extras::new(),
4042        };
4043        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
4044            base_frequency: 60.0,
4045            buses: vec![b, lv],
4046            sources: vec![vs],
4047            loads: vec![l],
4048            ..MulticonductorNetworkTables::default()
4049        });
4050        let out = emit_dss_text(&net);
4051        let loads: Vec<&str> = out
4052            .text
4053            .lines()
4054            .filter(|l| l.contains("New Load."))
4055            .collect();
4056        assert_eq!(loads.len(), 2, "{}", out.text);
4057        // Each leg carries half the power over its own hot node and the
4058        // grounded return, which dss spells as node 0.
4059        for (name, node) in [("ld_p1", "lv.1.0"), ("ld_p2", "lv.3.0")] {
4060            let line = loads
4061                .iter()
4062                .find(|l| l.contains(&format!("New Load.{name} ")))
4063                .unwrap_or_else(|| panic!("no {name}: {}", out.text));
4064            assert!(line.contains(&format!("bus1={node} ")), "{line}");
4065            assert!(line.contains("phases=1"), "{line}");
4066            assert!(line.contains("kw=1.304"), "{line}");
4067            assert!(line.contains("kvar=0.978"), "{line}");
4068        }
4069    }
4070
4071    #[test]
4072    fn misordered_grounded_returns_reorder_when_nothing_is_indexed() {
4073        let out = emit_dss_text(&terminal_order_network(&["p1", "n", "p2"]));
4074        let diagnostics = terminal_order_diagnostics(&out);
4075
4076        // The four element classes and the switch carry no conductor indexed
4077        // data into their records, so their node lists reorder return-last
4078        // with a declared substitution. The line references linecode `lc`,
4079        // which this network does not define, so its matrices cannot be
4080        // permuted in step and the order error stands for both endpoints.
4081        assert_eq!(diagnostics.len(), 2, "{:?}", out.diagnostics);
4082        for diagnostic in &diagnostics {
4083            assert_eq!(diagnostic.details()["class"], "line");
4084            assert_eq!(diagnostic.details()["element_name"], "l1");
4085        }
4086        let reordered = out
4087            .diagnostics
4088            .iter()
4089            .filter(|d| d.message().contains("moved last"))
4090            .count();
4091        assert_eq!(reordered, 5, "{:?}", out.render_diagnostics());
4092
4093        for expected in [
4094            "New Capacitor.cap bus1=lv.1.3.0 ",
4095            "New Generator.gen bus1=lv.1.3.0 ",
4096            "New Generator.fixed_ibr bus1=lv.1.3.0 ",
4097            "New PVSystem.pv_ibr bus1=lv.1.3.0 ",
4098            "New Line.sw1 bus1=lv.1.3.0 bus2=_pio_switch_sw1.1.3.0 phases=3 switch=y",
4099            "New Line._pio_switch_sw1 bus1=_pio_switch_sw1.1.3.0 bus2=lv.1.3.0 phases=3",
4100            "New Line.l1 bus1=lv.1.0.3 bus2=lv.1.0.3 phases=3 linecode=lc ",
4101        ] {
4102            assert!(
4103                out.text.contains(expected),
4104                "missing {expected:?}: {}",
4105                out.text
4106            );
4107        }
4108    }
4109
4110    #[test]
4111    fn a_line_with_its_linecode_permutes_the_matrices_in_step() {
4112        let mut net = terminal_order_network(&["p1", "n", "p2"]);
4113        net.line_codes_mut().push(DistLineCode::new(
4114            "lc",
4115            vec![
4116                vec![1.0, 0.2, 0.3],
4117                vec![0.2, 2.0, 0.4],
4118                vec![0.3, 0.4, 3.0],
4119            ],
4120            vec![
4121                vec![10.0, 0.0, 0.0],
4122                vec![0.0, 20.0, 0.0],
4123                vec![0.0, 0.0, 30.0],
4124            ],
4125        ));
4126        let out = emit_dss_text(&net);
4127
4128        assert_eq!(
4129            terminal_order_diagnostics(&out).len(),
4130            0,
4131            "{:?}",
4132            out.render_diagnostics()
4133        );
4134        // The line references the permuted copy and both node lists move the
4135        // return last.
4136        assert!(
4137            out.text
4138                .contains("New Line.l1 bus1=lv.1.3.0 bus2=lv.1.3.0 phases=3 linecode=lc_ret1 "),
4139            "{}",
4140            out.text
4141        );
4142        // Conductor order [p1, p2, n]: the permuted rmatrix rows and columns
4143        // move together, so row 2 is the old conductor 3 and the old mutual
4144        // 0.4 sits at (3, 2).
4145        assert!(
4146            out.text
4147                .contains("New Linecode.lc_ret1 nphases=3 units=m rmatrix=(1 | 0.3 3 | 0.2 0.4 2)"),
4148            "{}",
4149            out.text
4150        );
4151        // The original stays for any line that keeps its order.
4152        assert!(
4153            out.text
4154                .contains("New Linecode.lc nphases=3 units=m rmatrix=(1 | 0.2 2 | 0.3 0.4 3)"),
4155            "{}",
4156            out.text
4157        );
4158    }
4159
4160    #[test]
4161    fn disagreeing_endpoint_returns_keep_the_order_error() {
4162        let mut net = terminal_order_network(&["p1", "n", "p2"]);
4163        // The same wire cannot hold the return at conductor 2 on one end and
4164        // conductor 1 on the other; no permutation is sound, so the order
4165        // errors stand for the line and the switch.
4166        net.lines_mut()[0].terminal_map_to = strings(&["n", "p1", "p2"]);
4167        net.switches_mut()[0].terminal_map_to = strings(&["n", "p1", "p2"]);
4168        let out = emit_dss_text(&net);
4169        let diagnostics = terminal_order_diagnostics(&out);
4170        assert!(
4171            diagnostics
4172                .iter()
4173                .any(|d| d.details()["class"] == "switch" && d.details()["endpoint"] == "bus2"),
4174            "{:?}",
4175            out.render_diagnostics()
4176        );
4177        assert!(
4178            out.text.contains("New Line.sw1 bus1=lv.1.0.3 "),
4179            "{}",
4180            out.text
4181        );
4182    }
4183
4184    #[test]
4185    fn grounded_return_last_needs_no_terminal_order_diagnostic() {
4186        let out = emit_dss_text(&terminal_order_network(&["p1", "p2", "n"]));
4187        assert!(
4188            terminal_order_diagnostics(&out).is_empty(),
4189            "{:?}",
4190            out.diagnostics
4191        );
4192        assert!(out.text.contains("bus1=lv.1.2.0"), "{}", out.text);
4193    }
4194
4195    #[test]
4196    fn an_unbalanced_center_tap_load_keeps_each_leg_with_its_own_power() {
4197        // The balanced case cannot catch a swap. With the return conductor mid
4198        // map, taking the last terminal as the return pairs leg 1 with the
4199        // neutral and puts the second leg across both hots.
4200        let (b, vs, lv) = center_tap_service(11000.0);
4201        let l = DistLoad::new(
4202            "ld",
4203            "lv",
4204            strings(&["p1", "n", "p2"]),
4205            Configuration::Wye,
4206            vec![1000.0, 2000.0],
4207            vec![100.0, 200.0],
4208        );
4209        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
4210            base_frequency: 60.0,
4211            buses: vec![b, lv],
4212            sources: vec![vs],
4213            loads: vec![l],
4214            ..MulticonductorNetworkTables::default()
4215        });
4216        let out = emit_dss_text(&net);
4217        let loads: Vec<&str> = out
4218            .text
4219            .lines()
4220            .filter(|l| l.contains("New Load."))
4221            .collect();
4222        assert_eq!(loads.len(), 2, "{}", out.text);
4223        for (name, node, kw, kvar) in [
4224            ("ld_p1", "lv.1.0", "1", "0.1"),
4225            ("ld_p2", "lv.3.0", "2", "0.2"),
4226        ] {
4227            let line = loads
4228                .iter()
4229                .find(|l| l.contains(&format!("New Load.{name} ")))
4230                .unwrap_or_else(|| panic!("no {name}: {}", out.text));
4231            assert!(line.contains(&format!("bus1={node} ")), "{line}");
4232            assert!(line.contains(&format!("kw={kw} ")), "{line}");
4233            assert!(line.contains(&format!("kvar={kvar}")), "{line}");
4234        }
4235        // No part lands on the neutral terminal or spans the two hot legs.
4236        assert!(!out.text.contains("New Load.ld_n "), "{}", out.text);
4237    }
4238
4239    #[test]
4240    fn a_map_longer_than_the_record_says_what_dss_drops() {
4241        // The mirror of the short map warning. One power value over three
4242        // conductors cannot split, so the arity is all the writer can report.
4243        let (b, vs, lv) = center_tap_service(11000.0);
4244        let mut l = DistLoad::new(
4245            "ld",
4246            "lv",
4247            strings(&["p1", "n", "p2"]),
4248            Configuration::Wye,
4249            vec![2608.0],
4250            vec![1956.0],
4251        );
4252        l.extras.insert("phases".into(), 1.into());
4253        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
4254            base_frequency: 60.0,
4255            buses: vec![b, lv],
4256            sources: vec![vs],
4257            loads: vec![l],
4258            ..MulticonductorNetworkTables::default()
4259        });
4260        let out = emit_dss_text(&net);
4261        assert_eq!(
4262            out.text.lines().filter(|l| l.contains("New Load.")).count(),
4263            1,
4264            "{}",
4265            out.text
4266        );
4267        assert!(
4268            out.render_diagnostics()
4269                .iter()
4270                .any(|w| w.contains("addresses 2") && w.contains("loses them")),
4271            "{:?}",
4272            out.render_diagnostics()
4273        );
4274    }
4275
4276    #[test]
4277    fn a_star_with_no_secondary_leakage_goes_out_solvable() {
4278        // PowerIO.jl#79 bug 3. BMOPF puts the whole leakage on the primary
4279        // arm, so the star back solves to xlt=0, which dss converges on with
4280        // the secondary legs collapsed to about half voltage.
4281        let (b, vs, lv) = center_tap_service(11000.0);
4282        let winding = |bus: &str, map: &[&str], v: f64| DistWinding {
4283            bus: bus.into(),
4284            terminal_map: strings(map),
4285            conn: DistWindingConn::Wye,
4286            v_ref: v,
4287            s_rating: 25e3,
4288            r_pct: 0.5,
4289            tap: 1.0,
4290            r_neutral: None,
4291            x_neutral: None,
4292        };
4293        let t = DistTransformer {
4294            name: "tx".into(),
4295            phases: 1,
4296            windings: vec![
4297                winding("sb", &["1", "4"], 11000.0),
4298                winding("lv", &["p1", "n"], 240.0),
4299                winding("lv", &["n", "p2"], 240.0),
4300            ],
4301            xsc_pct: vec![2.5, 2.5, 0.0],
4302            extras: Extras::new(),
4303        };
4304        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
4305            base_frequency: 60.0,
4306            buses: vec![b, lv],
4307            sources: vec![vs],
4308            transformers: vec![t],
4309            ..MulticonductorNetworkTables::default()
4310        });
4311        let out = emit_dss_text(&net);
4312        let line = out
4313            .text
4314            .lines()
4315            .find(|l| l.contains("New Transformer.tx"))
4316            .unwrap_or_else(|| panic!("no transformer: {}", out.text));
4317        assert!(line.contains("xhl=2.5 xht=2.5 xlt=1.666"), "{line}");
4318        // The reversed third winding is the dss center tap spelling, not a
4319        // node order fault: the two halves are series additive.
4320        assert!(line.contains("buses=(sb.1.0, lv.1.0, lv.0.3)"), "{line}");
4321        assert!(
4322            out.render_diagnostics()
4323                .iter()
4324                .any(|w| w.contains("collapsed secondary")),
4325            "{:?}",
4326            out.render_diagnostics()
4327        );
4328    }
4329
4330    #[test]
4331    fn an_unbalanced_delta_load_preserves_each_ordered_branch() {
4332        let (b, vs) = three_phase_source(2400.0);
4333        let l = DistLoad::new(
4334            "d1",
4335            "sb",
4336            strings(&["1", "2", "3"]),
4337            Configuration::Delta,
4338            vec![1e3, 2e3, 3e3],
4339            vec![0.0, 0.0, 0.0],
4340        );
4341        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
4342            base_frequency: 60.0,
4343            buses: vec![b],
4344            sources: vec![vs],
4345            loads: vec![l],
4346            ..MulticonductorNetworkTables::default()
4347        });
4348        let out = emit_dss_text(&net);
4349        let records: Vec<_> = out
4350            .text
4351            .lines()
4352            .filter(|l| l.contains("New Load."))
4353            .collect();
4354        assert_eq!(records.len(), 3, "{}", out.text);
4355        for (record, pair, kw) in [
4356            (records[0], "1.2", 1),
4357            (records[1], "2.3", 2),
4358            (records[2], "3.1", 3),
4359        ] {
4360            assert!(
4361                record.contains(&format!("bus1=sb.{pair} phases=1 conn=delta")),
4362                "{record}"
4363            );
4364            assert!(record.contains(&format!("kw={kw} ")), "{record}");
4365        }
4366        assert!(
4367            !out.render_diagnostics()
4368                .iter()
4369                .any(|w| w.contains("collapsed"))
4370        );
4371    }
4372
4373    #[test]
4374    fn two_phase_capacitor_kvar_uses_line_to_line_kv() {
4375        // The reader treats wye capacitor kv as line to line for 2 and 3
4376        // phase; the kvar fallback must invert with the same convention.
4377        let (b, vs) = three_phase_source(2400.0);
4378        let b_phase = 1e-3;
4379        let sh = DistShunt {
4380            name: "c1".into(),
4381            bus: "sb".into(),
4382            terminal_map: strings(&["1", "2"]),
4383            g: vec![vec![0.0; 2]; 2],
4384            b: vec![vec![b_phase, 0.0], vec![0.0, b_phase]],
4385            extras: Extras::new(),
4386        };
4387        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
4388            base_frequency: 60.0,
4389            buses: vec![b],
4390            sources: vec![vs],
4391            shunts: vec![sh],
4392            ..MulticonductorNetworkTables::default()
4393        });
4394        let out = emit_dss_text(&net);
4395        let kv = 2400.0 * 3f64.sqrt() / 1e3;
4396        let v_phase = crate::electrical::calc_wye_phase_voltage(kv * 1e3);
4397        let expected = b_phase * v_phase * v_phase * 2.0 / 1e3;
4398        let line = out
4399            .text
4400            .lines()
4401            .find(|l| l.contains("Capacitor.c1"))
4402            .unwrap();
4403        assert!(line.contains(&format!("kvar={}", num(expected))), "{line}");
4404    }
4405
4406    #[test]
4407    fn inductive_shunt_regenerates_as_a_reactor() {
4408        // A negative diagonal susceptance is the grounding-reactor sign; it
4409        // must emit `New Reactor`, not a capacitor, with the positive kvar
4410        // rating recovered from |b| v^2.
4411        let (b, vs) = three_phase_source(2400.0);
4412        let b_phase = -1e-3;
4413        let sh = DistShunt {
4414            name: "rx".into(),
4415            bus: "sb".into(),
4416            terminal_map: strings(&["1", "2", "3"]),
4417            g: vec![vec![0.0; 3]; 3],
4418            b: vec![
4419                vec![b_phase, 0.0, 0.0],
4420                vec![0.0, b_phase, 0.0],
4421                vec![0.0, 0.0, b_phase],
4422            ],
4423            extras: Extras::new(),
4424        };
4425        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
4426            base_frequency: 60.0,
4427            buses: vec![b],
4428            sources: vec![vs],
4429            shunts: vec![sh],
4430            ..MulticonductorNetworkTables::default()
4431        });
4432        let out = emit_dss_text(&net);
4433        let line = out
4434            .text
4435            .lines()
4436            .find(|l| l.contains("Reactor.rx"))
4437            .unwrap_or_else(|| panic!("no reactor emitted in:\n{}", out.text));
4438        assert!(!out.text.contains("Capacitor.rx"), "{}", out.text);
4439        let kv = 2400.0 * 3f64.sqrt() / 1e3;
4440        let v_phase = crate::electrical::calc_wye_phase_voltage(kv * 1e3);
4441        let expected = b_phase.abs() * v_phase * v_phase * 3.0 / 1e3;
4442        assert!(line.contains(&format!("kvar={}", num(expected))), "{line}");
4443    }
4444
4445    #[test]
4446    fn conductive_shunt_regenerates_as_grounding_reactor() {
4447        let (_, vs) = three_phase_source(2400.0);
4448        let b = bus("sb", &["1", "2", "3", "4"], &[]);
4449        let sh = DistShunt {
4450            name: "gnd".into(),
4451            bus: "sb".into(),
4452            terminal_map: strings(&["4"]),
4453            g: vec![vec![1.0 / 0.3]],
4454            b: vec![vec![0.0]],
4455            extras: Extras::new(),
4456        };
4457        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
4458            base_frequency: 60.0,
4459            buses: vec![b],
4460            sources: vec![vs],
4461            shunts: vec![sh],
4462            ..MulticonductorNetworkTables::default()
4463        });
4464        let out = emit_dss_text(&net);
4465        let line = out
4466            .text
4467            .lines()
4468            .find(|l| l.contains("Reactor.gnd"))
4469            .unwrap_or_else(|| panic!("no reactor emitted in:\n{}", out.text));
4470        assert!(line.contains("bus1=sb.4"), "{line}");
4471        assert!(line.contains("bus2=sb.0"), "{line}");
4472        assert!(line.contains("phases=1"), "{line}");
4473        assert!(line.contains("r=0.3"), "{line}");
4474        assert!(line.contains("x=0"), "{line}");
4475        assert!(
4476            !line.contains("x=-0"),
4477            "negative zero must canonicalize: {line}"
4478        );
4479    }
4480
4481    #[test]
4482    fn delta_shunt_regenerates_conn_delta() {
4483        let (b, vs) = three_phase_source(2400.0);
4484        let b_branch = 2e-4;
4485        let bmat = vec![
4486            vec![2.0 * b_branch, -b_branch, -b_branch],
4487            vec![-b_branch, 2.0 * b_branch, -b_branch],
4488            vec![-b_branch, -b_branch, 2.0 * b_branch],
4489        ];
4490        let mut extras = Extras::new();
4491        extras.insert("conn".into(), serde_json::json!("delta"));
4492        extras.insert("phases".into(), serde_json::json!("3"));
4493        let sh = DistShunt {
4494            name: "capd".into(),
4495            bus: "sb".into(),
4496            terminal_map: strings(&["1", "2", "3"]),
4497            g: vec![vec![0.0; 3]; 3],
4498            b: bmat,
4499            extras,
4500        };
4501        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
4502            base_frequency: 60.0,
4503            buses: vec![b],
4504            sources: vec![vs],
4505            shunts: vec![sh],
4506            ..MulticonductorNetworkTables::default()
4507        });
4508        let out = emit_dss_text(&net);
4509        let line = out
4510            .text
4511            .lines()
4512            .find(|l| l.contains("Capacitor.capd"))
4513            .unwrap_or_else(|| panic!("no capacitor emitted in:\n{}", out.text));
4514        assert!(line.contains("phases=3 conn=delta"), "{line}");
4515        assert!(
4516            !out.render_diagnostics()
4517                .iter()
4518                .any(|w| w.contains("off diagonal")),
4519            "{:?}",
4520            out.render_diagnostics()
4521        );
4522    }
4523
4524    #[test]
4525    fn non_scalar_delta_matrix_is_not_inferred_silently() {
4526        let (b, vs) = three_phase_source(2400.0);
4527        let bmat = vec![
4528            vec![0.003, -0.001, -0.002],
4529            vec![-0.001, 0.003, -0.002],
4530            vec![-0.002, -0.002, 0.004],
4531        ];
4532        let sh = DistShunt {
4533            name: "capx".into(),
4534            bus: "sb".into(),
4535            terminal_map: strings(&["1", "2", "3"]),
4536            g: vec![vec![0.0; 3]; 3],
4537            b: bmat,
4538            extras: Extras::new(),
4539        };
4540        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
4541            base_frequency: 60.0,
4542            buses: vec![b],
4543            sources: vec![vs],
4544            shunts: vec![sh],
4545            ..MulticonductorNetworkTables::default()
4546        });
4547        let out = emit_dss_text(&net);
4548        assert!(out.text.contains("_pio_shunt_0_pair_"));
4549        assert!(
4550            out.render_diagnostics()
4551                .iter()
4552                .any(|w| w.contains("full admittance"))
4553        );
4554        assert!(
4555            !out.render_diagnostics()
4556                .iter()
4557                .any(|w| w.contains("only the diagonal"))
4558        );
4559    }
4560
4561    #[test]
4562    fn stashed_delta_matrix_preserves_unequal_branches() {
4563        let (b, vs) = three_phase_source(2400.0);
4564        let bmat = vec![
4565            vec![0.003, -0.001, -0.002],
4566            vec![-0.001, 0.003, -0.002],
4567            vec![-0.002, -0.002, 0.004],
4568        ];
4569        let mut extras = Extras::new();
4570        extras.insert("conn".into(), serde_json::json!("delta"));
4571        extras.insert("phases".into(), serde_json::json!("3"));
4572        let sh = DistShunt {
4573            name: "capx".into(),
4574            bus: "sb".into(),
4575            terminal_map: strings(&["1", "2", "3"]),
4576            g: vec![vec![0.0; 3]; 3],
4577            b: bmat,
4578            extras,
4579        };
4580        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
4581            base_frequency: 60.0,
4582            buses: vec![b],
4583            sources: vec![vs],
4584            shunts: vec![sh],
4585            ..MulticonductorNetworkTables::default()
4586        });
4587        let out = emit_dss_text(&net);
4588        assert!(out.text.contains("_pio_shunt_0_pair_"));
4589        assert!(
4590            out.render_diagnostics()
4591                .iter()
4592                .any(|w| w.contains("full admittance"))
4593        );
4594        assert!(
4595            !out.render_diagnostics()
4596                .iter()
4597                .any(|w| w.contains("only the average"))
4598        );
4599    }
4600
4601    #[test]
4602    fn option_values_choose_a_wrapper_the_lexer_undoes() {
4603        let src = "Clear\n\
4604                   New Circuit.c1 basekv=12.47 pu=1 angle=0 phases=3 bus1=sb\n\
4605                   Set foo=[a!b]\n\
4606                   Set bar=[(abc]\n\
4607                   Set baz=(x ] y)\n\
4608                   Set qux=[a ) b]\n\
4609                   Solve\n";
4610        let net = parse_dss_str(src);
4611        let first = emit_dss_text(&net);
4612        for line in [
4613            "Set foo=(a!b)",
4614            "Set bar=((abc)",
4615            "Set baz=(x ] y)",
4616            "Set qux=[a ) b]",
4617        ] {
4618            assert!(
4619                first.text.contains(line),
4620                "{line} missing in {}",
4621                first.text
4622            );
4623        }
4624        assert!(
4625            !first
4626                .render_diagnostics()
4627                .iter()
4628                .any(|w| w.contains("emitted as written")),
4629            "{:?}",
4630            first.render_diagnostics()
4631        );
4632        // The reader strips the wrapper back off...
4633        let reparsed = parse_dss_str(&first.text);
4634        let opt = |k: &str| {
4635            reparsed
4636                .options()
4637                .iter()
4638                .find(|(name, _)| name == k)
4639                .map(|(_, v)| v.as_str())
4640        };
4641        assert_eq!(opt("foo"), Some("a!b"));
4642        assert_eq!(opt("bar"), Some("(abc"));
4643        assert_eq!(opt("baz"), Some("x ] y"));
4644        assert_eq!(opt("qux"), Some("a ) b"));
4645        // ...and the second write picks the same wrapper from the bare value.
4646        let second = emit_dss_text(&reparsed);
4647        for prefix in ["Set foo=", "Set bar=", "Set baz=", "Set qux="] {
4648            assert_eq!(
4649                first.text.lines().find(|line| line.starts_with(prefix)),
4650                second.text.lines().find(|line| line.starts_with(prefix))
4651            );
4652        }
4653    }
4654
4655    #[test]
4656    fn extras_tail_values_wrap_like_options() {
4657        // Spectrum remains an emitted extra for generators. Static loads
4658        // deliberately omit it because its harmonic definition is not emitted.
4659        let mut net = parse_dss_str(
4660            "new circuit.c basekv=4.16\nnew generator.g phases=3 bus1=sourcebus kv=4.16 kw=1 kvar=0\n",
4661        );
4662        net.generators_mut()[0]
4663            .extras
4664            .insert("spectrum".into(), serde_json::json!("a ) b"));
4665        let (first, second) = roundtrip(&net);
4666        // A paren wrapper would close at the `)` and land `b)` on the next
4667        // positional property; brackets survive.
4668        assert!(first.contains("spectrum=[a ) b]"), "{first}");
4669        assert_eq!(
4670            first
4671                .lines()
4672                .find(|line| line.starts_with("New Generator.g ")),
4673            second
4674                .lines()
4675                .find(|line| line.starts_with("New Generator.g "))
4676                .map(|line| line.replace(" vlowpu=0.5", ""))
4677                .as_deref()
4678        );
4679        let back = parse_dss_str(&first);
4680        assert_eq!(
4681            back.generators()[0]
4682                .extras
4683                .get("spectrum")
4684                .and_then(serde_json::Value::as_str),
4685            Some("a ) b")
4686        );
4687    }
4688
4689    #[test]
4690    fn unrepresentable_values_emit_as_written_and_warn() {
4691        // Every quote closer appears, and the spaces split a bare scan: no
4692        // emitted form reparses to this value.
4693        let bad = "a )]}\"' b";
4694        let mut net = parse_dss_str(
4695            "new circuit.c basekv=4.16\nnew generator.g phases=3 bus1=sourcebus kv=4.16 kw=1 kvar=0\n",
4696        );
4697        net.generators_mut()[0]
4698            .extras
4699            .insert("spectrum".into(), serde_json::json!(bad));
4700        net.options_mut().push(("foo".into(), bad.into()));
4701        let out = emit_dss_text(&net);
4702        assert!(out.text.contains(&format!("Set foo={bad}")), "{}", out.text);
4703        assert!(
4704            out.text.contains(&format!("spectrum={bad}")),
4705            "{}",
4706            out.text
4707        );
4708        let warned = |needle: &str| {
4709            out.render_diagnostics()
4710                .iter()
4711                .any(|w| w.contains(needle) && w.contains("emitted as written"))
4712        };
4713        assert!(warned("option `foo`"), "{:?}", out.render_diagnostics());
4714        assert!(warned("`spectrum`"), "{:?}", out.render_diagnostics());
4715    }
4716
4717    #[test]
4718    fn canonical_snapshot_omits_loadshape_references_with_diagnostics() {
4719        let dss = "clear\nnew circuit.c basekv=12.47 bus1=sb\n\
4720                   new load.ld bus1=sb.1 phases=1 kv=7.2 kw=10 daily=() duty=sh yearly=annual spectrum=custom\nsolve\n";
4721        let net = parse_dss_str(dss);
4722        assert_eq!(
4723            net.loads()[0].extras.get("duty").and_then(|v| v.as_str()),
4724            Some("sh")
4725        );
4726        let emitted = emit_dss_text(&net);
4727        for key in ["daily", "duty", "yearly"] {
4728            assert!(!emitted.text.contains(&format!(" {key}=")));
4729            assert!(
4730                emitted
4731                    .render_diagnostics()
4732                    .iter()
4733                    .any(|d| d.contains(&format!("`{key}` loadshape reference omitted")))
4734            );
4735        }
4736        assert!(!emitted.text.contains(" spectrum="));
4737        assert!(
4738            emitted
4739                .render_diagnostics()
4740                .iter()
4741                .any(|d| d.contains("harmonic spectrum reference omitted"))
4742        );
4743        let again = parse_dss_str(&emitted.text);
4744        assert_eq!(again.loads()[0].p_nom, net.loads()[0].p_nom);
4745        assert_eq!(again.loads()[0].q_nom, net.loads()[0].q_nom);
4746        assert_eq!(again.loads()[0].voltage_model, net.loads()[0].voltage_model);
4747    }
4748
4749    #[test]
4750    fn sub_unique_option_prefixes_re_emit_instead_of_vanishing() {
4751        // "ca" is CapkVAR and "default" is DefaultDaily in the engine's
4752        // option table; neither may be skipped as a derived key, and
4753        // `Set default=2.5` must not change the base frequency.
4754        let dss = "clear\nnew circuit.c basekv=12.47 bus1=sb\n\
4755                   Set ca=600\nSet default=2.5\nsolve\n";
4756        let net = parse_dss_str(dss);
4757        assert!((net.base_frequency() - 60.0).abs() < 1e-12);
4758        let out = emit_dss_text(&net).text;
4759        assert!(out.contains("Set ca=600"), "{out}");
4760        assert!(out.contains("Set default=2.5"), "{out}");
4761    }
4762
4763    #[test]
4764    fn abbreviated_derived_options_skip_and_set_the_frequency() {
4765        // The engine resolves Set names by unique prefix, so volt= IS
4766        // Voltagebases and defaultb= IS DefaultBaseFrequency.
4767        let src = "Clear\n\
4768                   New Circuit.c1 basekv=12.47 pu=1 angle=0 phases=3 bus1=sb\n\
4769                   Set volt=[115, 132]\n\
4770                   Set defaultb=50\n\
4771                   Solve\n";
4772        let net = parse_dss_str(src);
4773        assert!((net.base_frequency() - 50.0).abs() < 1e-12);
4774        let out = emit_dss_text(&net);
4775        assert!(
4776            out.text.contains("Set DefaultBaseFrequency=50"),
4777            "{}",
4778            out.text
4779        );
4780        assert_eq!(
4781            out.text
4782                .to_lowercase()
4783                .matches("defaultbasefrequency")
4784                .count(),
4785            1,
4786            "{}",
4787            out.text
4788        );
4789        assert_eq!(
4790            out.text.matches("Set VoltageBases").count(),
4791            0,
4792            "{}",
4793            out.text
4794        );
4795        assert!(!out.text.contains("Set volt="), "{}", out.text);
4796        assert!(!out.text.contains("Set defaultb="), "{}", out.text);
4797        let second = emit_dss_text(&parse_dss_str(&out.text));
4798        assert_eq!(
4799            parse_dss_str(&second.text).base_frequency().to_bits(),
4800            50.0_f64.to_bits()
4801        );
4802        // DefaultBaseFrequency changed after construction: native source
4803        // frequency remains 60 Hz and therefore supplies zero EMF at 50 Hz.
4804        assert!(
4805            net.sources()
4806                .iter()
4807                .all(|source| source.v_magnitude.iter().all(|v| v.abs() < 1e-12))
4808        );
4809    }
4810
4811    #[test]
4812    fn non_numeric_source_extras_do_not_override_typed_constraints() {
4813        let (b, mut vs) = three_phase_source(2400.0);
4814        vs.extras
4815            .insert("basekv".into(), serde_json::json!("@base"));
4816        vs.extras.insert("pu".into(), serde_json::json!("unity"));
4817        vs.extras.insert("angle".into(), serde_json::json!([0.0]));
4818        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
4819            base_frequency: 60.0,
4820            buses: vec![b],
4821            sources: vec![vs],
4822            ..MulticonductorNetworkTables::default()
4823        });
4824        let out = emit_dss_text(&net);
4825        for key in ["basekv", "pu", "angle"] {
4826            assert!(
4827                out.render_diagnostics()
4828                    .iter()
4829                    .any(|w| w.contains(&format!("extra {key}"))
4830                        && w.contains("not part of the typed ideal voltage constraint")),
4831                "{key}: {:?}",
4832                out.render_diagnostics()
4833            );
4834        }
4835        // The derived values substitute.
4836        let line = out.text.lines().find(|l| l.contains("Circuit.")).unwrap();
4837        assert!(line.contains("pu=1 angle=-360"), "{line}");
4838    }
4839
4840    fn emitted_source_ports(text: &str) -> BTreeMap<String, num_complex::Complex64> {
4841        let raw = crate::dss::__parse_raw_with(text, "sources.dss", &mut |_: &std::path::Path| {
4842            Err(std::io::Error::other("no includes"))
4843        });
4844        let mut ports = BTreeMap::new();
4845        for source in raw.of_class("vsource") {
4846            let internal = source.get("bus1").unwrap().text.to_ascii_lowercase();
4847            let line = raw
4848                .of_class("line")
4849                .find(|line| {
4850                    line.get("bus1")
4851                        .unwrap()
4852                        .text
4853                        .eq_ignore_ascii_case(&internal)
4854                })
4855                .unwrap();
4856            let resolved = crate::dss::source::resolve(&raw, source, 60.0).unwrap();
4857            assert_eq!(resolved.emf.len(), 1);
4858            assert!((resolved.impedance[0][0] - 1.0).norm() < 1e-12);
4859            assert_eq!(line.get("r1").unwrap().text, "-1");
4860            assert_eq!(line.get("x1").unwrap().text, "0");
4861            let port = line.get("bus2").unwrap().text.to_ascii_lowercase();
4862            assert!(ports.insert(port, resolved.emf[0]).is_none());
4863        }
4864        ports
4865    }
4866
4867    #[test]
4868    fn de_energized_source_phase_keeps_its_conductor() {
4869        let (b, mut vs) = three_phase_source(2400.0);
4870        vs.v_magnitude[2] = 0.0; // de-energized, but still a phase conductor
4871        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
4872            name: Some("t".into()),
4873            base_frequency: 60.0,
4874            buses: vec![b],
4875            sources: vec![vs],
4876            ..MulticonductorNetworkTables::default()
4877        });
4878        let out = emit_dss_text(&net);
4879        let ports = emitted_source_ports(&out.text);
4880        assert_eq!(ports.len(), 3);
4881        assert!((ports["sb.1"].re - 2400.0).abs() < 1e-10);
4882        assert!((ports["sb.2"].norm() - 2400.0).abs() < 1e-10);
4883        assert!(ports["sb.3"].norm() < 1e-12);
4884        let reparsed = parse_dss_str(&out.text);
4885        let bus = reparsed.buses().iter().find(|b| b.id == "sb").unwrap();
4886        assert!(bus.terminals.contains(&"3".into()));
4887        assert!(!bus.grounded.contains(&"3".into()));
4888    }
4889
4890    #[test]
4891    fn multiple_sources_preserve_each_bus_and_phase_constraint() {
4892        let third = 2.0 * std::f64::consts::FRAC_PI_3;
4893        let source = VoltageSource {
4894            reference_terminal: None,
4895            name: "source".into(),
4896            bus: "Bx".into(),
4897            terminal_map: strings(&["1", "2", "3", "4"]),
4898            v_magnitude: vec![20_000.0, 20_000.0, 20_000.0, 0.0],
4899            v_angle: vec![0.0, -third, third, 0.0],
4900            energy_cost_rate: None,
4901            extras: Extras::new(),
4902        };
4903        let wind = VoltageSource {
4904            reference_terminal: None,
4905            name: "WindGen1".into(),
4906            bus: "Bg".into(),
4907            terminal_map: strings(&["1", "2", "3", "4"]),
4908            v_magnitude: vec![400.0, 400.0, 400.0, 0.0],
4909            v_angle: vec![
4910                -std::f64::consts::FRAC_PI_3,
4911                std::f64::consts::PI,
4912                third / 2.0,
4913                0.0,
4914            ],
4915            energy_cost_rate: None,
4916            extras: Extras::new(),
4917        };
4918        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
4919            name: Some("dg".into()),
4920            base_frequency: 60.0,
4921            buses: vec![
4922                bus("Bg", &["1", "2", "3", "4"], &["4"]),
4923                bus("Bx", &["1", "2", "3", "4"], &["4"]),
4924            ],
4925            sources: vec![wind, source],
4926            ..MulticonductorNetworkTables::default()
4927        });
4928
4929        let out = emit_dss_text(&net);
4930        let ports = emitted_source_ports(&out.text);
4931        assert_eq!(ports.len(), 6);
4932        for source in net.sources() {
4933            for i in 0..3 {
4934                let expected =
4935                    num_complex::Complex64::from_polar(source.v_magnitude[i], source.v_angle[i]);
4936                let port =
4937                    format!("{}.{}", source.bus, source.terminal_map[i]).to_ascii_lowercase();
4938                assert!((ports[&port] - expected).norm() < 1e-9, "{port}");
4939            }
4940            assert!(
4941                out.render_diagnostics()
4942                    .iter()
4943                    .any(|d| d.contains(&format!("source {}:", source.name))
4944                        && d.contains("3 voltage constraint(s)"))
4945            );
4946        }
4947    }
4948
4949    #[test]
4950    fn source_phases_extra_cannot_override_typed_constraints() {
4951        let (b, mut vs) = three_phase_source(2400.0);
4952        vs.extras.insert("phases".into(), serde_json::json!("3"));
4953        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
4954            base_frequency: 60.0,
4955            buses: vec![b],
4956            sources: vec![vs],
4957            ..MulticonductorNetworkTables::default()
4958        });
4959        let out = emit_dss_text(&net);
4960        let sources: Vec<_> = out
4961            .text
4962            .lines()
4963            .filter(|l| l.starts_with("New Circuit.") || l.starts_with("New Vsource."))
4964            .collect();
4965        assert_eq!(sources.len(), 3);
4966        for line in sources {
4967            assert!(line.contains("phases=1"), "{line}");
4968            assert_eq!(line.matches("phases=").count(), 1, "{line}");
4969        }
4970        assert!(
4971            out.render_diagnostics()
4972                .iter()
4973                .any(|d| d.contains("extra phases")
4974                    && d.contains("not part of the typed ideal voltage constraint"))
4975        );
4976        let ports = emitted_source_ports(&out.text);
4977        assert_eq!(ports.len(), 3);
4978        assert!(ports.values().all(|v| (v.norm() - 2400.0).abs() < 1e-10));
4979    }
4980
4981    #[test]
4982    fn wye_load_materialized_neutral_is_reported_once() {
4983        // A wye load without an explicit return acquires a grounded neutral.
4984        // Report that topology change once; ideal source constraints keep
4985        // their own terminal maps.
4986        let third = 2.0 * std::f64::consts::FRAC_PI_3;
4987        let vs = VoltageSource {
4988            reference_terminal: None,
4989            name: "source".into(),
4990            bus: "sb".into(),
4991            terminal_map: strings(&["1", "2", "3"]),
4992            v_magnitude: vec![2400.0; 3],
4993            v_angle: vec![0.0, -third, third],
4994            energy_cost_rate: None,
4995            extras: Extras::new(),
4996        };
4997        let load = load_on("sb", &["1"], Configuration::Wye);
4998        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
4999            name: Some("t".into()),
5000            base_frequency: 60.0,
5001            buses: vec![bus("sb", &["1", "2", "3"], &[])],
5002            sources: vec![vs],
5003            loads: vec![load],
5004            ..MulticonductorNetworkTables::default()
5005        });
5006        let first = emit_dss_text(&net);
5007        let hits = |warnings: &[String], name: &str| {
5008            warnings
5009                .iter()
5010                .any(|w| w.contains(name) && w.contains("materializes a grounded neutral"))
5011        };
5012        assert!(
5013            hits(&first.render_diagnostics(), "load ld"),
5014            "{:?}",
5015            first.render_diagnostics()
5016        );
5017        let restored = parse_dss_str(&first.text);
5018        assert_eq!(restored.loads()[0].terminal_map, ["1", "4"]);
5019        let second = emit_dss_text(&restored);
5020        assert!(
5021            !hits(&second.render_diagnostics(), "vsource"),
5022            "{:?}",
5023            second.render_diagnostics()
5024        );
5025        assert!(
5026            !hits(&second.render_diagnostics(), "load"),
5027            "{:?}",
5028            second.render_diagnostics()
5029        );
5030        let restored_again = parse_dss_str(&second.text);
5031        assert_eq!(restored.loads()[0], restored_again.loads()[0]);
5032    }
5033
5034    #[test]
5035    fn generator_phases_and_conn_match_the_load_rules() {
5036        let (b, vs) = three_phase_source(2400.0);
5037        let g = DistGenerator {
5038            name: "g1".into(),
5039            bus: "sb".into(),
5040            terminal_map: strings(&["1", "2", "3"]),
5041            configuration: Configuration::Delta,
5042            p_nom: vec![1e3; 3],
5043            q_nom: vec![0.0; 3],
5044            p_min: None,
5045            p_max: None,
5046            q_min: None,
5047            q_max: None,
5048            cost: None,
5049            s_max: None,
5050            i_max: None,
5051            extras: Extras::from([
5052                ("kv".to_string(), serde_json::json!("4.16")),
5053                ("phases".to_string(), serde_json::json!("2")),
5054            ]),
5055        };
5056        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
5057            base_frequency: 60.0,
5058            buses: vec![b],
5059            sources: vec![vs],
5060            generators: vec![g],
5061            ..MulticonductorNetworkTables::default()
5062        });
5063        let out = emit_dss_text(&net);
5064        let line = out
5065            .text
5066            .lines()
5067            .find(|l| l.contains("Generator.g1"))
5068            .unwrap();
5069        assert!(line.contains("phases=2 conn=delta"), "{line}");
5070        assert_eq!(line.matches("phases=").count(), 1, "{line}");
5071    }
5072
5073    #[test]
5074    fn inverter_phase_count_uses_typed_ratings_instead_of_topology_or_stale_extras() {
5075        for (phases, conn, nodes) in [
5076            (1, "wye", "1.0"),
5077            (2, "wye", "1.2.0"),
5078            (2, "delta", "1.2.3"),
5079            (3, "wye", "1.2.3.0"),
5080        ] {
5081            let mut net = parse_dss_str(&format!(
5082                "new circuit.c\nnew pvsystem.pv bus1=sourcebus.{nodes} phases={phases} conn={conn} kv=12.47 kva=90 pmpp=60\n"
5083            ));
5084            net.ibrs_mut()[0]
5085                .extras
5086                .insert("phases".into(), "99".into());
5087            for fixed in [false, true] {
5088                if fixed {
5089                    let ibr = &mut net.ibrs_mut()[0];
5090                    ibr.p_min.clone_from(&ibr.p_max);
5091                    ibr.q_min = Some(vec![0.0; phases]);
5092                    ibr.q_max.clone_from(&ibr.q_min);
5093                }
5094                let output = emit_dss_text(&net);
5095                let class = if fixed { "Generator" } else { "PVSystem" };
5096                let prefix = format!("New {class}.pv ");
5097                let line = output
5098                    .text
5099                    .lines()
5100                    .find(|l| l.starts_with(&prefix))
5101                    .unwrap();
5102                assert!(line.contains(&format!("phases={phases} ")), "{line}");
5103                assert_eq!(line.matches("phases=").count(), 1);
5104            }
5105        }
5106    }
5107
5108    #[test]
5109    fn fixed_dispatch_ibr_exports_as_generator_model_one() {
5110        let (b, vs) = three_phase_source(240.0);
5111        let ibr = DistIbr {
5112            name: "pv".into(),
5113            bus: "sb".into(),
5114            terminal_map: strings(&["1", "2", "3", "4"]),
5115            topology: IbrTopology::FourLeg,
5116            prime_mover: IbrPrimeMover::Pv,
5117            s_max: vec![10_000.0; 3],
5118            i_max: None,
5119            p_avail: Some(24_000.0),
5120            p_min: Some(vec![8_000.0; 3]),
5121            p_max: Some(vec![8_000.0; 3]),
5122            q_min: Some(vec![0.0; 3]),
5123            q_max: Some(vec![0.0; 3]),
5124            control_profile: None,
5125            voltage_aggregation: None,
5126            extras: Extras::from([("kv".to_string(), serde_json::json!("0.416"))]),
5127        };
5128        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
5129            name: Some("fixed".into()),
5130            base_frequency: 60.0,
5131            buses: vec![b],
5132            sources: vec![vs],
5133            ibrs: vec![ibr],
5134            ..MulticonductorNetworkTables::default()
5135        });
5136
5137        let out = emit_dss_text(&net);
5138
5139        assert!(
5140            out.diagnostics
5141                .iter()
5142                .all(|d| d.code() == C::EMIT_DSS_SOURCE_EQUIVALENT.code),
5143            "{:?}",
5144            out.render_diagnostics()
5145        );
5146        let line = out
5147            .text
5148            .lines()
5149            .find(|l| l.starts_with("New Generator.pv"))
5150            .unwrap();
5151        assert!(line.contains("model=1 vminpu=0 vmaxpu=2"), "{line}");
5152        assert!(line.contains("kw=24"), "{line}");
5153        assert!(!out.text.contains("PVSystem.pv"), "{}", out.text);
5154    }
5155
5156    #[test]
5157    fn volt_var_ibr_exports_pvsystem_xycurve_and_invcontrol() {
5158        let (b, vs) = three_phase_source(240.0);
5159        let base_v = 416.0 / 3f64.sqrt();
5160        let ibr = DistIbr {
5161            name: "pv".into(),
5162            bus: "sb".into(),
5163            terminal_map: strings(&["1", "2", "3", "4"]),
5164            topology: IbrTopology::FourLeg,
5165            prime_mover: IbrPrimeMover::Pv,
5166            s_max: vec![10_000.0; 3],
5167            i_max: None,
5168            p_avail: Some(24_000.0),
5169            p_min: Some(vec![0.0; 3]),
5170            p_max: Some(vec![8_000.0; 3]),
5171            q_min: Some(vec![-4_000.0; 3]),
5172            q_max: Some(vec![4_000.0; 3]),
5173            control_profile: Some("cp".into()),
5174            voltage_aggregation: None,
5175            extras: Extras::from([("kv".to_string(), serde_json::json!("0.416"))]),
5176        };
5177        let profile = DistControlProfile {
5178            name: "cp".into(),
5179            power_factor: None,
5180            volt_var: Some(VoltVarControl {
5181                voltage_reference: Some(ControlVoltageReference::PgAveraged),
5182                breakpoints: [0.92, 0.98, 1.02, 1.08]
5183                    .into_iter()
5184                    .map(|v| v * base_v)
5185                    .collect(),
5186                q_limits: vec![-0.44, 0.44],
5187                q_unit: Some(ReactivePowerUnit::VaFraction),
5188                q_ref: Some(ReactivePowerReference::VarMax),
5189                p_min_for_q: Some(10.0),
5190                p_min_for_q_max: Some(50.0),
5191            }),
5192            volt_watt: None,
5193            extras: Extras::new(),
5194        };
5195        let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables {
5196            name: Some("controlled".into()),
5197            base_frequency: 60.0,
5198            buses: vec![b],
5199            sources: vec![vs],
5200            ibrs: vec![ibr],
5201            control_profiles: vec![profile],
5202            ..MulticonductorNetworkTables::default()
5203        });
5204
5205        let out = emit_dss_text(&net);
5206
5207        assert!(
5208            out.diagnostics
5209                .iter()
5210                .all(|d| d.code() == C::EMIT_DSS_SOURCE_EQUIVALENT.code),
5211            "{:?}",
5212            out.render_diagnostics()
5213        );
5214        let pv = out
5215            .text
5216            .lines()
5217            .find(|l| l.starts_with("New PVSystem.pv"))
5218            .unwrap();
5219        assert!(pv.contains("WattPriority=No VarFollowInverter=Yes"), "{pv}");
5220        assert!(pv.contains("kvarMax=12"), "{pv}");
5221        assert!(pv.contains("kvarMaxAbs=12"), "{pv}");
5222        assert!(pv.contains("%PminNoVars=10"), "{pv}");
5223        assert!(pv.contains("%PminkvarMax=50"), "{pv}");
5224
5225        let curve = out
5226            .text
5227            .lines()
5228            .find(|l| l.starts_with("New XYcurve.vv_pv"))
5229            .unwrap();
5230        assert!(curve.contains("Xarray=[0.92 0.98 1.02 1.08]"), "{curve}");
5231        assert!(curve.contains("Yarray=[0.44 0 0 -0.44]"), "{curve}");
5232
5233        let inv = out
5234            .text
5235            .lines()
5236            .find(|l| l.starts_with("New InvControl.ivc_pv"))
5237            .unwrap();
5238        assert!(inv.contains("mode=VOLTVAR"), "{inv}");
5239        assert!(inv.contains("vvc_curve1=vv_pv"), "{inv}");
5240        assert!(inv.contains("RefReactivePower=VARMAX"), "{inv}");
5241        assert!(inv.contains("monVoltageCalc=AVG"), "{inv}");
5242    }
5243}