powerio-dist 0.11.7

Multiconductor distribution network model and lossless converters for OpenDSS, PMD JSON, BMOPF JSON, and distribution CIM.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
//! [`MulticonductorNetwork`] into PMD ENGINEERING JSON.
//!
//! The output reproduces what PMD's own dss2eng emits for the same network
//! wherever the model carries the data: terminal integers, `ENABLED`
//! status, `source_id`, the materialized grounded neutral with zero
//! `rg`/`xg`, linecode `cm_ub` from the emergency rating, transformer
//! `tm_*` tap fields, the delta wye barrel roll with `polarity` -1 on the
//! lagging wye winding, and explicit voltage source Thevenin matrices
//! retained from PMD input. Typed ideal sources emit zero impedance; DSS
//! source impedance is carried by a separate typed line. The reader's `pmd_*` stashes (status, settings, files, grounding and switch
//! impedance, tap arrays, polarity, inline line impedance) win over the
//! recomputed defaults, so PMD in, PMD out does not alter fields.

use std::collections::{BTreeMap, BTreeSet};

use serde_json::{Map, Value, json};

use crate::convert::TextEmission;
use crate::diagnostics::codes as C;
use crate::geo::CoordinateSpace;
use crate::model::{
    ConductorMatrix, Configuration, DistBus, DistLine, DistLineCode, DistLoadVoltageModel,
    DistTransformer, DistWinding, DistWindingConn, Extras, MulticonductorNetwork, VoltageSource,
};

/// Emits the ENGINEERING document.
///
/// # Panics
///
/// Never in practice: the document is maps, strings, finite numbers, and
/// nulls, which always serialize.
pub(crate) fn emit_pmd_json_text(net: &MulticonductorNetwork) -> TextEmission {
    let retained = retained_sections(net);
    let mut w = Writer {
        warnings: crate::diagnostics::Diagnostics::new(),
        renamed_terminals: renamed_terminals(net),
        time_series: retained
            .get("time_series")
            .map(|items| items.keys().cloned().collect())
            .unwrap_or_default(),
        retained,
    };
    for source in net
        .sources()
        .iter()
        .filter(|source| source.energy_cost_rate.is_some())
    {
        w.warn(
            &C::EMIT_PMD_FIELD_DROPPED,
            format!(
                "voltage source {}: energy_cost_rate has no target field",
                source.name
            ),
        );
    }
    let doc = w.document(net);
    TextEmission::new(
        serde_json::to_string_pretty(&doc).expect("maps and finite numbers") + "\n",
        Vec::new(),
        w.warnings,
    )
}

/// Upper bound on the conductor counts this writer expands quadratically:
/// the switch series and shunt matrices and the voltage source Thevenin
/// matrices are all sized from a terminal map, a linear model array. The
/// readers cap the same quantity on their way in, but callers can construct a
/// `MulticonductorNetwork` without those caps, and a linear-size model could
/// otherwise demand O(n²) memory here. No physical element comes near this
/// bound.
const MAX_DIM: usize = 64;

struct Writer {
    warnings: crate::diagnostics::Diagnostics,
    /// One id per terminal name that is not numeric, for the whole network.
    renamed_terminals: BTreeMap<String, i64>,
    /// ENGINEERING sections the PMD reader kept untyped (`time_series`, say),
    /// by section and then by name, as the source stated them.
    retained: BTreeMap<String, Map<String, Value>>,
    /// The names of the time series the output carries, so a component's
    /// `time_series` references are emitted only when they resolve.
    time_series: BTreeSet<String>,
}

/// The sections the PMD reader kept untyped, decoded back to JSON. Only a
/// network read from PMD JSON carries them: there an untyped object is one
/// ENGINEERING component whose single unnamed property is the component's
/// JSON text. Untyped objects from other formats (an OpenDSS `loadshape`)
/// have no ENGINEERING form and stay out.
fn retained_sections(net: &MulticonductorNetwork) -> BTreeMap<String, Map<String, Value>> {
    let mut sections: BTreeMap<String, Map<String, Value>> = BTreeMap::new();
    if *net.source_format() != Some(crate::model::DistSourceFormat::PmdJson) {
        return sections;
    }
    for u in net.untyped_objects() {
        if let [(None, text)] = u.props.as_slice()
            && let Ok(value) = serde_json::from_str::<Value>(text)
        {
            sections
                .entry(u.class.clone())
                .or_default()
                .insert(u.name.clone(), value);
        }
    }
    sections
}

/// One id for each terminal name in the network that PMD cannot spell.
///
/// PMD requires integer connections. A name such as `n` therefore needs an
/// id, and that id must be the same everywhere the name appears, or two
/// elements at one bus stop sharing a conductor. Each name takes the
/// smallest positive integer that no numeric terminal name already uses, so
/// the ids stay as small as the model allows: an id far above the conductor
/// count would drive the `conductor_ids` enumeration to its cap and produce
/// a document with 64 conductors for a 4 conductor network.
///
/// Counting up from the largest numeric name would look simpler, but a
/// document may name a terminal `9223372036854775807`. That saturates every
/// id to the same value, and two conductors then merge into one. Taking the
/// smallest free integer cannot collide and cannot overflow: the search
/// stops after at most one step per terminal already in the document.
fn renamed_terminals(net: &MulticonductorNetwork) -> BTreeMap<String, i64> {
    let mut used = BTreeSet::new();
    let mut names = BTreeSet::new();
    for terminal in all_terminal_names(net) {
        match terminal.parse::<i64>() {
            Ok(value) => {
                used.insert(value);
            }
            Err(_) => {
                names.insert(terminal.to_string());
            }
        }
    }
    let mut out = BTreeMap::new();
    let mut next = 1i64;
    for name in names {
        while used.contains(&next) {
            next += 1;
        }
        used.insert(next);
        out.insert(name, next);
        next += 1;
    }
    out
}

/// Linecode lookup by name, built once rather than searched per line:
/// `net.linecode()` is a linear scan, and a line runs it once each.
fn linecodes_by_name(net: &MulticonductorNetwork) -> BTreeMap<String, &DistLineCode> {
    let mut by_name = BTreeMap::new();
    for c in net.line_codes() {
        by_name.entry(c.name.to_ascii_lowercase()).or_insert(c);
    }
    by_name
}

/// Bus lookup by id, built once rather than searched per load: `net.bus()`
/// is a linear scan, and a single phase load runs it once each.
fn buses_by_id(net: &MulticonductorNetwork) -> BTreeMap<String, &DistBus> {
    let mut by_id = BTreeMap::new();
    for b in net.buses() {
        by_id.entry(b.id.to_ascii_lowercase()).or_insert(b);
    }
    by_id
}

impl Writer {
    /// Terminal names as PMD integer connections. A name that is not numeric
    /// takes the id [`renamed_terminals`] gave it, so the same name is the
    /// same conductor everywhere in the document.
    fn conns(&mut self, map: &[String], what: &str) -> Vec<i64> {
        map.iter()
            .map(|t| {
                if let Ok(value) = t.parse::<i64>() {
                    return value;
                }
                let id = self.renamed_terminals.get(t).copied().unwrap_or(0);
                self.warnings.push(
                    &C::EMIT_PMD_VALUE_SUBSTITUTED,
                    format!("{what}: terminal `{t}` is not numeric; emitted as {id}"),
                );
                id
            })
            .collect()
    }
}

fn all_terminal_names(net: &MulticonductorNetwork) -> impl Iterator<Item = &str> {
    let maps = net
        .lines()
        .iter()
        .flat_map(|l| [&l.terminal_map_from, &l.terminal_map_to])
        .chain(
            net.switches()
                .iter()
                .flat_map(|s| [&s.terminal_map_from, &s.terminal_map_to]),
        )
        .chain(net.loads().iter().map(|l| &l.terminal_map))
        .chain(net.generators().iter().map(|g| &g.terminal_map))
        .chain(net.capacitors().iter().map(|c| &c.terminal_map))
        .chain(net.shunts().iter().map(|s| &s.terminal_map))
        .chain(net.sources().iter().map(|s| &s.terminal_map))
        .chain(net.ibrs().iter().map(|i| &i.terminal_map))
        .chain(
            net.transformers()
                .iter()
                .flat_map(|t| t.windings.iter().map(|w| &w.terminal_map)),
        );
    net.buses()
        .iter()
        .flat_map(|b| [&b.terminals, &b.grounded])
        .chain(maps)
        .flat_map(|m| m.iter().map(String::as_str))
}

/// A matrix as PMD serializes it: array of columns (`hcat` rebuilds it).
/// Rows shorter than the row count read as 0, so a degenerate model matrix
/// emits a square block instead of panicking.
/// The susceptance matrix of one rated capacitor bank over its own
/// conductors, siemens: the nameplate reactive power at the nameplate
/// voltage, the same equivalence the multiconductor admittance builder
/// stamps. Wye nameplate voltage is line to line with the neutral mapped
/// last; delta couples successive phase pairs; single phase spans its two
/// terminals.
fn capacitor_susceptance(
    c: &crate::model::DistCapacitor,
) -> std::result::Result<ConductorMatrix, String> {
    let finite_positive = |v: f64| v.is_finite() && v > 0.0;
    if !finite_positive(c.v_nom) || !c.q_rated.is_finite() {
        return Err("nameplate q_rated or v_nom is missing or nonpositive".into());
    }
    let n = c.terminal_map.len();
    let mut bs = vec![vec![0.0; n]; n];
    let mut couple = |a: usize, b: usize, y: f64| {
        bs[a][a] += y;
        bs[b][b] += y;
        bs[a][b] -= y;
        bs[b][a] -= y;
    };
    match c.configuration {
        crate::model::Configuration::SinglePhase => {
            if n != 2 {
                return Err(format!("single phase bank maps {n} terminals"));
            }
            couple(0, 1, c.q_rated / (c.v_nom * c.v_nom));
        }
        crate::model::Configuration::Wye => {
            let phases = n.saturating_sub(1);
            if phases == 0 {
                return Err("wye bank maps no phase terminal".into());
            }
            let v_ln = c.v_nom / 3f64.sqrt();
            let b = c.q_rated / (phases as f64) / (v_ln * v_ln);
            for phase in 0..phases {
                couple(phase, phases, b);
            }
        }
        crate::model::Configuration::Delta => {
            if n < 2 {
                return Err(format!("delta bank maps {n} terminals"));
            }
            // Two terminals form one phase-to-phase leg, not two; divide the
            // rated power by the legs actually stamped.
            let loops = if n == 2 { 1 } else { n };
            let b = c.q_rated / (loops as f64) / (c.v_nom * c.v_nom);
            for pair in 0..loops {
                couple(pair, (pair + 1) % n, b);
            }
        }
    }
    Ok(bs)
}

fn matrix(m: &ConductorMatrix) -> Value {
    let n = m.len();
    let cols: Vec<Value> = (0..n)
        .map(|j| {
            Value::Array(
                (0..n)
                    .map(|i| json!(m[i].get(j).copied().unwrap_or(0.0)))
                    .collect(),
            )
        })
        .collect();
    Value::Array(cols)
}

fn zero_matrix(n: usize) -> ConductorMatrix {
    vec![vec![0.0; n]; n]
}

/// A shunt whose stashed `conn` marks it a delta (line to line) bank.
fn shunt_is_delta(extras: &Extras) -> bool {
    extras
        .get("conn")
        .and_then(|v| v.as_str())
        .is_some_and(|t| t.to_ascii_lowercase().starts_with('d') || t.eq_ignore_ascii_case("ll"))
}

fn scale(m: &ConductorMatrix, k: f64) -> ConductorMatrix {
    m.iter()
        .map(|row| row.iter().map(|v| v * k).collect())
        .collect()
}

impl Writer {
    fn warn(&mut self, info: &'static crate::diagnostics::DiagnosticInfo, msg: impl Into<String>) {
        self.warnings.push(info, msg);
    }

    /// The dimension a matrix is materialized at, clamped to [`MAX_DIM`]
    /// with a diagnostic naming the element.
    fn bounded_dim(&mut self, n: usize, what: &str) -> usize {
        if n > MAX_DIM {
            self.warn(
                &C::EMIT_PMD_VALUE_CLAMPED,
                format!(
                    "{what}: {n} conductors exceed the supported maximum of \
                 {MAX_DIM}; matrices emitted at {MAX_DIM}"
                ),
            );
            MAX_DIM
        } else {
            n
        }
    }

    /// Reports extras the ENGINEERING model has no field for. `consumed`
    /// names keys a field already represents; `pmd_*` bookkeeping and the
    /// BMOPF subtype marker pass silently.
    fn extras_dropped(&mut self, extras: &crate::model::Extras, consumed: &[&str], what: &str) {
        for key in extras.keys() {
            // `time_series` is reported by `time_series_refs`.
            if consumed.contains(&key.as_str())
                || key.starts_with("pmd_")
                || key == "bmopf_subtype"
                || key == "time_series"
            {
                continue;
            }
            self.warn(
                &C::EMIT_PMD_FIELD_DROPPED,
                format!("{what}: `{key}` has no ENGINEERING field; dropped from the output"),
            );
        }
    }

    /// A component's ENGINEERING `time_series` field, which maps a component
    /// field to the name of a document level time series. It is emitted when
    /// every name it references is a time series the output carries, and
    /// reported as dropped otherwise, since PMD rejects a dangling reference.
    fn time_series_refs(&mut self, extras: &Extras, o: &mut Map<String, Value>, what: &str) {
        let Some(refs) = extras.get("time_series") else {
            return;
        };
        let resolves = refs.as_object().is_some_and(|fields| {
            fields
                .values()
                .all(|name| name.as_str().is_some_and(|n| self.time_series.contains(n)))
        });
        if resolves {
            o.insert("time_series".into(), refs.clone());
        } else {
            self.warn(
                &C::EMIT_PMD_FIELD_DROPPED,
                format!(
                    "{what}: `time_series` references a time series the output does not \
                     carry; dropped from the output"
                ),
            );
        }
    }

    fn extras_f64(extras: &Extras, key: &str) -> Option<f64> {
        extras.get(key).and_then(|v| {
            v.as_f64()
                .or_else(|| v.as_str().and_then(|s| s.parse().ok()))
        })
    }

    /// The element status: the reader's stash when the source carried a non
    /// ENABLED status, `ENABLED` otherwise.
    fn status(extras: &Extras) -> Value {
        extras
            .get("pmd_status")
            .cloned()
            .unwrap_or_else(|| json!("ENABLED"))
    }

    fn bus_coordinates(
        &mut self,
        o: &mut Map<String, Value>,
        b: &DistBus,
        net: &MulticonductorNetwork,
    ) {
        if let Some(location) = b.location {
            if !matches!(
                net.geo().as_ref().map(|geo| &geo.space),
                Some(CoordinateSpace::Geographic { .. })
            ) {
                self.warnings.push(&C::EMIT_PMD_FIELD_DROPPED, format!(
                    "bus {}: non-geographic or undeclared location is not emitted to PMD lon/lat",
                    b.id
                ));
                return;
            }
            if location.x.is_finite() && location.y.is_finite() {
                o.insert("lon".into(), json!(location.x));
                o.insert("lat".into(), json!(location.y));
            } else {
                self.warnings.push(
                    &C::EMIT_PMD_FIELD_DROPPED,
                    format!(
                        "bus {}: nonfinite location is not emitted to PMD JSON",
                        b.id
                    ),
                );
            }
            return;
        }
        if let Some(x) = Self::extras_f64(&b.extras, "x") {
            o.insert("lon".into(), json!(x));
        }
        if let Some(y) = Self::extras_f64(&b.extras, "y") {
            o.insert("lat".into(), json!(y));
        }
    }

    // One block per object field; splitting it would scatter a list that
    // reads end to end.
    #[expect(clippy::too_many_lines)]
    fn document(&mut self, net: &MulticonductorNetwork) -> Value {
        let mut doc = Map::new();
        doc.insert("data_model".into(), json!("ENGINEERING"));
        doc.insert(
            "name".into(),
            json!(net.name().clone().unwrap_or_default().to_lowercase()),
        );
        doc.insert(
            "files".into(),
            net.extras()
                .get("pmd_files")
                .cloned()
                .unwrap_or_else(|| json!([])),
        );

        // The reader's stash wins; synthesis covers dss/bmopf sourced
        // models.
        let settings = net
            .extras()
            .get("pmd_settings")
            .cloned()
            .unwrap_or_else(|| synthesized_settings(net));
        doc.insert("settings".into(), settings);

        // `conductor_ids` enumerates 1..=max, so its length is the numeric
        // value of a terminal name rather than a count of anything. A single
        // terminal named `4444444444444444` would ask for petabytes, so the
        // enumeration is clamped like every other model driven dimension.
        // A terminal name that is not numeric holds an id from
        // `renamed_terminals`. Those ids are the smallest free positive
        // integers, so a numeric name does not bound them and the enumeration
        // must include them explicitly. Without them the document lists fewer
        // conductors than its own `connections` arrays use, and a read back
        // and rewrite then produces a longer list.
        let max_conductor = net
            .buses()
            .iter()
            .flat_map(|b| &b.terminals)
            .filter_map(|t| t.parse::<i64>().ok())
            .chain(self.renamed_terminals.values().copied())
            .max()
            .unwrap_or(4);
        let max_dim = i64::try_from(MAX_DIM).expect("MAX_DIM is small");
        if max_conductor > max_dim {
            self.warn(
                &C::EMIT_PMD_VALUE_CLAMPED,
                format!(
                    "terminal {max_conductor} exceeds the supported maximum conductor id \
                 of {MAX_DIM}; conductor_ids enumerated to {MAX_DIM}"
                ),
            );
        }
        let max_conductor = max_conductor.clamp(4, max_dim);
        doc.insert(
            "conductor_ids".into(),
            Value::Array((1..=max_conductor).map(|i| json!(i)).collect()),
        );

        let mut buses = Map::new();
        for b in net.buses() {
            let mut o = Map::new();
            o.insert(
                "terminals".into(),
                json!(self.conns(&b.terminals, &format!("bus {}", b.id))),
            );
            let grounded = self.conns(&b.grounded, &format!("bus {}", b.id));
            // Nonzero grounding impedance rides in extras (the reader's
            // stash); zero vectors are the materialized default.
            for key in ["rg", "xg"] {
                let v = b
                    .extras
                    .get(key)
                    .cloned()
                    .unwrap_or_else(|| json!(vec![0.0; grounded.len()]));
                o.insert(key.into(), v);
            }
            o.insert("grounded".into(), json!(grounded));
            o.insert("status".into(), Self::status(&b.extras));
            self.bus_coordinates(&mut o, b, net);
            let phase_indices = b.phase_indices(net.extras().get("bmopf_terminal_conventions"));
            for (key, scalar, phases, default) in [
                ("vm_lb", b.v_min, &b.v_min_phase, 0.0),
                ("vm_ub", b.v_max, &b.v_max_phase, f64::INFINITY),
            ] {
                let retained = b.extras.get(&format!("pmd_{key}"));
                let mut values = retained
                    .and_then(Value::as_array)
                    .cloned()
                    .filter(|values| values.len() == b.terminals.len())
                    .unwrap_or_else(|| vec![json!(default); b.terminals.len()]);
                if scalar.is_some() || phases.is_some() {
                    for (phase, &terminal) in phase_indices.iter().enumerate() {
                        if let Some(v) =
                            scalar.or_else(|| phases.as_ref().and_then(|v| v.get(phase)).copied())
                        {
                            values[terminal] = json!(v / 1e3);
                        }
                    }
                    o.insert(key.into(), Value::Array(values));
                } else if let Some(retained) = retained {
                    o.insert(key.into(), retained.clone());
                }
            }
            // The phase-to-neutral, phase-to-phase, and sequence bound families
            // have no ENGINEERING analog; they drop loudly.
            for (key, present) in [
                ("vpn_min", b.vpn_min.is_some()),
                ("vpn_max", b.vpn_max.is_some()),
                ("vpp_min", b.vpp_min.is_some()),
                ("vpp_max", b.vpp_max.is_some()),
                ("vpos_min", b.vpos_min.is_some()),
                ("vpos_max", b.vpos_max.is_some()),
                ("vneg_max", b.vneg_max.is_some()),
                ("vzero_max", b.vzero_max.is_some()),
                ("vn_max", b.vn_max.is_some()),
            ] {
                if present {
                    self.warn(
                        &C::EMIT_PMD_FIELD_DROPPED,
                        format!(
                            "bus {}: `{key}` volt bounds have no ENGINEERING field; dropped",
                            b.id
                        ),
                    );
                }
            }
            buses.insert(b.id.to_lowercase(), Value::Object(o));
        }
        doc.insert("bus".into(), Value::Object(buses));

        self.line_codes(net, &mut doc);
        self.branches(net, &mut doc);
        self.injections(net, &mut doc);
        self.transformers(net, &mut doc);

        for u in net.untyped_objects() {
            let retained = self
                .retained
                .get(&u.class)
                .is_some_and(|items| items.contains_key(&u.name));
            if !retained {
                self.warn(
                    &C::EMIT_PMD_RECORD_DROPPED,
                    format!(
                        "{} {}: class is not converted to ENGINEERING; dropped from the output",
                        u.class, u.name
                    ),
                );
            }
        }
        for (class, items) in std::mem::take(&mut self.retained) {
            match doc.get_mut(&class) {
                None => {
                    doc.insert(class, Value::Object(items));
                }
                Some(Value::Object(section)) => {
                    for (name, value) in items {
                        if section.contains_key(&name) {
                            self.warn(
                                &C::EMIT_PMD_RECORD_DROPPED,
                                format!(
                                    "{class} {name}: the typed component of the same name \
                                     takes its place; the retained one is dropped"
                                ),
                            );
                        } else {
                            section.insert(name, value);
                        }
                    }
                }
                Some(_) => {
                    for name in items.keys() {
                        self.warn(
                            &C::EMIT_PMD_RECORD_DROPPED,
                            format!(
                                "{class} {name}: `{class}` is not a component section in the \
                                 output; dropped"
                            ),
                        );
                    }
                }
            }
        }
        // Top level values the reader kept (PMD's `time_elapsed`, say).
        if let Some(Value::Object(top_level)) = net.extras().get("pmd_top_level") {
            for (key, value) in top_level {
                if !doc.contains_key(key) {
                    doc.insert(key.clone(), value.clone());
                }
            }
        }
        Value::Object(doc)
    }

    fn line_codes(&mut self, net: &MulticonductorNetwork, doc: &mut Map<String, Value>) {
        // Linecodes the reader materialized from inline line impedance
        // re-inline on the line; they are skipped here unless a line
        // without the marker also references them.
        let inlined = inlined_codes(net);
        let mut codes = Map::new();
        for c in net.line_codes() {
            if inlined.contains(&c.name.to_lowercase()) {
                continue;
            }
            let mut o = Map::new();
            insert_impedance_matrices(&mut o, c, net.base_frequency());
            if let Some(i_max) = &c.i_max {
                o.insert("cm_ub".into(), json!(i_max));
            }
            if let Some(s_max) = &c.s_max {
                o.insert("sm_ub".into(), json!(s_max));
            }
            if c.source.is_some() {
                self.warn(
                    &C::EMIT_PMD_FIELD_DROPPED,
                    format!(
                        "linecode {}: matrix provenance `source` has no ENGINEERING field; dropped",
                        c.name
                    ),
                );
            }
            codes.insert(c.name.to_lowercase(), Value::Object(o));
        }
        if !codes.is_empty() {
            doc.insert("linecode".into(), Value::Object(codes));
        }
    }

    /// Line-level ratings (BMOPF `i_max`/`s_max`) map onto the ENGINEERING
    /// line's own `cm_ub`/`sm_ub` slots.
    fn line_ratings(o: &mut Map<String, Value>, l: &DistLine) {
        if let Some(i_max) = &l.i_max {
            o.insert("cm_ub".into(), json!(i_max));
        }
        if let Some(s_max) = &l.s_max {
            o.insert("sm_ub".into(), json!(s_max));
        }
    }

    // Two lines over the pedantic ceiling after the index lookup landed;
    // the function is one linear pass and splitting it hides the flow.
    #[allow(clippy::too_many_lines)]
    fn branches(&mut self, net: &MulticonductorNetwork, doc: &mut Map<String, Value>) {
        if !net.lines().is_empty() {
            let mut lines = Map::new();
            let linecodes_by_name = linecodes_by_name(net);
            for l in net.lines() {
                let mut o = Map::new();
                o.insert("f_bus".into(), json!(l.bus_from.to_lowercase()));
                o.insert("t_bus".into(), json!(l.bus_to.to_lowercase()));
                let what = format!("line {}", l.name);
                o.insert(
                    "f_connections".into(),
                    json!(self.conns(&l.terminal_map_from, &what)),
                );
                o.insert(
                    "t_connections".into(),
                    json!(self.conns(&l.terminal_map_to, &what)),
                );
                o.insert("length".into(), json!(l.length));
                // A line the reader materialized a linecode for re-inlines
                // its impedance, the dss2eng shape for rmatrix defined
                // lines: matrices on the line, no linecode key.
                let inline = l.extras.get("pmd_inline").and_then(Value::as_bool) == Some(true);
                let lc = linecodes_by_name.get(l.linecode.to_ascii_lowercase().as_str());
                match lc.copied() {
                    Some(c) if inline => {
                        insert_impedance_matrices(&mut o, c, net.base_frequency());
                        if let Some(i_max) = &c.i_max {
                            o.insert("cm_ub".into(), json!(i_max));
                        }
                        if let Some(s_max) = &c.s_max {
                            o.insert("sm_ub".into(), json!(s_max));
                        }
                    }
                    _ => {
                        if inline {
                            self.warn(&C::EMIT_PMD_VALUE_SUBSTITUTED, format!(
                                "{what}: linecode `{}` is missing; emitted the reference instead of inline impedance",
                                l.linecode
                            ));
                        }
                        o.insert("linecode".into(), json!(l.linecode.to_lowercase()));
                    }
                }
                Self::line_ratings(&mut o, l);
                o.insert("status".into(), Self::status(&l.extras));
                o.insert(
                    "source_id".into(),
                    json!(format!("line.{}", l.name.to_lowercase())),
                );
                self.time_series_refs(&l.extras, &mut o, &what);
                self.extras_dropped(&l.extras, &["units"], &what);
                lines.insert(l.name.to_lowercase(), Value::Object(o));
            }
            doc.insert("line".into(), Value::Object(lines));
        }

        if !net.switches().is_empty() {
            let mut switches = Map::new();
            for s in net.switches() {
                let mut o = Map::new();
                let what = format!("switch {}", s.name);
                let n = self.bounded_dim(s.terminal_map_from.len(), &what);
                o.insert("f_bus".into(), json!(s.bus_from.to_lowercase()));
                o.insert("t_bus".into(), json!(s.bus_to.to_lowercase()));
                o.insert(
                    "f_connections".into(),
                    json!(self.conns(&s.terminal_map_from, &what)),
                );
                o.insert(
                    "t_connections".into(),
                    json!(self.conns(&s.terminal_map_to, &what)),
                );
                // The reader's stash carries the source's series matrices;
                // otherwise PMD models a dss switch as a tiny series
                // resistance, 1e-4 ohm/m over the forced 0.001 m length
                // (the product form keeps the value bit identical).
                let rs = s.extras.get("pmd_rs").cloned().unwrap_or_else(|| {
                    let mut rs = zero_matrix(n);
                    for (i, row) in rs.iter_mut().enumerate() {
                        row[i] = 1e-4 * 0.001;
                    }
                    matrix(&rs)
                });
                o.insert("rs".into(), rs);
                let xs = s
                    .extras
                    .get("pmd_xs")
                    .cloned()
                    .unwrap_or_else(|| matrix(&zero_matrix(n)));
                o.insert("xs".into(), xs);
                o.insert("g_fr".into(), matrix(&zero_matrix(n)));
                o.insert("g_to".into(), matrix(&zero_matrix(n)));
                o.insert("b_fr".into(), matrix(&zero_matrix(n)));
                o.insert("b_to".into(), matrix(&zero_matrix(n)));
                if let Some(i_max) = &s.i_max {
                    o.insert("cm_ub".into(), json!(i_max));
                }
                o.insert(
                    "state".into(),
                    json!(if s.open { "OPEN" } else { "CLOSED" }),
                );
                o.insert("dispatchable".into(), json!("YES"));
                o.insert("status".into(), Self::status(&s.extras));
                o.insert(
                    "source_id".into(),
                    json!(format!("line.{}", s.name.to_lowercase())),
                );
                self.time_series_refs(&s.extras, &mut o, &what);
                self.extras_dropped(&s.extras, &[], &what);
                switches.insert(s.name.to_lowercase(), Value::Object(o));
            }
            doc.insert("switch".into(), Value::Object(switches));
        }
    }

    fn loads(&mut self, net: &MulticonductorNetwork, doc: &mut Map<String, Value>) {
        if !net.loads().is_empty() {
            let mut loads = Map::new();
            let buses_by_id = buses_by_id(net);
            for l in net.loads() {
                let mut o = Map::new();
                let what = format!("load {}", l.name);
                let connections = self.conns(&l.terminal_map, &what);
                // PMD types a two terminal load WYE when the return is the
                // bus's grounded neutral and DELTA otherwise.
                let configuration = match l.configuration {
                    Configuration::Delta => "DELTA",
                    Configuration::Wye => "WYE",
                    Configuration::SinglePhase => {
                        let grounded_return = l
                            .terminal_map
                            .last()
                            .zip(
                                buses_by_id
                                    .get(l.bus.to_ascii_lowercase().as_str())
                                    .copied(),
                            )
                            .is_some_and(|(t, b)| b.grounded.contains(t));
                        if grounded_return { "WYE" } else { "DELTA" }
                    }
                };
                o.insert("configuration".into(), json!(configuration));
                o.insert("connections".into(), json!(connections));
                o.insert(
                    "pd_nom".into(),
                    json!(l.p_nom.iter().map(|p| p / 1e3).collect::<Vec<_>>()),
                );
                o.insert(
                    "qd_nom".into(),
                    json!(l.q_nom.iter().map(|q| q / 1e3).collect::<Vec<_>>()),
                );
                o.insert("bus".into(), json!(l.bus.to_lowercase()));
                let mut insert_vm_nom = |v_nom: &[f64]| {
                    if let Some(value) = source_vm_nom(&l.extras, v_nom) {
                        o.insert("vm_nom".into(), value);
                    } else if !v_nom.is_empty() {
                        let value = if v_nom.len() == 1 {
                            json!(v_nom[0] / 1e3)
                        } else {
                            json!(v_nom.iter().map(|v| v / 1e3).collect::<Vec<_>>())
                        };
                        o.insert("vm_nom".into(), value);
                    } else if let Some(kv) = Self::extras_f64(&l.extras, "kv") {
                        o.insert("vm_nom".into(), json!(kv));
                    }
                };
                let nominal_model = l.voltage_model.without_voltage_bounds();
                if matches!(
                    l.voltage_model,
                    DistLoadVoltageModel::BoundedZip { .. }
                        | DistLoadVoltageModel::BoundedExponential { .. }
                        | DistLoadVoltageModel::BoundedConstantPower { .. }
                ) {
                    self.warn(&C::EMIT_PMD_VALUE_SUBSTITUTED, format!("{what}: voltage-band transitions, current limits and dropout have no PMD load-law field; emitted the nominal law"));
                }
                let model = match &nominal_model {
                    DistLoadVoltageModel::BoundedZip { .. }
                    | DistLoadVoltageModel::BoundedExponential { .. }
                    | DistLoadVoltageModel::BoundedConstantPower { .. } => {
                        unreachable!("bounds handled above")
                    }
                    DistLoadVoltageModel::ConstantImpedance { v_nom } => {
                        insert_vm_nom(v_nom);
                        "IMPEDANCE"
                    }
                    DistLoadVoltageModel::ConstantCurrent { v_nom } => {
                        insert_vm_nom(v_nom);
                        "CURRENT"
                    }
                    DistLoadVoltageModel::Zip { v_nom, .. } => {
                        insert_vm_nom(v_nom);
                        "ZIPV"
                    }
                    DistLoadVoltageModel::Exponential { v_nom, .. } => {
                        insert_vm_nom(v_nom);
                        self.warn(&C::EMIT_PMD_VALUE_SUBSTITUTED, format!(
                            "{what}: exponential load model has no ENGINEERING field; emitted POWER"
                        ));
                        "POWER"
                    }
                    DistLoadVoltageModel::ConstantPower { v_nom } => {
                        insert_vm_nom(v_nom);
                        "POWER"
                    }
                };
                o.insert("model".into(), json!(model));
                o.insert("dispatchable".into(), json!("NO"));
                o.insert("status".into(), Self::status(&l.extras));
                o.insert(
                    "source_id".into(),
                    json!(format!("load.{}", l.name.to_lowercase())),
                );
                self.time_series_refs(&l.extras, &mut o, &what);
                self.extras_dropped(&l.extras, &["kv", "model", "pf"], &what);
                loads.insert(l.name.to_lowercase(), Value::Object(o));
            }
            doc.insert("load".into(), Value::Object(loads));
        }
    }

    fn generators(&mut self, net: &MulticonductorNetwork, doc: &mut Map<String, Value>) {
        if !net.generators().is_empty() {
            let mut gens = Map::new();
            for g in net.generators() {
                let mut o = Map::new();
                let what = format!("generator {}", g.name);
                o.insert("bus".into(), json!(g.bus.to_lowercase()));
                o.insert(
                    "connections".into(),
                    json!(self.conns(&g.terminal_map, &what)),
                );
                o.insert(
                    "configuration".into(),
                    json!(match g.configuration {
                        Configuration::Delta => "DELTA",
                        _ => "WYE",
                    }),
                );
                let kw = |w: &[f64]| w.iter().map(|v| v / 1e3).collect::<Vec<_>>();
                o.insert("pg".into(), json!(kw(&g.p_nom)));
                o.insert("qg".into(), json!(kw(&g.q_nom)));
                if let Some(b) = &g.q_min {
                    o.insert("qg_lb".into(), json!(kw(b)));
                }
                if let Some(b) = &g.q_max {
                    o.insert("qg_ub".into(), json!(kw(b)));
                }
                if let Some(b) = &g.p_min {
                    o.insert("pg_lb".into(), json!(kw(b)));
                }
                if let Some(b) = &g.p_max {
                    o.insert("pg_ub".into(), json!(kw(b)));
                }
                if g.cost.is_some() {
                    self.warn(
                        &C::EMIT_PMD_FIELD_DROPPED,
                        format!("{what}: generation cost has no ENGINEERING field; dropped"),
                    );
                }
                // The ENGINEERING generator carries kVA-scale sm_ub/cm_ub;
                // that mapping is a #266 decision, so the drop stays loud.
                for (key, present) in [("s_max", g.s_max.is_some()), ("i_max", g.i_max.is_some())] {
                    if present {
                        self.warn(
                            &C::EMIT_PMD_FIELD_DROPPED,
                            format!(
                                "{what}: `{key}` has no ENGINEERING generator mapping yet; dropped"
                            ),
                        );
                    }
                }
                o.insert("control_mode".into(), json!("FREQUENCYDROOP"));
                o.insert("status".into(), Self::status(&g.extras));
                o.insert(
                    "source_id".into(),
                    json!(format!("generator.{}", g.name.to_lowercase())),
                );
                self.time_series_refs(&g.extras, &mut o, &what);
                self.extras_dropped(&g.extras, &["kv"], &what);
                gens.insert(g.name.to_lowercase(), Value::Object(o));
            }
            doc.insert("generator".into(), Value::Object(gens));
        }
    }

    fn injections(&mut self, net: &MulticonductorNetwork, doc: &mut Map<String, Value>) {
        self.loads(net, doc);
        self.generators(net, doc);
        // Typed capacitor banks convert to ENGINEERING shunts: the nameplate
        // reactive power at the nameplate voltage becomes the susceptance
        // matrix over the bank's own conductors, the same equivalence the
        // admittance builder stamps.
        let mut capacitor_shunts = Map::new();
        for c in net.capacitors() {
            let what = format!("capacitor {}", c.name);
            match capacitor_susceptance(c) {
                Ok(bs) => {
                    let n = bs.len();
                    let mut o = Map::new();
                    o.insert("bus".into(), json!(c.bus.to_lowercase()));
                    o.insert(
                        "connections".into(),
                        json!(self.conns(&c.terminal_map, &what)),
                    );
                    o.insert("gs".into(), matrix(&vec![vec![0.0; n]; n]));
                    o.insert("bs".into(), matrix(&bs));
                    o.insert(
                        "configuration".into(),
                        json!(match c.configuration {
                            Configuration::Delta => "DELTA",
                            _ => "WYE",
                        }),
                    );
                    o.insert("model".into(), json!("CAPACITOR"));
                    o.insert("dispatchable".into(), json!("NO"));
                    o.insert("status".into(), Self::status(&c.extras));
                    o.insert(
                        "source_id".into(),
                        json!(format!("capacitor.{}", c.name.to_lowercase())),
                    );
                    self.time_series_refs(&c.extras, &mut o, &what);
                    self.extras_dropped(&c.extras, &[], &what);
                    capacitor_shunts.insert(c.name.to_lowercase(), Value::Object(o));
                }
                Err(reason) => {
                    self.warn(
                        &C::EMIT_PMD_RECORD_DROPPED,
                        format!("{what}: {reason}; dropped"),
                    );
                }
            }
        }
        if !net.shunts().is_empty() || !capacitor_shunts.is_empty() {
            let mut shunts = capacitor_shunts;
            for s in net.shunts() {
                let mut o = Map::new();
                let what = format!("shunt {}", s.name);
                o.insert("bus".into(), json!(s.bus.to_lowercase()));
                o.insert(
                    "connections".into(),
                    json!(self.conns(&s.terminal_map, &what)),
                );
                o.insert("gs".into(), matrix(&s.g));
                o.insert("bs".into(), matrix(&s.b));
                // A delta bank carries a `conn` marker and an off diagonal B
                // matrix; emitting it as WYE would describe a line to line
                // admittance as line to ground.
                let configuration = if shunt_is_delta(&s.extras) {
                    "DELTA"
                } else {
                    "WYE"
                };
                o.insert("configuration".into(), json!(configuration));
                o.insert("model".into(), json!("CAPACITOR"));
                o.insert("dispatchable".into(), json!("NO"));
                o.insert("status".into(), Self::status(&s.extras));
                o.insert(
                    "source_id".into(),
                    json!(format!("capacitor.{}", s.name.to_lowercase())),
                );
                self.time_series_refs(&s.extras, &mut o, &what);
                self.extras_dropped(&s.extras, &["kv", "kvar", "conn"], &what);
                shunts.insert(s.name.to_lowercase(), Value::Object(o));
            }
            doc.insert("shunt".into(), Value::Object(shunts));
        }

        let mut sources = Map::new();
        for vs in net.sources() {
            sources.insert(vs.name.to_lowercase(), self.voltage_source(vs));
        }
        doc.insert("voltage_source".into(), Value::Object(sources));
    }

    fn voltage_source(&mut self, vs: &VoltageSource) -> Value {
        let mut o = Map::new();
        let what = format!("voltage source {}", vs.name);
        let connections = self.conns(&vs.terminal_map, &what);
        let n = self.bounded_dim(connections.len(), &what);
        o.insert("bus".into(), json!(vs.bus.to_lowercase()));
        o.insert("connections".into(), json!(connections));
        o.insert("configuration".into(), json!("WYE"));
        o.insert(
            "vm".into(),
            json!(vs.v_magnitude.iter().map(|v| v / 1e3).collect::<Vec<_>>()),
        );
        o.insert(
            "va".into(),
            json!(
                vs.v_angle
                    .iter()
                    .map(|a| a.to_degrees())
                    .collect::<Vec<_>>()
            ),
        );
        // Retain explicit PMD source matrices for same-format fidelity.
        // A typed ideal source has no implicit short-circuit impedance: a
        // DSS import already carries its full impedance in a separate line.
        if let (Some(rs), Some(xs)) = (vs.extras.get("rs"), vs.extras.get("xs")) {
            o.insert("rs".into(), rs.clone());
            o.insert("xs".into(), xs.clone());
        } else {
            o.insert("rs".into(), matrix(&zero_matrix(n)));
            o.insert("xs".into(), matrix(&zero_matrix(n)));
        }
        o.insert("status".into(), Self::status(&vs.extras));
        o.insert(
            "source_id".into(),
            json!(format!("vsource.{}", vs.name.to_lowercase())),
        );
        // Nominal voltage and power bases are used by synthesized_settings.
        // Short-circuit hints cannot override the typed ideal constraint.
        self.time_series_refs(&vs.extras, &mut o, &what);
        self.extras_dropped(
            &vs.extras,
            &[
                "basekv",
                "nominal_phase_kv",
                "basemva",
                "pu",
                "rs",
                "xs",
                "configuration",
            ],
            &what,
        );
        Value::Object(o)
    }

    fn transformers(&mut self, net: &MulticonductorNetwork, doc: &mut Map<String, Value>) {
        if net.transformers().is_empty() {
            return;
        }
        let mut out = Map::new();
        for t in net.transformers() {
            out.insert(t.name.to_lowercase(), self.transformer(t));
        }
        doc.insert("transformer".into(), Value::Object(out));
    }

    fn transformer(&mut self, t: &DistTransformer) -> Value {
        let mut o = Map::new();
        let what = format!("transformer {}", t.name);
        let phases = t.phases;

        // The reader's stash carries a source polarity/connections pair the
        // lag convention does not reproduce (euro/lead, reversed windings);
        // emit it verbatim. Otherwise apply the ANSI lag convention the
        // reference dss2eng uses: barrel roll the wye phase conductors
        // under a delta primary and reverse the winding polarity.
        let stashed = t.extras.contains_key("pmd_polarity");
        let mut buses = Vec::new();
        let mut connections: Vec<Value> = Vec::new();
        for (w_idx, w) in t.windings.iter().enumerate() {
            buses.push(json!(w.bus.to_lowercase()));
            let mut c = self.conns(&w.terminal_map, &what);
            if !stashed
                && w_idx > 0
                && t.windings[0].conn == DistWindingConn::Delta
                && w.conn == DistWindingConn::Wye
                && c.len() > 1
            {
                let phases_part = c.len() - 1;
                c[..phases_part].rotate_left(1);
            }
            connections.push(json!(c));
        }
        o.insert("bus".into(), Value::Array(buses));
        o.insert(
            "connections".into(),
            t.extras
                .get("pmd_connections")
                .cloned()
                .unwrap_or(Value::Array(connections)),
        );
        o.insert(
            "polarity".into(),
            t.extras
                .get("pmd_polarity")
                .cloned()
                .unwrap_or_else(|| json!(lag_polarity(&t.windings))),
        );
        o.insert(
            "configuration".into(),
            Value::Array(
                t.windings
                    .iter()
                    .map(|w| {
                        json!(match w.conn {
                            DistWindingConn::Wye => "WYE",
                            DistWindingConn::Delta => "DELTA",
                        })
                    })
                    .collect(),
            ),
        );
        o.insert(
            "rw".into(),
            json!(
                t.windings
                    .iter()
                    .map(|w| w.r_pct / 100.0)
                    .collect::<Vec<_>>()
            ),
        );
        o.insert(
            "xsc".into(),
            json!(t.xsc_pct.iter().map(|x| x / 100.0).collect::<Vec<_>>()),
        );
        o.insert(
            "sm_nom".into(),
            json!(
                t.windings
                    .iter()
                    .map(|w| w.s_rating / 1e3)
                    .collect::<Vec<_>>()
            ),
        );
        o.insert(
            "vm_nom".into(),
            json!(t.windings.iter().map(|w| w.v_ref / 1e3).collect::<Vec<_>>()),
        );
        // A transformer with no windings is degenerate but reachable from
        // untrusted input (a PMD or BMOPF document with the winding array
        // absent), so derive the emergency rating default from the first
        // winding only when one exists rather than indexing unconditionally.
        let sm_ub = Self::extras_f64(&t.extras, "emerghkva")
            .unwrap_or_else(|| t.windings.first().map_or(0.0, |w| w.s_rating / 1e3 * 1.5));
        o.insert("sm_ub".into(), json!(sm_ub));
        insert_tap_fields(&mut o, t, phases);
        if let Some(controls) = t.extras.get("controls") {
            o.insert("controls".into(), controls.clone());
        }
        self.transformer_no_load_fields(t, &mut o, &what);
        o.insert("status".into(), Self::status(&t.extras));
        o.insert(
            "source_id".into(),
            json!(format!("transformer.{}", t.name.to_lowercase())),
        );
        Value::Object(o)
    }
    fn transformer_no_load_fields(
        &mut self,
        t: &DistTransformer,
        o: &mut Map<String, Value>,
        what: &str,
    ) {
        let explicit_shunt = crate::model::transformer_no_load_percentages(t);
        let (loss, imag) = explicit_shunt.unwrap_or_else(|| {
            (
                Self::extras_f64(&t.extras, "%noloadloss").unwrap_or(0.0),
                Self::extras_f64(&t.extras, "%imag").unwrap_or(0.0),
            )
        });
        let noloadloss = loss / 100.0;
        let cmag = imag / 100.0;
        o.insert("noloadloss".into(), json!(noloadloss));
        o.insert("cmag".into(), json!(cmag));
        let mut allowed = vec!["controls", "%loadloss", "%noloadloss", "%imag", "emerghkva"];
        if explicit_shunt.is_some() {
            allowed.push("no_load_shunt");
        }
        self.time_series_refs(&t.extras, o, what);
        self.extras_dropped(&t.extras, &allowed, what);
    }
}

/// The per winding per phase tap arrays. The reader's `pmd_tm_*` stashes
/// win (per phase taps, custom bounds, regulator fix flags); the defaults
/// for the rest are the engine's bounds (0.9..1.1) and step (1/32).
fn insert_tap_fields(o: &mut Map<String, Value>, t: &DistTransformer, phases: usize) {
    let nw = t.windings.len();
    let mut insert = |key: &str, default: fn(&DistTransformer, usize, usize) -> Value| {
        let v = t
            .extras
            .get(&format!("pmd_{key}"))
            .cloned()
            .unwrap_or_else(|| default(t, nw, phases));
        o.insert(key.into(), v);
    };
    insert("tm_set", |t, _, phases| {
        Value::Array(
            t.windings
                .iter()
                .map(|w| json!(vec![w.tap; phases]))
                .collect(),
        )
    });
    insert("tm_fix", |_, nw, phases| {
        Value::Array((0..nw).map(|_| json!(vec![true; phases])).collect())
    });
    insert("tm_lb", |_, nw, phases| {
        Value::Array((0..nw).map(|_| json!(vec![0.9; phases])).collect())
    });
    insert("tm_ub", |_, nw, phases| {
        Value::Array((0..nw).map(|_| json!(vec![1.1; phases])).collect())
    });
    insert("tm_step", |_, nw, phases| {
        Value::Array((0..nw).map(|_| json!(vec![1.0 / 32.0; phases])).collect())
    });
}

/// The ENGINEERING settings for a model without the reader's stash (dss or
/// bmopf sourced), following the dss2eng conventions: the per bus vbase is
/// the source's nominal line to neutral kV without the pu factor folded
/// in, and sbase is basemva in kVA (default 100 MVA).
fn synthesized_settings(net: &MulticonductorNetwork) -> Value {
    let mut settings = Map::new();
    settings.insert("base_frequency".into(), json!(net.base_frequency()));
    settings.insert("power_scale_factor".into(), json!(1000.0));
    settings.insert("voltage_scale_factor".into(), json!(1000.0));
    let sbase = net
        .sources()
        .first()
        .and_then(|vs| Writer::extras_f64(&vs.extras, "basemva"))
        .map_or(100_000.0, |mva| mva * 1e3);
    settings.insert("sbase_default".into(), json!(sbase));
    let mut vbases = Map::new();
    for vs in net.sources() {
        let phases = count_phases(vs).max(1) as f64;
        let vln_kv = Writer::extras_f64(&vs.extras, "nominal_phase_kv").unwrap_or_else(|| {
            Writer::extras_f64(&vs.extras, "basekv").map_or_else(
                || {
                    let pu = Writer::extras_f64(&vs.extras, "pu").unwrap_or(1.0);
                    vs.v_magnitude.first().copied().unwrap_or(0.0) / 1e3 / pu
                },
                |kv| kv / phases.sqrt(),
            )
        });
        vbases.insert(vs.bus.to_lowercase(), json!(vln_kv));
    }
    settings.insert("vbases_default".into(), Value::Object(vbases));
    Value::Object(settings)
}

/// The polarity vector the ANSI lag convention produces for these windings:
/// -1 with a barrel roll on each wye winding under a delta primary, -1 on
/// the reversed second half of a center tap secondary, 1 elsewhere. The
/// reader compares the source against this to decide whether the file's
/// polarity needs an extras stash.
pub(super) fn lag_polarity(windings: &[DistWinding]) -> Vec<i64> {
    let nw = windings.len();
    let mut polarity = vec![1i64; nw];
    for (w_idx, w) in windings.iter().enumerate().skip(1) {
        if windings[0].conn == DistWindingConn::Delta
            && w.conn == DistWindingConn::Wye
            && w.terminal_map.len() > 1
        {
            polarity[w_idx] = -1;
        }
        // Center tap: the second half winding is reversed.
        if w_idx == 2 && nw == 3 && windings[1].terminal_map.last() == w.terminal_map.first() {
            polarity[w_idx] = -1;
        }
    }
    polarity
}

/// Names (lowercased) of linecodes that re-inline on their lines: every
/// referencing line carries the reader's `pmd_inline` marker.
fn inlined_codes(net: &MulticonductorNetwork) -> BTreeSet<String> {
    let mut all_inline = BTreeMap::new();
    for line in net.lines() {
        let inline = line.extras.get("pmd_inline").and_then(Value::as_bool) == Some(true);
        all_inline
            .entry(line.linecode.to_ascii_lowercase())
            .and_modify(|value| *value &= inline)
            .or_insert(inline);
    }
    net.line_codes()
        .iter()
        .filter(|code| all_inline.get(&code.name.to_ascii_lowercase()) == Some(&true))
        .map(|code| code.name.to_lowercase())
        .collect()
}

/// The six ENGINEERING impedance matrices of a linecode, emitted onto a
/// `linecode` entry or re-inlined onto a line. The b_fr/b_to numbers are
/// the dss cmatrix halves in nanofarads per meter (the susceptance follows
/// as 2 pi f C); the model holds true siemens per meter, so divide the
/// omega back out — or emit the reader's raw stash, which is bit exact.
fn insert_impedance_matrices(o: &mut Map<String, Value>, c: &DistLineCode, base_frequency: f64) {
    o.insert("rs".into(), matrix(&c.r_series));
    o.insert("xs".into(), matrix(&c.x_series));
    o.insert("g_fr".into(), matrix(&c.g_from));
    o.insert("g_to".into(), matrix(&c.g_to));
    if let (Some(fr), Some(to)) = (c.extras.get("pmd_b_fr"), c.extras.get("pmd_b_to")) {
        o.insert("b_fr".into(), fr.clone());
        o.insert("b_to".into(), to.clone());
    } else {
        let to_nf = 1.0 / (std::f64::consts::TAU * base_frequency * 1e-9);
        o.insert("b_fr".into(), matrix(&scale(&c.b_from, to_nf)));
        o.insert("b_to".into(), matrix(&scale(&c.b_to, to_nf)));
    }
}

fn count_phases(vs: &VoltageSource) -> usize {
    vs.v_magnitude.iter().filter(|&&v| v > 0.0).count()
}

fn source_vm_nom(extras: &Extras, v_nom: &[f64]) -> Option<Value> {
    let raw = extras.get("kv")?;
    if v_nom.is_empty() {
        return Some(raw.clone());
    }
    if let Some(kv) = raw
        .as_f64()
        .or_else(|| raw.as_str().and_then(|s| s.parse().ok()))
        && v_nom.iter().all(|v| same_voltage(*v, kv * 1e3))
    {
        return Some(json!(kv));
    }
    let vals: Vec<f64> = raw
        .as_array()?
        .iter()
        .filter_map(serde_json::Value::as_f64)
        .collect();
    if vals.len() == 1 && v_nom.iter().all(|v| same_voltage(*v, vals[0] * 1e3)) {
        return Some(raw.clone());
    }
    if vals.len() == v_nom.len()
        && vals
            .iter()
            .zip(v_nom)
            .all(|(a, b)| same_voltage(*b, *a * 1e3))
    {
        return Some(raw.clone());
    }
    None
}

fn same_voltage(a: f64, b: f64) -> bool {
    (a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1.0)
}