powerio-dist 0.5.0

Multiconductor distribution network model and lossless converters for OpenDSS, PMD JSON, and BMOPF JSON.
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
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
//! [`DistNetwork`] into OpenDSS `.dss` text.
//!
//! The canonical writer regenerates a solvable case from the typed model:
//! a `Clear`/`Set DefaultBaseFrequency` header, the circuit with its
//! source, linecodes in meters, elements with explicit bus dots (a
//! terminal in the bus's perfectly grounded set emits as node 0, the exact
//! inverse of the reader's materialization), the source `Set` options the
//! writer does not derive itself, `Set VoltageBases`, `Calcvoltagebases`,
//! and `Solve`. Element extras whose keys appear in the class property
//! tables emit verbatim; everything else is reported.
//!
//! Floats print through Rust's shortest round trip formatting; OpenDSS
//! reads the full precision back.

use std::collections::BTreeMap;
use std::fmt::Write as _;

use crate::convert::Conversion;
use crate::model::{
    Configuration, DistBus, DistLoadVoltageModel, DistNetwork, Extras, Mat, Winding, WindingConn,
};

use super::read::delta_edges;
use super::{lex, prop};

/// Writes canonical `.dss` text from the model.
pub fn write_dss(net: &DistNetwork) -> Conversion {
    let mut w = DssWriter {
        out: String::new(),
        warnings: Vec::new(),
        grounded: net
            .buses
            .iter()
            .map(|b| (b.id.to_ascii_lowercase(), b.grounded.clone()))
            .collect(),
        terminals: net
            .buses
            .iter()
            .map(|b| (b.id.to_ascii_lowercase(), b.terminals.clone()))
            .collect(),
        kv_estimate: estimate_bus_kv(net),
    };
    w.network(net);
    Conversion {
        text: w.out,
        warnings: w.warnings,
    }
}

struct DssWriter {
    out: String,
    warnings: Vec<String>,
    /// Bus id (lowercase) → perfectly grounded terminal names.
    grounded: BTreeMap<String, Vec<String>>,
    /// Bus id (lowercase) → ordered terminal names.
    terminals: BTreeMap<String, Vec<String>>,
    /// Bus id (lowercase) → phase to neutral voltage estimate, volts.
    kv_estimate: BTreeMap<String, f64>,
}

#[derive(Clone, Copy)]
struct ElementKv<'a> {
    bus: &'a str,
    phases: usize,
    configuration: Configuration,
    name: &'a str,
    class: &'a str,
    typed_kv: Option<f64>,
}

/// Phase to neutral voltage per bus, propagated from the sources through
/// lines and switches (same level) and transformers (winding ratios). The
/// estimate feeds load/capacitor `kv` and `Set VoltageBases` when the
/// source format did not carry them.
///
/// The seed is not the model voltage directly: it is the basekv the writer
/// will emit (the stashed token when the source carried one), run through
/// the reader's basekv → per phase formula. A reparse then reproduces the
/// same floats bit for bit; seeding from `v_magnitude` is not a fixed
/// point of the sqrt round trip and `Set VoltageBases` would drift one ulp
/// per write. Transformer ratios use `(v_ref / 1e3) * 1e3`, the value a
/// reparse of the emitted `kvs=` rebuilds, for the same reason.
fn estimate_bus_kv(net: &DistNetwork) -> BTreeMap<String, f64> {
    let mut kv: BTreeMap<String, f64> = BTreeMap::new();
    for vs in &net.sources {
        let phases = source_phases(net, vs);
        let basekv = extras_f64(&vs.extras, "basekv").unwrap_or_else(|| source_basekv(vs, phases));
        let pu = extras_f64(&vs.extras, "pu").unwrap_or(1.0);
        let vln = basekv * 1e3 * pu / source_chord(phases);
        if vln > 0.0 {
            kv.insert(vs.bus.to_ascii_lowercase(), vln);
        }
    }
    // Per bus grounded terminal sets, to tell a line to neutral winding (a
    // terminal tied to ground in its map) from a line to line one. Grounding
    // and the terminal map both survive a BMOPF round trip, the wye/delta
    // label does not, so this is what the transformer ratio keys on below.
    let grounded: BTreeMap<String, &Vec<String>> = net
        .buses
        .iter()
        .map(|b| (b.id.to_ascii_lowercase(), &b.grounded))
        .collect();
    for _ in 0..net.buses.len() {
        let mut changed = false;
        for l in &net.lines {
            let (f, t) = (
                l.bus_from.to_ascii_lowercase(),
                l.bus_to.to_ascii_lowercase(),
            );
            match (kv.get(&f).copied(), kv.get(&t).copied()) {
                (Some(v), None) => {
                    kv.insert(t, v);
                    changed = true;
                }
                (None, Some(v)) => {
                    kv.insert(f, v);
                    changed = true;
                }
                _ => {}
            }
        }
        for s in &net.switches {
            let (f, t) = (
                s.bus_from.to_ascii_lowercase(),
                s.bus_to.to_ascii_lowercase(),
            );
            match (kv.get(&f).copied(), kv.get(&t).copied()) {
                (Some(v), None) => {
                    kv.insert(t, v);
                    changed = true;
                }
                (None, Some(v)) => {
                    kv.insert(f, v);
                    changed = true;
                }
                _ => {}
            }
        }
        for t in &net.transformers {
            // Propagate by winding voltage ratio from any known winding bus.
            // The bus map holds phase to neutral voltages, so each winding's
            // v_ref is first reduced to that base. A winding's rating is the
            // voltage across its two terminals: line to line when both are
            // phases (a polyphase winding, or a single phase delta leg), line
            // to neutral when one terminal is the bus's grounded neutral.
            // Matched windings (wye-wye, three phase wye-delta) cancel the
            // factor; only a mixed open delta leg (single phase wye to delta)
            // shifts, where the old raw ratio was a sqrt(3) off.
            let pn = |w: &Winding| {
                let v = (w.v_ref / 1e3) * 1e3;
                let line_to_neutral = t.phases < 2
                    && grounded
                        .get(&w.bus.to_ascii_lowercase())
                        .is_some_and(|g| w.terminal_map.iter().any(|tm| g.contains(tm)));
                if line_to_neutral { v } else { v / 3f64.sqrt() }
            };
            let known: Option<(usize, f64)> = t
                .windings
                .iter()
                .enumerate()
                .find_map(|(i, w)| kv.get(&w.bus.to_ascii_lowercase()).map(|v| (i, *v)));
            if let Some((i, v_known)) = known {
                let pn_known = pn(&t.windings[i]);
                if pn_known > 0.0 {
                    for (j, w) in t.windings.iter().enumerate() {
                        if j != i && !kv.contains_key(&w.bus.to_ascii_lowercase()) {
                            kv.insert(w.bus.to_ascii_lowercase(), v_known * pn(w) / pn_known);
                            changed = true;
                        }
                    }
                }
            }
        }
        if !changed {
            break;
        }
    }
    kv
}

/// A float in the shortest form Rust round trips. Negative zero canonicalizes
/// to `0` so a `-x/denom` that lands on `-0.0` does not emit the literal `-0`.
fn num(v: f64) -> String {
    let v = if v == 0.0 { 0.0 } else { v };
    format!("{v}")
}

/// VSource.cpp's per phase magnitude divisor: the chord of the n-gon
/// (1 for a single phase source, sqrt(3) at n = 3). Division by the
/// 1 phase chord is exact, so one expression serves both reader branches.
fn source_chord(phases: usize) -> f64 {
    if phases <= 1 {
        1.0
    } else {
        2.0 * (std::f64::consts::PI / phases as f64).sin()
    }
}

/// The basekv a source without a stashed token emits: the model magnitude
/// through the inverse of the reader's chord formula.
fn source_basekv(vs: &crate::model::VoltageSource, phases: usize) -> f64 {
    vs.v_magnitude.iter().copied().fold(0.0_f64, f64::max) * source_chord(phases) / 1e3
}

/// An extra as a number: the reader stashes written tokens as strings and
/// materialized defaults as numbers.
fn extras_f64(extras: &Extras, key: &str) -> Option<f64> {
    let v = extras.get(key)?;
    v.as_f64()
        .or_else(|| v.as_str().and_then(|s| s.parse().ok()))
        // A stashed `inf`/`NaN` token parses to a non-finite f64; reject it so
        // it never reaches `num()` and emits a literal `inf`/`NaN` DSS token.
        .filter(|f| f.is_finite())
}

fn extras_usize(extras: &Extras, key: &str) -> Option<usize> {
    let v = extras.get(key)?;
    v.as_u64()
        .and_then(|u| usize::try_from(u).ok())
        .or_else(|| v.as_str().and_then(|s| s.parse().ok()))
        .or_else(|| {
            v.as_f64()
                .filter(|f| f.fract() == 0.0 && *f >= 0.0)
                .map(|f| f as usize)
        })
}

fn zipv_cutoff(value: Option<&serde_json::Value>) -> Option<f64> {
    let text = value?.as_str()?;
    lex::Value::new(text)
        .to_vector(None)
        .ok()
        .and_then(|v| v.get(6).copied())
        .filter(|v| v.is_finite())
}

/// Whether the dss tokenizer would split this name: its delimiters, quote
/// pair characters, comment openers, and (in bus ids) the node dot.
fn name_breaks_dss(name: &str, is_bus_id: bool) -> bool {
    name.contains("//")
        || name.chars().any(|c| {
            matches!(
                c,
                ' ' | '\t' | ',' | '=' | '!' | '"' | '\'' | '(' | ')' | '[' | ']' | '{' | '}'
            ) || (is_bus_id && c == '.')
        })
}

/// A `key=value` value as dss text. A value the lexer scans back as one
/// bare token emits bare; anything else wraps in the first quote pair
/// whose closer is absent from the value. The lexer honors all five pairs,
/// and its quoted scan runs to the closer without checking delimiters or
/// comment openers, so the wrapper protects spaces, commas, `=`, `!`, and
/// `//`. The choice depends only on the value: the reader strips the
/// wrapper, so the next write sees the bare value and picks the same form.
/// `false` means nothing reparses to the value — every closer appears in
/// it and bare scanning splits it — and the caller must warn.
fn dss_value_out(value: &str) -> (String, bool) {
    // An empty value is never bare representable: `key=` makes the lexer
    // eat the next token as the value. `()` strips back to the empty string.
    if value.is_empty() {
        return ("()".to_string(), true);
    }
    let mut scan = lex::Scanner::new(value, None);
    let bare = scan.next_param().is_some_and(|p| {
        p.name.is_none() && !p.value.quoted && p.value.text == value && scan.next_param().is_none()
    });
    if bare {
        return (value.to_string(), true);
    }
    for (open, close) in [('(', ')'), ('[', ']'), ('{', '}'), ('"', '"'), ('\'', '\'')] {
        if !value.contains(close) {
            return (format!("{open}{value}{close}"), true);
        }
    }
    (value.to_string(), false)
}

/// Emitted source `phases=`: the stashed token when the source carried
/// one, otherwise the terminal map entries outside the bus's grounded
/// set. The engine counts conductors, not energized phases, so a phase
/// at v_magnitude 0 keeps its place on the dot list; the emission site
/// warns about the disagreement.
fn source_phases(net: &DistNetwork, vs: &crate::model::VoltageSource) -> usize {
    if let Some(p) = extras_usize(&vs.extras, "phases") {
        return p.max(1);
    }
    let energized = vs.v_magnitude.iter().filter(|&&v| v > 0.0).count();
    if energized > 0
        && vs.v_magnitude.len() == vs.terminal_map.len()
        && energized + 1 == vs.v_magnitude.len()
        && vs.v_magnitude.last().is_some_and(|&v| v == 0.0)
    {
        return energized;
    }
    let grounded = net
        .buses
        .iter()
        .find(|b| b.id.eq_ignore_ascii_case(&vs.bus))
        .map(|b| b.grounded.as_slice())
        .unwrap_or_default();
    vs.terminal_map
        .iter()
        .filter(|t| !grounded.contains(t))
        .count()
        .max(1)
}

/// First row (self, mutual) of a series matrix extra, without consuming it.
fn seq_parts(extras: &Extras, key: &str) -> Option<(f64, f64)> {
    let row = extras.get(key)?.as_array()?.first()?.as_array()?;
    let self_v = row.first()?.as_f64()?;
    let mutual = row
        .get(1)
        .and_then(serde_json::Value::as_f64)
        .unwrap_or(0.0);
    Some((self_v, mutual))
}

impl DssWriter {
    fn warn(&mut self, msg: impl Into<String>) {
        self.warnings.push(msg.into());
    }

    /// The engine's bus fill rule gives every conductor the dot list does
    /// not cover a default — nodes 1..=phases for the phase conductors,
    /// ground for the rest — so a map shorter than the class's conductor
    /// count comes back from a reparse one grounded neutral longer. The
    /// first write of such a model is not a fixed point; the second is.
    fn warn_short_map(&mut self, class: &str, name: &str, map_len: usize, nconds: usize) {
        if map_len < nconds {
            self.warn(format!(
                "{class} {name}: terminal map lists {map_len} of {nconds} conductors; \
                 dss materializes a grounded neutral terminal and the reparsed model \
                 gains one"
            ));
        }
    }

    /// A numeric source extra. A present token that does not parse warns;
    /// the derived value substitutes and the extra is consumed either way.
    fn source_extra_f64(&mut self, vs: &crate::model::VoltageSource, key: &str) -> Option<f64> {
        let v = vs.extras.get(key)?;
        let parsed = v
            .as_f64()
            .or_else(|| v.as_str().and_then(|s| s.parse().ok()));
        if parsed.is_none() {
            self.warn(format!(
                "vsource {}: {key} extra `{v}` does not parse as a number; \
                 using the derived value",
                vs.name
            ));
        }
        parsed
    }

    fn line_out(&mut self, s: &str) {
        self.out.push_str(s);
        self.out.push('\n');
    }

    fn check_name(&mut self, class: &str, name: &str) {
        if name_breaks_dss(name, false) {
            self.warn(format!(
                "{class} `{name}`: name contains characters dss cannot represent; \
                 output will not reparse identically"
            ));
        }
    }

    /// `bus.1.2.0` syntax: terminals in the bus's perfectly grounded set
    /// emit as node 0, the inverse of the reader's neutral naming. dss
    /// nodes are positional integers, so a non numeric terminal name emits
    /// as its 1 based position on the bus (the element map position when
    /// the bus does not list it), reported, keeping the conductor structure
    /// intact across the trip.
    fn bus_ref(&mut self, bus: &str, map: &[String]) -> String {
        let key = bus.to_ascii_lowercase();
        if name_breaks_dss(bus, true) {
            self.warn(format!(
                "bus `{bus}`: id contains characters dss cannot represent; \
                 output will not reparse identically"
            ));
        }
        let grounded = self.grounded.get(&key).cloned();
        let terminals = self.terminals.get(&key).cloned().unwrap_or_default();
        let nodes: Vec<String> = map
            .iter()
            .enumerate()
            .map(|(i, t)| {
                if grounded.as_ref().is_some_and(|g| g.contains(t)) {
                    "0".to_string()
                } else if t.parse::<u32>().is_ok() {
                    t.clone()
                } else {
                    let pos = terminals.iter().position(|x| x == t).unwrap_or(i) + 1;
                    self.warn(format!(
                        "bus {bus}: terminal `{t}` is not a dss node number; \
                         emitted as node {pos}, its position on the bus"
                    ));
                    pos.to_string()
                }
            })
            .collect();
        if nodes.is_empty() {
            bus.to_string()
        } else {
            format!("{bus}.{}", nodes.join("."))
        }
    }

    /// Extras whose keys are dss properties of `class` emit as written;
    /// the rest are reported per key.
    fn extras_tail(&mut self, class: &str, name: &str, extras: &Extras) -> String {
        let table = prop::class_by_name(class);
        let mut tail = String::new();
        for (key, value) in extras {
            if matches!(key.as_str(), "bmopf_subtype") || key.starts_with("pmd_") {
                continue; // converter bookkeeping
            }
            let known = table.is_some_and(|t| t.props.contains(&key.as_str()));
            let text = value
                .as_str()
                .map(ToString::to_string)
                .or_else(|| value.as_f64().map(num))
                .or_else(|| value.as_i64().map(|v| v.to_string()));
            match (known, text) {
                (true, Some(text)) => {
                    let (out, representable) = dss_value_out(&text);
                    if !representable {
                        self.warn(format!(
                            "{class} {name}: extra `{key}` value `{text}` contains every \
                             dss quote closer and splits when scanned bare; emitted as \
                             written and a reparse will not see the same value"
                        ));
                    }
                    let _ = write!(tail, " {key}={out}");
                }
                _ => self.warn(format!(
                    "{class} {name}: extra `{key}` is not a dss property; dropped from the output"
                )),
            }
        }
        tail
    }

    /// Lower triangle matrix text. Rows shorter than the triangle pad
    /// with 0 instead of panicking, and the padding is reported.
    fn matrix_arg(&mut self, m: &Mat, what: &str) -> String {
        let mut short = false;
        let rows: Vec<String> = m
            .iter()
            .enumerate()
            .map(|(i, row)| {
                let take = row.len().min(i + 1);
                let mut vals: Vec<String> = row[..take].iter().map(|v| num(*v)).collect();
                if take < i + 1 {
                    short = true;
                    vals.resize(i + 1, "0".to_string());
                }
                vals.join(" ")
            })
            .collect();
        if short {
            self.warn(format!(
                "{what}: matrix rows are shorter than the lower triangle; \
                 missing entries emitted as 0"
            ));
        }
        format!("({})", rows.join(" | "))
    }

    /// Consumes an rs/xs extras pair only when both first rows parse; a
    /// half present or unusable pair stays in extras and is reported.
    fn take_seq_pair(
        &mut self,
        extras: &mut Extras,
        r_key: &str,
        x_key: &str,
        what: &str,
    ) -> Option<((f64, f64), (f64, f64))> {
        let r = seq_parts(extras, r_key);
        let x = seq_parts(extras, x_key);
        if let (Some(r), Some(x)) = (r, x) {
            extras.remove(r_key);
            extras.remove(x_key);
            return Some((r, x));
        }
        if extras.contains_key(r_key) || extras.contains_key(x_key) {
            let state = |key: &str, parsed: bool| {
                if !extras.contains_key(key) {
                    format!("`{key}` is missing")
                } else if parsed {
                    format!("`{key}` is usable")
                } else {
                    format!("`{key}` is not a numeric matrix")
                }
            };
            self.warn(format!(
                "{what}: series impedance extras unusable ({}, {}); left in extras",
                state(r_key, r.is_some()),
                state(x_key, x.is_some()),
            ));
        }
        None
    }

    /// Emitted `phases=`: the reader's stash when present, otherwise
    /// inferred from the terminal map shape. A delta map with 3 conductors
    /// is 2 or 3 phase; without the stash the 3 phase reading wins, loudly.
    fn element_phases(
        &mut self,
        extras: &Extras,
        terminal_map: &[String],
        configuration: Configuration,
        class: &str,
        name: &str,
    ) -> usize {
        if let Some(p) = extras_usize(extras, "phases") {
            return p.max(1);
        }
        match configuration {
            Configuration::Delta => match terminal_map.len() {
                2 => 1,
                3 => {
                    self.warn(format!(
                        "{class} {name}: a delta terminal map with 3 conductors is 2 or 3 \
                         phase and no phases record disambiguates; emitted phases=3"
                    ));
                    3
                }
                n => {
                    self.warn(format!(
                        "{class} {name}: a delta terminal map with {n} conductors has no \
                         dss phases mapping; emitted phases={}",
                        n.max(1)
                    ));
                    n.max(1)
                }
            },
            Configuration::Wye => terminal_map.len().saturating_sub(1).max(1),
            _ => 1,
        }
    }

    fn network(&mut self, net: &DistNetwork) {
        self.line_out("Clear");
        self.line_out(&format!(
            "Set DefaultBaseFrequency={}",
            num(net.base_frequency)
        ));
        self.out.push('\n');

        self.sources(net);
        self.linecodes(net);
        self.lines(net);
        self.switches(net);
        self.transformers(net);
        self.loads(net);
        self.shunts(net);
        self.generators(net);

        for u in &net.untyped {
            self.warn(format!(
                "{} {}: untyped object is not regenerated in canonical dss output",
                u.class, u.name
            ));
        }
        for b in &net.buses {
            self.bus_extras(b);
        }

        self.out.push('\n');
        // Source options re-emit in stored order, except the keys this
        // writer derives itself (the DefaultBaseFrequency header, the
        // VoltageBases tail). Commands do not re-emit: their position in
        // the script matters and the canonical element order does not
        // preserve it, so each drop is reported instead.
        for (key, value) in &net.options {
            if key.is_empty() {
                self.warn(format!(
                    "option `{value}` has no name; not regenerated in canonical dss output"
                ));
                continue;
            }
            // The engine resolves Set names by first match in option table
            // order (Command.cpp Getcommand → HashList FindAbbrev). Every
            // prefix of "voltagebases" binds Voltagebases (it precedes the
            // other v options), but prefixes of "defaultbasefrequency"
            // shorter than "defaultb" bind DefaultDaily, so the frequency
            // skip is bounded at the engine's unique resolution point.
            // Calcvoltagebases is a command, never a Set option, so it does
            // not belong here.
            let key_lc = key.to_ascii_lowercase();
            if "voltagebases".starts_with(&key_lc)
                || (key_lc.len() >= "defaultb".len() && "defaultbasefrequency".starts_with(&key_lc))
            {
                continue;
            }
            let (text, representable) = dss_value_out(value);
            if !representable {
                self.warn(format!(
                    "option `{key}`: value `{value}` contains every dss quote closer \
                     and splits when scanned bare; emitted as written and a reparse \
                     will not see the same value"
                ));
            }
            self.line_out(&format!("Set {key}={text}"));
        }
        for (verb, args) in &net.commands {
            if verb.eq_ignore_ascii_case("calcvoltagebases") || verb.eq_ignore_ascii_case("solve") {
                continue; // the tail emits these
            }
            let shown = if args.is_empty() {
                verb.clone()
            } else {
                format!("{verb} {args}")
            };
            self.warn(format!(
                "command `{shown}` is not regenerated in canonical dss output"
            ));
        }
        let mut bases: Vec<f64> = self
            .kv_estimate
            .values()
            .map(|v| v * 3f64.sqrt() / 1e3)
            .collect();
        bases.sort_by(f64::total_cmp);
        bases.dedup_by(|a, b| (*a - *b).abs() < 1e-9);
        if !bases.is_empty() {
            let list: Vec<String> = bases.iter().map(|v| num(*v)).collect();
            self.line_out(&format!("Set VoltageBases=[{}]", list.join(", ")));
            self.line_out("Calcvoltagebases");
        }
        self.line_out("Solve");
    }

    fn bus_extras(&mut self, b: &DistBus) {
        for key in b.extras.keys() {
            if key == "x" || key == "y" {
                continue; // coordinates have no command in canonical output yet
            }
            self.warnings.push(format!(
                "bus {}: extra `{key}` is not regenerated in canonical dss output",
                b.id
            ));
        }
        for (field, present) in [
            ("v_min", b.v_min.is_some()),
            ("v_max", b.v_max.is_some()),
            ("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()),
            ("vsym_min", b.vsym_min.is_some()),
            ("vsym_max", b.vsym_max.is_some()),
        ] {
            if present {
                self.warnings.push(format!(
                    "bus {}: `{field}` voltage bounds have no dss expression; dropped",
                    b.id
                ));
            }
        }
    }

    fn sources(&mut self, net: &DistNetwork) {
        let mut order: Vec<usize> = (0..net.sources.len()).collect();
        if let Some(source_idx) = net
            .sources
            .iter()
            .position(|vs| vs.name.eq_ignore_ascii_case("source"))
        {
            order.swap(0, source_idx);
        }
        for (i, source_idx) in order.into_iter().enumerate() {
            let vs = &net.sources[source_idx];
            let phases = source_phases(net, vs);
            let energized = vs.v_magnitude.iter().filter(|&&v| v > 0.0).count();
            if energized > 0 && energized != phases {
                self.warn(format!(
                    "vsource {}: emitted phases={phases} but {energized} v_magnitude \
                     entries are positive; a reparse energizes all {phases}",
                    vs.name
                ));
            }
            self.warn_short_map("vsource", &vs.name, vs.terminal_map.len(), phases + 1);
            let basekv = self
                .source_extra_f64(vs, "basekv")
                .unwrap_or_else(|| source_basekv(vs, phases));
            let pu = self.source_extra_f64(vs, "pu").unwrap_or(1.0);
            let angle = self
                .source_extra_f64(vs, "angle")
                .unwrap_or_else(|| vs.v_angle.first().copied().unwrap_or(0.0).to_degrees());
            let head = if i == 0 {
                let name = net.name.clone().unwrap_or_else(|| "converted".into());
                self.check_name("circuit", &name);
                format!("New Circuit.{name}")
            } else {
                self.check_name("vsource", &vs.name);
                format!("New Vsource.{}", vs.name)
            };
            let mut s = format!(
                "{head} basekv={} pu={} angle={} phases={phases} bus1={}",
                num(basekv),
                num(pu),
                num(angle),
                self.bus_ref(&vs.bus, &vs.terminal_map),
            );
            let mut extras = vs.extras.clone();
            extras.remove("basekv");
            extras.remove("pu");
            extras.remove("angle");
            extras.remove("phases"); // the head already prints phases=
            // A source that came through the ENGINEERING model carries its
            // Thevenin impedance as rs/xs matrices; sequence values
            // reconstruct exactly (z1 = self - mutual, z0 = self + 2 mutual).
            let what = format!("vsource {}", vs.name);
            if let Some(((rs, rm), (xs, xm))) = self.take_seq_pair(&mut extras, "rs", "xs", &what) {
                // Lowercase keys in sorted order: a reparse keeps these in
                // extras and the next write emits them from there verbatim.
                let _ = write!(
                    s,
                    " z0=({}, {}) z1=({}, {})",
                    num(rs + 2.0 * rm),
                    num(xs + 2.0 * xm),
                    num(rs - rm),
                    num(xs - xm)
                );
            }
            s.push_str(&self.extras_tail("vsource", &vs.name, &extras));
            self.line_out(&s);
        }
        self.out.push('\n');
    }

    fn linecodes(&mut self, net: &DistNetwork) {
        let omega_nf = std::f64::consts::TAU * net.base_frequency * 1e-9;
        for c in &net.linecodes {
            self.check_name("linecode", &c.name);
            let n = c.n_conductors;
            let what = format!("linecode {}", c.name);
            let mut s = format!("New Linecode.{} nphases={n} units=m", c.name);
            let rm = self.matrix_arg(&c.r_series, &what);
            let _ = write!(s, " rmatrix={rm}");
            let xm = self.matrix_arg(&c.x_series, &what);
            let _ = write!(s, " xmatrix={xm}");
            // cmatrix in nF per meter: each half is omega C / 2, so
            // C_nF = 2 b / (omega 1e-9).
            let c_nf: Mat = c
                .b_from
                .iter()
                .map(|row| row.iter().map(|b| 2.0 * b / omega_nf).collect())
                .collect();
            let cm = self.matrix_arg(&c_nf, &what);
            let _ = write!(s, " cmatrix={cm}");
            match c.i_max.as_deref() {
                Some([amps, ..]) => {
                    let _ = write!(s, " emergamps={}", num(*amps));
                }
                Some([]) => self.warn(format!(
                    "linecode {}: i_max is empty; emergamps not emitted",
                    c.name
                )),
                None => {}
            }
            if !c.g_from.iter().flatten().all(|&g| g == 0.0) {
                self.warn(format!(
                    "linecode {}: shunt conductance has no dss linecode field; dropped",
                    c.name
                ));
            }
            let mut extras = c.extras.clone();
            extras.remove("units"); // canonical output is in meters
            s.push_str(&self.extras_tail("linecode", &c.name, &extras));
            self.line_out(&s);
        }
        self.out.push('\n');
    }

    fn lines(&mut self, net: &DistNetwork) {
        for l in &net.lines {
            self.check_name("line", &l.name);
            let phases = l.terminal_map_from.len();
            let mut s = format!(
                "New Line.{} bus1={} bus2={} phases={phases} linecode={} length={} units=m",
                l.name,
                self.bus_ref(&l.bus_from, &l.terminal_map_from),
                self.bus_ref(&l.bus_to, &l.terminal_map_to),
                l.linecode,
                num(l.length),
            );
            let mut extras = l.extras.clone();
            extras.remove("units"); // canonical output is in meters
            s.push_str(&self.extras_tail("line", &l.name, &extras));
            self.line_out(&s);
        }
        self.out.push('\n');
    }

    fn switches(&mut self, net: &DistNetwork) {
        for sw in &net.switches {
            self.check_name("line", &sw.name);
            let phases = sw.terminal_map_from.len();
            let mut s = format!(
                "New Line.{} bus1={} bus2={} phases={phases} switch=y",
                sw.name,
                self.bus_ref(&sw.bus_from, &sw.terminal_map_from),
                self.bus_ref(&sw.bus_to, &sw.terminal_map_to),
            );
            match sw.i_max.as_deref() {
                Some([amps, ..]) => {
                    let _ = write!(s, " emergamps={}", num(*amps));
                }
                Some([]) => self.warn(format!(
                    "line {}: i_max is empty; emergamps not emitted",
                    sw.name
                )),
                None => {}
            }
            // A switch that came through the ENGINEERING model carries its
            // total series matrices; sequence overrides reproduce them over
            // the forced 0.001 length (the engine's switch dummy values
            // would otherwise apply).
            let mut extras = sw.extras.clone();
            let what = format!("line {}", sw.name);
            if let Some(((rs, rm), (xs, xm))) =
                self.take_seq_pair(&mut extras, "pmd_rs", "pmd_xs", &what)
            {
                let _ = write!(
                    s,
                    " c0=0 c1=0 r0={} r1={} x0={} x1={}",
                    num((rs + 2.0 * rm) / 0.001),
                    num((rs - rm) / 0.001),
                    num((xs + 2.0 * xm) / 0.001),
                    num((xs - xm) / 0.001)
                );
            }
            s.push_str(&self.extras_tail("line", &sw.name, &extras));
            self.line_out(&s);
            self.line_out(&format!(
                "New SwtControl.{}_state SwitchedObj=Line.{} Action={}",
                sw.name,
                sw.name,
                if sw.open { "open" } else { "close" },
            ));
        }
        self.out.push('\n');
    }

    fn transformers(&mut self, net: &DistNetwork) {
        for t in &net.transformers {
            self.check_name("transformer", &t.name);
            let nw = t.windings.len();
            let buses: Vec<String> = t
                .windings
                .iter()
                .map(|w| self.bus_ref(&w.bus, &w.terminal_map))
                .collect();
            let conns: Vec<&str> = t
                .windings
                .iter()
                .map(|w| match w.conn {
                    WindingConn::Wye => "wye",
                    WindingConn::Delta => "delta",
                })
                .collect();
            let kvs: Vec<String> = t.windings.iter().map(|w| num(w.v_ref / 1e3)).collect();
            let kvas: Vec<String> = t.windings.iter().map(|w| num(w.s_rating / 1e3)).collect();
            let rs: Vec<String> = t.windings.iter().map(|w| num(w.r_pct)).collect();
            let taps: Vec<String> = t.windings.iter().map(|w| num(w.tap)).collect();
            let mut s = format!(
                "New Transformer.{} phases={} windings={nw} buses=({}) conns=({}) kvs=({}) kvas=({}) %Rs=({}) taps=({})",
                t.name,
                t.phases,
                buses.join(", "),
                conns.join(", "),
                kvs.join(", "),
                kvas.join(", "),
                rs.join(", "),
                taps.join(", "),
            );
            if let Some(xhl) = t.xsc_pct.first() {
                let _ = write!(s, " xhl={}", num(*xhl));
                if t.xsc_pct.len() >= 3 {
                    let _ = write!(s, " xht={} xlt={}", num(t.xsc_pct[1]), num(t.xsc_pct[2]));
                }
            } else {
                self.warn(format!(
                    "transformer {}: xsc_pct is empty; emitted xhl=0",
                    t.name
                ));
                s.push_str(" xhl=0");
            }
            s.push_str(&self.extras_tail("transformer", &t.name, &t.extras));
            self.line_out(&s);
        }
        self.out.push('\n');
    }

    fn loads(&mut self, net: &DistNetwork) {
        for l in &net.loads {
            self.check_name("load", &l.name);
            let phases =
                self.element_phases(&l.extras, &l.terminal_map, l.configuration, "load", &l.name);
            let conn = self.element_conn(&l.extras, l.configuration, &l.bus, &l.terminal_map);
            // The reader's nconds: a 3 phase delta has no neutral conductor,
            // every other connection carries phases + 1.
            let nconds = if conn == "delta" && phases == 3 {
                phases
            } else {
                phases + 1
            };
            self.warn_short_map("load", &l.name, l.terminal_map.len(), nconds);
            let kw: f64 = l.p_nom.iter().sum::<f64>() / 1e3;
            let kvar: f64 = l.q_nom.iter().sum::<f64>() / 1e3;
            let typed_kv = self.load_nominal_kv(&l.voltage_model, phases, l.configuration, &l.name);
            let kv = self.element_kv(
                &l.extras,
                ElementKv {
                    bus: &l.bus,
                    phases,
                    configuration: l.configuration,
                    name: &l.name,
                    class: "load",
                    typed_kv,
                },
            );
            let mut extras = l.extras.clone();
            extras.remove("kv");
            extras.remove("phases");
            extras.remove("conn");
            let retained_model = extras.remove("model");
            let retained_zipv = extras.remove("zipv");
            // q that came from a power factor goes back as pf=, so the
            // engine recomputes its own kvar bit for bit.
            let reactive = match extras.remove("pf").and_then(|v| v.as_f64()) {
                Some(pf) => format!("pf={}", num(pf)),
                None => format!("kvar={}", num(kvar)),
            };
            let mut s = format!(
                "New Load.{} bus1={} phases={phases} conn={conn} kv={} kw={} {reactive}",
                l.name,
                self.bus_ref(&l.bus, &l.terminal_map),
                num(kv),
                num(kw),
            );
            match &l.voltage_model {
                DistLoadVoltageModel::ConstantPower { .. } => {
                    if let Some(model) = retained_model {
                        extras.insert("model".into(), model);
                    }
                }
                DistLoadVoltageModel::ConstantImpedance { .. } => {
                    s.push_str(" model=2");
                }
                DistLoadVoltageModel::ConstantCurrent { .. } => {
                    s.push_str(" model=5");
                }
                DistLoadVoltageModel::Zip {
                    alpha_z,
                    alpha_i,
                    alpha_p,
                    beta_z,
                    beta_i,
                    beta_p,
                    ..
                } => {
                    s.push_str(" model=8");
                    if let (Some(az), Some(ai), Some(ap), Some(bz), Some(bi), Some(bp)) = (
                        alpha_z.first(),
                        alpha_i.first(),
                        alpha_p.first(),
                        beta_z.first(),
                        beta_i.first(),
                        beta_p.first(),
                    ) {
                        let cutoff = zipv_cutoff(retained_zipv.as_ref()).unwrap_or(0.0);
                        let _ = write!(
                            s,
                            " zipv=({}, {}, {}, {}, {}, {}, {})",
                            num(*az),
                            num(*ai),
                            num(*ap),
                            num(*bz),
                            num(*bi),
                            num(*bp),
                            num(cutoff)
                        );
                    }
                }
                DistLoadVoltageModel::Exponential { .. } => {
                    self.warn(format!(
                        "load {}: exponential voltage model has no OpenDSS load model code; emitted constant power",
                        l.name
                    ));
                }
            }
            s.push_str(&self.extras_tail("load", &l.name, &extras));
            self.line_out(&s);
        }
        self.out.push('\n');
    }

    /// `kv` for a load or capacitor: the recorded value when the source
    /// carried one, otherwise the propagated bus estimate.
    fn element_kv(&mut self, extras: &Extras, ctx: ElementKv<'_>) -> f64 {
        if let Some(v) = extras.get("kv") {
            match v
                .as_f64()
                .or_else(|| v.as_str().and_then(|s| s.parse().ok()))
            {
                Some(kv) => return kv,
                None => self.warn(format!(
                    "{} {}: kv extra `{v}` does not parse as a number; \
                     using the bus voltage estimate",
                    ctx.class, ctx.name
                )),
            }
        }
        if let Some(kv) = ctx.typed_kv {
            return kv;
        }
        if let Some(vln) = self.kv_estimate.get(&ctx.bus.to_ascii_lowercase()).copied() {
            // OpenDSS convention: line to line for 2 and 3 phase, line to
            // neutral for single phase.
            let v = if ctx.phases >= 2 || ctx.configuration == Configuration::Delta {
                vln * 3f64.sqrt()
            } else {
                vln
            };
            v / 1e3
        } else {
            self.warn(format!(
                "{} {}: no kv in the source and no bus voltage estimate; \
                 emitted 12.47",
                ctx.class, ctx.name
            ));
            12.47
        }
    }

    fn load_nominal_kv(
        &mut self,
        model: &DistLoadVoltageModel,
        phases: usize,
        configuration: Configuration,
        name: &str,
    ) -> Option<f64> {
        let v_nom = model.v_nom();
        let v_phase = v_nom
            .first()
            .copied()
            .filter(|v| v.is_finite() && *v > 0.0)?;
        if v_nom
            .iter()
            .any(|v| (*v - v_phase).abs() > 1e-9 * v.abs().max(v_phase.abs()).max(1.0))
        {
            self.warn(format!(
                "load {name}: nonuniform nominal voltage array has no OpenDSS scalar kv; emitted the first value"
            ));
        }
        let v = if phases >= 2 && configuration == Configuration::Wye {
            v_phase * 3f64.sqrt()
        } else {
            v_phase
        };
        Some(v / 1e3)
    }

    /// Emitted `conn=`: delta for typed delta, for a stashed DSS delta token,
    /// and for a single phase two terminal map that does not include a grounded
    /// return conductor.
    fn element_conn(
        &self,
        extras: &Extras,
        configuration: Configuration,
        bus: &str,
        terminal_map: &[String],
    ) -> &'static str {
        let stash_delta = 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")
            });
        let has_grounded_return = self
            .grounded
            .get(&bus.to_ascii_lowercase())
            .is_some_and(|g| terminal_map.iter().any(|t| g.contains(t)));
        match configuration {
            Configuration::Delta => "delta",
            Configuration::SinglePhase
                if stash_delta || (terminal_map.len() == 2 && !has_grounded_return) =>
            {
                "delta"
            }
            _ => "wye",
        }
    }

    fn write_impedance_shunt(&mut self, sh: &crate::model::DistShunt, phases: usize) {
        self.check_name("reactor", &sh.name);
        let Some((conductance, susceptance)) = first_diag_admittance(&sh.g, &sh.b, phases) else {
            self.warn(format!(
                "shunt {}: conductance matrix has no diagonal admittance; dropped from the output",
                sh.name
            ));
            return;
        };
        if has_off_diagonal(&sh.g) || has_off_diagonal(&sh.b) {
            self.warn(format!(
                "shunt {}: off diagonal admittance has no scalar reactor expression; \
                 only the first diagonal admittance is regenerated",
                sh.name
            ));
        }
        if !uniform_diag_admittance(&sh.g, &sh.b, phases, conductance, susceptance) {
            self.warn(format!(
                "shunt {}: diagonal admittances differ; only the first diagonal \
                 admittance is regenerated",
                sh.name
            ));
        }
        let denom = conductance * conductance + susceptance * susceptance;
        if !denom.is_finite() || denom <= 0.0 {
            self.warn(format!(
                "shunt {}: invalid grounding admittance; dropped from the output",
                sh.name
            ));
            return;
        }
        let resistance = conductance / denom;
        let reactance = -susceptance / denom;
        let mut extras = sh.extras.clone();
        strip_shunt_extras(&mut extras);
        let ground = vec!["0".to_string(); phases.max(1)];
        let mut line = format!(
            "New Reactor.{} bus1={} bus2={} phases={} r={} x={}",
            sh.name,
            self.bus_ref(&sh.bus, &sh.terminal_map),
            self.bus_ref(&sh.bus, &ground),
            phases.max(1),
            num(resistance),
            num(reactance),
        );
        line.push_str(&self.extras_tail("reactor", &sh.name, &extras));
        self.line_out(&line);
    }

    fn shunt_phases(
        &mut self,
        sh: &crate::model::DistShunt,
        conn_delta: bool,
        inferred_phases: usize,
    ) -> usize {
        if let Some(p) = extras_usize(&sh.extras, "phases") {
            p.max(1)
        } else if conn_delta {
            self.element_phases(
                &sh.extras,
                &sh.terminal_map,
                Configuration::Delta,
                "shunt",
                &sh.name,
            )
        } else {
            inferred_phases
        }
    }

    fn write_kvar_shunt(&mut self, sh: &crate::model::DistShunt, phases: usize, conn_delta: bool) {
        // Scan every diagonal conductor, not just the first `phases` of them: a
        // delta bank's conductor count exceeds its stashed `phases`, and a
        // sign-flipped diagonal past that bound must still set the class.
        let (b_max, b_min) = (0..sh.b.len())
            .map(|idx| diag_at(&sh.b, idx))
            .fold((0.0_f64, 0.0_f64), |(mx, mn), v| (mx.max(v), mn.min(v)));
        let (class, b_phase) = if b_max > 0.0 {
            ("capacitor", b_max)
        } else if b_min < 0.0 {
            ("reactor", b_min)
        } else {
            self.warn(format!(
                "shunt {}: no nonzero susceptance; dropped from the output",
                sh.name
            ));
            return;
        };
        if b_max > 0.0 && b_min < 0.0 {
            self.warn(format!(
                "shunt {}: diagonal mixes capacitive and inductive phases; only the \
                 {class} phases are regenerated",
                sh.name
            ));
        }
        self.check_name(class, &sh.name);
        let off_diag = has_off_diagonal(&sh.b);
        if off_diag && !conn_delta {
            self.warn(format!(
                "shunt {}: off diagonal susceptance has no {class} expression; \
                 only the diagonal is regenerated",
                sh.name
            ));
        }
        let edges = if conn_delta {
            delta_edges(sh.terminal_map.len(), phases)
        } else {
            Vec::new()
        };
        if conn_delta && edges.is_empty() {
            self.warn(format!(
                "shunt {}: delta terminal map has no branch expression; dropped from the output",
                sh.name
            ));
            return;
        }
        if conn_delta && delta_branch_susceptance(&sh.b, &edges, sh.terminal_map.len()).is_none() {
            self.warn(format!(
                "shunt {}: delta susceptance matrix has no scalar {class} expression; \
                 only the average branch susceptance is regenerated",
                sh.name
            ));
        }
        let configuration = if conn_delta {
            Configuration::Delta
        } else {
            Configuration::Wye
        };
        let kv = self.element_kv(
            &sh.extras,
            ElementKv {
                bus: &sh.bus,
                phases,
                configuration,
                name: &sh.name,
                class,
                typed_kv: None,
            },
        );
        let kvar = extras_f64(&sh.extras, "kvar")
            .unwrap_or_else(|| shunt_kvar(sh, phases, conn_delta, &edges, b_phase, kv));
        let mut extras = sh.extras.clone();
        strip_shunt_extras(&mut extras);
        let conn = if conn_delta { "delta" } else { "wye" };
        let decl = if class == "reactor" {
            "Reactor"
        } else {
            "Capacitor"
        };
        let mut line = format!(
            "New {decl}.{} bus1={} phases={phases} conn={conn} kv={} kvar={}",
            sh.name,
            self.bus_ref(&sh.bus, &sh.terminal_map),
            num(kv),
            num(kvar),
        );
        line.push_str(&self.extras_tail(class, &sh.name, &extras));
        self.line_out(&line);
    }

    fn shunts(&mut self, net: &DistNetwork) {
        for sh in &net.shunts {
            let stashed_delta = shunt_stashed_delta(sh);
            let inferred_phases =
                extras_usize(&sh.extras, "phases").unwrap_or_else(|| sh.terminal_map.len().max(1));
            let conn_delta = stashed_delta
                || looks_like_delta_shunt(&sh.b, sh.terminal_map.len(), inferred_phases);
            let phases = self.shunt_phases(sh, conn_delta, inferred_phases);
            if has_nonzero(&sh.g) {
                self.write_impedance_shunt(sh, phases);
            } else {
                self.write_kvar_shunt(sh, phases, conn_delta);
            }
        }
        self.out.push('\n');
    }

    fn generators(&mut self, net: &DistNetwork) {
        for g in &net.generators {
            self.check_name("generator", &g.name);
            let phases = self.element_phases(
                &g.extras,
                &g.terminal_map,
                g.configuration,
                "generator",
                &g.name,
            );
            let conn = self.element_conn(&g.extras, g.configuration, &g.bus, &g.terminal_map);
            let nconds = if conn == "delta" && phases == 3 {
                phases
            } else {
                phases + 1
            };
            self.warn_short_map("generator", &g.name, g.terminal_map.len(), nconds);
            let kw: f64 = g.p_nom.iter().sum::<f64>() / 1e3;
            let kvar: f64 = g.q_nom.iter().sum::<f64>() / 1e3;
            let kv = self.element_kv(
                &g.extras,
                ElementKv {
                    bus: &g.bus,
                    phases,
                    configuration: g.configuration,
                    name: &g.name,
                    class: "generator",
                    typed_kv: None,
                },
            );
            let mut s = format!(
                "New Generator.{} bus1={} phases={phases} conn={conn} kv={} kw={} kvar={}",
                g.name,
                self.bus_ref(&g.bus, &g.terminal_map),
                num(kv),
                num(kw),
                num(kvar),
            );
            if let Some(q) = &g.q_max {
                let _ = write!(s, " maxkvar={}", num(q.iter().sum::<f64>() / 1e3));
            }
            if let Some(q) = &g.q_min {
                let _ = write!(s, " minkvar={}", num(q.iter().sum::<f64>() / 1e3));
            }
            if g.cost.is_some() {
                self.warn(format!(
                    "generator {}: generation cost has no dss field; dropped",
                    g.name
                ));
            }
            let mut extras = g.extras.clone();
            extras.remove("kv");
            extras.remove("phases");
            extras.remove("conn");
            s.push_str(&self.extras_tail("generator", &g.name, &extras));
            self.line_out(&s);
        }
    }
}

/// Drop the shunt keys the writer regenerates from the typed model so a stale
/// copy is not re-emitted in the extras tail.
fn strip_shunt_extras(extras: &mut Extras) {
    for key in ["kv", "kvar", "phases", "conn"] {
        extras.remove(key);
    }
}

fn has_nonzero(m: &Mat) -> bool {
    m.iter().flatten().any(|&v| v != 0.0)
}

fn has_off_diagonal(m: &Mat) -> bool {
    m.iter()
        .enumerate()
        .any(|(i, row)| row.iter().enumerate().any(|(j, &v)| i != j && v != 0.0))
}

fn diag_at(m: &Mat, i: usize) -> f64 {
    m.get(i).and_then(|row| row.get(i)).copied().unwrap_or(0.0)
}

fn matrix_scale(m: &Mat) -> f64 {
    m.iter().flatten().fold(0.0_f64, |acc, &v| acc.max(v.abs()))
}

fn close(a: f64, b: f64, scale: f64) -> bool {
    (a - b).abs() <= 1e-12_f64.max(scale * 1e-9)
}

fn first_diag_admittance(g: &Mat, b: &Mat, phases: usize) -> Option<(f64, f64)> {
    (0..phases.max(1)).find_map(|i| {
        let gi = diag_at(g, i);
        let bi = diag_at(b, i);
        (gi != 0.0 || bi != 0.0).then_some((gi, bi))
    })
}

fn uniform_diag_admittance(g: &Mat, b: &Mat, phases: usize, g0: f64, b0: f64) -> bool {
    let scale = matrix_scale(g)
        .max(matrix_scale(b))
        .max(g0.abs())
        .max(b0.abs());
    (0..phases.max(1)).all(|i| close(diag_at(g, i), g0, scale) && close(diag_at(b, i), b0, scale))
}

fn shunt_stashed_delta(sh: &crate::model::DistShunt) -> bool {
    sh.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 mat_at(m: &Mat, i: usize, j: usize) -> f64 {
    m.get(i).and_then(|row| row.get(j)).copied().unwrap_or(0.0)
}

fn looks_like_delta_shunt(b: &Mat, terminals: usize, phases: usize) -> bool {
    if terminals < 2 || !has_off_diagonal(b) {
        return false;
    }
    let edges = delta_edges(terminals, phases);
    delta_branch_susceptance(b, &edges, terminals).is_some()
}

fn delta_branch_abs(b: &Mat, edges: &[(usize, usize)]) -> Option<f64> {
    if edges.is_empty() {
        return None;
    }
    // Average over every edge (a missing entry contributes 0), so the divisor
    // matches the `edges.len()` that `shunt_kvar` multiplies back in; counting
    // only present entries would over-scale the regenerated kvar on a ragged
    // matrix.
    let total: f64 = edges
        .iter()
        .map(|&(i, j)| {
            b.get(i)
                .and_then(|row| row.get(j))
                .copied()
                .unwrap_or(0.0)
                .abs()
        })
        .sum();
    Some(total / edges.len() as f64)
}

fn delta_branch_susceptance(b: &Mat, edges: &[(usize, usize)], terminals: usize) -> Option<f64> {
    if terminals < 2 || edges.is_empty() {
        return None;
    }
    let scale = matrix_scale(b);
    if scale == 0.0 {
        return None;
    }
    let first = edges[0];
    let branch = -mat_at(b, first.0, first.1);
    if branch == 0.0 {
        return None;
    }
    let scale = scale.max(branch.abs());
    for (i, row) in b.iter().enumerate() {
        for (j, &value) in row.iter().enumerate() {
            if (i >= terminals || j >= terminals) && !close(value, 0.0, scale) {
                return None;
            }
        }
    }
    for i in 0..terminals {
        let incident = edges
            .iter()
            .filter(|&&(from, to)| from == i || to == i)
            .count() as f64;
        for j in 0..terminals {
            let linked = edges
                .iter()
                .any(|&(from, to)| (from == i && to == j) || (from == j && to == i));
            let expected = if i == j {
                incident * branch
            } else if linked {
                -branch
            } else {
                0.0
            };
            if !close(mat_at(b, i, j), expected, scale) {
                return None;
            }
        }
    }
    Some(branch)
}

fn shunt_kvar(
    sh: &crate::model::DistShunt,
    phases: usize,
    conn_delta: bool,
    edges: &[(usize, usize)],
    b_phase: f64,
    kv: f64,
) -> f64 {
    if conn_delta {
        let b_branch = delta_branch_abs(&sh.b, edges).unwrap_or(b_phase.abs());
        b_branch * (kv * 1e3) * (kv * 1e3) * edges.len() as f64 / 1e3
    } else {
        let v_phase = if matches!(phases, 2 | 3) {
            kv * 1e3 / 3f64.sqrt()
        } else {
            kv * 1e3
        };
        b_phase.abs() * v_phase * v_phase * phases as f64 / 1e3
    }
}

#[cfg(test)]
mod tests {
    use super::super::read::parse_dss_str;
    use super::*;
    use crate::model::{
        DistGenerator, DistLine, DistLineCode, DistLoad, DistShunt, DistSwitch, DistTransformer,
        VoltageSource, Winding,
    };

    fn strings(v: &[&str]) -> Vec<String> {
        v.iter().map(ToString::to_string).collect()
    }

    fn bus(id: &str, terminals: &[&str], grounded: &[&str]) -> DistBus {
        DistBus {
            id: id.into(),
            terminals: strings(terminals),
            grounded: strings(grounded),
            ..DistBus::default()
        }
    }

    fn three_phase_source(vln: f64) -> (DistBus, VoltageSource) {
        let third = 2.0 * std::f64::consts::FRAC_PI_3;
        (
            bus("sb", &["1", "2", "3", "4"], &["4"]),
            VoltageSource {
                name: "source".into(),
                bus: "sb".into(),
                terminal_map: strings(&["1", "2", "3", "4"]),
                v_magnitude: vec![vln, vln, vln, 0.0],
                v_angle: vec![0.0, -third, third, 0.0],
                extras: Extras::new(),
            },
        )
    }

    fn load_on(bus: &str, map: &[&str], configuration: Configuration) -> DistLoad {
        let phases = map.len();
        DistLoad {
            name: "ld".into(),
            bus: bus.into(),
            terminal_map: strings(map),
            configuration,
            p_nom: vec![1e3; phases],
            q_nom: vec![0.0; phases],
            voltage_model: DistLoadVoltageModel::ConstantPower { v_nom: Vec::new() },
            extras: Extras::from([("kv".to_string(), serde_json::json!("0.4"))]),
        }
    }

    fn roundtrip(net: &DistNetwork) -> (String, String) {
        let first = write_dss(net);
        let second = write_dss(&parse_dss_str(&first.text));
        (first.text, second.text)
    }

    #[test]
    fn voltage_bases_survive_the_sqrt_round_trip() {
        // basekv = vln*sqrt(3)/1e3 then vln' = basekv*1e3/sqrt(3) is not a
        // float fixed point for this PMD shaped value; the second write must
        // reuse the stashed basekv instead of re-deriving the entry.
        let vln = 9_336.235_056_420_312_f64;
        let basekv = vln * 3f64.sqrt() / 1e3;
        assert!(
            (basekv * 1e3 / 3f64.sqrt()).to_bits() != vln.to_bits(),
            "test value no longer reproduces the drift"
        );
        let (b, vs) = three_phase_source(vln);
        let net = DistNetwork {
            name: Some("t".into()),
            base_frequency: 60.0,
            buses: vec![b],
            sources: vec![vs],
            ..DistNetwork::default()
        };
        let (first, second) = roundtrip(&net);
        assert!(first.contains("Set VoltageBases="), "{first}");
        assert_eq!(first, second);
    }

    #[test]
    fn load_phases_prefer_the_reader_stash() {
        let (b, vs) = three_phase_source(2400.0);
        let mut load = load_on("sb", &["1", "2", "3"], Configuration::Delta);
        load.extras.insert("phases".into(), serde_json::json!("2"));
        let net = DistNetwork {
            base_frequency: 60.0,
            buses: vec![b],
            sources: vec![vs],
            loads: vec![load],
            ..DistNetwork::default()
        };
        let out = write_dss(&net);
        let line = out.text.lines().find(|l| l.contains("Load.ld")).unwrap();
        assert!(line.contains("phases=2 conn=delta"), "{line}");
        // The stash must not double emit through the extras tail.
        assert_eq!(line.matches("phases=").count(), 1, "{line}");
        assert!(!out.warnings.iter().any(|w| w.contains("2 or 3 phase")));
    }

    #[test]
    fn ambiguous_delta_keeps_three_phases_loudly() {
        let (b, vs) = three_phase_source(2400.0);
        let net = DistNetwork {
            base_frequency: 60.0,
            buses: vec![b],
            sources: vec![vs],
            loads: vec![load_on("sb", &["1", "2", "3"], Configuration::Delta)],
            ..DistNetwork::default()
        };
        let out = write_dss(&net);
        let line = out.text.lines().find(|l| l.contains("Load.ld")).unwrap();
        assert!(line.contains("phases=3 conn=delta"), "{line}");
        assert!(
            out.warnings.iter().any(|w| w.contains("2 or 3 phase")),
            "{:?}",
            out.warnings
        );
    }

    #[test]
    fn single_phase_delta_emits_conn_delta() {
        let (b, vs) = three_phase_source(2400.0);
        // Two conductor delta typed as Delta: phases=1 conn=delta.
        let two_wire = load_on("sb", &["1", "2"], Configuration::Delta);
        // The reader types 1 phase delta as SinglePhase; the stashed conn
        // token carries the delta.
        let mut stashed = load_on("sb", &["1", "2"], Configuration::SinglePhase);
        stashed.name = "ld2".into();
        stashed
            .extras
            .insert("conn".into(), serde_json::json!("delta"));
        let net = DistNetwork {
            base_frequency: 60.0,
            buses: vec![b],
            sources: vec![vs],
            loads: vec![two_wire, stashed],
            ..DistNetwork::default()
        };
        let out = write_dss(&net);
        let l1 = out.text.lines().find(|l| l.contains("Load.ld ")).unwrap();
        assert!(l1.contains("phases=1 conn=delta"), "{l1}");
        let l2 = out.text.lines().find(|l| l.contains("Load.ld2 ")).unwrap();
        assert!(l2.contains("phases=1 conn=delta"), "{l2}");
        assert_eq!(l2.matches("conn=").count(), 1, "{l2}");
    }

    #[test]
    fn unrepresentable_names_are_reported() {
        let (b, vs) = three_phase_source(2400.0);
        let mut load = load_on("sb", &["1", "2", "3", "4"], Configuration::Wye);
        load.name = "load 1".into();
        let net = DistNetwork {
            name: Some("my circuit".into()),
            base_frequency: 60.0,
            buses: vec![b, bus("a=b", &["1"], &[])],
            sources: vec![vs],
            loads: vec![load],
            ..DistNetwork::default()
        };
        let out = write_dss(&net);
        let hits = |needle: &str| {
            out.warnings
                .iter()
                .any(|w| w.contains(needle) && w.contains("cannot represent"))
        };
        assert!(hits("load 1"), "{:?}", out.warnings);
        assert!(hits("my circuit"), "{:?}", out.warnings);
        // The bad bus id warns at its bus_ref emission site.
        let mut net2 = net.clone();
        net2.lines.push(DistLine {
            name: "l1".into(),
            bus_from: "sb".into(),
            bus_to: "a=b".into(),
            terminal_map_from: strings(&["1"]),
            terminal_map_to: strings(&["1"]),
            linecode: "lc".into(),
            length: 1.0,
            extras: Extras::new(),
        });
        let out2 = write_dss(&net2);
        assert!(
            out2.warnings
                .iter()
                .any(|w| w.contains("a=b") && w.contains("cannot represent")),
            "{:?}",
            out2.warnings
        );
    }

    #[test]
    fn unparseable_kv_extra_warns_instead_of_silently_substituting() {
        let (b, vs) = three_phase_source(2400.0);
        let mut load = load_on("sb", &["1", "2", "3", "4"], Configuration::Wye);
        load.extras.insert("kv".into(), serde_json::json!("@kv"));
        let net = DistNetwork {
            base_frequency: 60.0,
            buses: vec![b],
            sources: vec![vs],
            loads: vec![load],
            ..DistNetwork::default()
        };
        let out = write_dss(&net);
        assert!(
            out.warnings
                .iter()
                .any(|w| w.contains("@kv") && w.contains("does not parse")),
            "{:?}",
            out.warnings
        );
        // The estimate substitutes: 2400*sqrt(3)/1e3 line to line.
        let line = out.text.lines().find(|l| l.contains("Load.ld")).unwrap();
        assert!(
            line.contains(&format!("kv={}", num(2400.0 * 3f64.sqrt() / 1e3))),
            "{line}"
        );
    }

    #[test]
    fn options_reemit_and_commands_warn() {
        let src = "Clear\n\
                   New Circuit.c1 basekv=12.47 pu=1 angle=0 phases=3 bus1=sb\n\
                   Set mode=snapshot\n\
                   Set controlmode=OFF\n\
                   Disable Line.l1\n\
                   Set VoltageBases=[12.47]\n\
                   Calcvoltagebases\n\
                   Solve\n";
        let out = write_dss(&parse_dss_str(src));
        assert!(out.text.contains("Set mode=snapshot"), "{}", out.text);
        assert!(out.text.contains("Set controlmode=OFF"), "{}", out.text);
        // The writer derives these; the stored options must not double them.
        assert_eq!(out.text.matches("Set VoltageBases").count(), 1);
        assert_eq!(out.text.matches("Calcvoltagebases").count(), 1);
        assert_eq!(out.text.matches("DefaultBaseFrequency").count(), 1);
        assert!(!out.text.to_lowercase().contains("disable"));
        assert!(
            out.warnings
                .iter()
                .any(|w| w.contains("disable Line.l1") && w.contains("not regenerated")),
            "{:?}",
            out.warnings
        );
        // Solve and Calcvoltagebases re-derive; no warning claims they drop.
        assert!(!out.warnings.iter().any(|w| w.contains("`solve`")));
        let again = write_dss(&parse_dss_str(&out.text));
        assert_eq!(out.text, again.text);
    }

    #[test]
    fn non_numeric_terminal_positionalizes() {
        let mut load = load_on("b1", &["a", "n"], Configuration::Wye);
        load.extras.insert("kv".into(), serde_json::json!("0.23"));
        let net = DistNetwork {
            base_frequency: 60.0,
            buses: vec![bus("b1", &["a", "n"], &["n"])],
            loads: vec![load],
            ..DistNetwork::default()
        };
        let (first, second) = roundtrip(&net);
        let line = first.lines().find(|l| l.contains("Load.ld")).unwrap();
        assert!(line.contains("bus1=b1.1.0"), "{line}");
        let out = write_dss(&net);
        assert!(
            out.warnings
                .iter()
                .any(|w| w.contains("`a`") && w.contains("position")),
            "{:?}",
            out.warnings
        );
        assert_eq!(first, second);
    }

    #[test]
    fn half_present_thevenin_pair_stays_and_warns() {
        let (b, mut vs) = three_phase_source(2400.0);
        vs.extras
            .insert("rs".into(), serde_json::json!([[1.0, 0.1], [0.1, 1.0]]));
        let net = DistNetwork {
            base_frequency: 60.0,
            buses: vec![b],
            sources: vec![vs],
            ..DistNetwork::default()
        };
        let out = write_dss(&net);
        assert!(!out.text.contains("z1="), "{}", out.text);
        assert!(
            out.warnings.iter().any(|w| w.contains("`xs` is missing")),
            "{:?}",
            out.warnings
        );
    }

    #[test]
    fn unusable_switch_sequence_extras_warn() {
        let (b, vs) = three_phase_source(2400.0);
        let sw = DistSwitch {
            name: "sw1".into(),
            bus_from: "sb".into(),
            bus_to: "b2".into(),
            terminal_map_from: strings(&["1", "2", "3"]),
            terminal_map_to: strings(&["1", "2", "3"]),
            open: false,
            i_max: Some(Vec::new()),
            extras: Extras::from([("pmd_rs".to_string(), serde_json::json!("oops"))]),
        };
        let net = DistNetwork {
            base_frequency: 60.0,
            buses: vec![b, bus("b2", &["1", "2", "3"], &[])],
            sources: vec![vs],
            switches: vec![sw],
            ..DistNetwork::default()
        };
        let out = write_dss(&net);
        assert!(!out.text.contains("r0="), "{}", out.text);
        assert!(
            out.warnings
                .iter()
                .any(|w| w.contains("pmd_rs") && w.contains("not a numeric matrix")),
            "{:?}",
            out.warnings
        );
        assert!(
            out.warnings.iter().any(|w| w.contains("i_max is empty")),
            "{:?}",
            out.warnings
        );
    }

    #[test]
    fn degenerate_shapes_warn_instead_of_panicking() {
        let (b, vs) = three_phase_source(2400.0);
        let lc = DistLineCode {
            name: "lc1".into(),
            n_conductors: 2,
            r_series: vec![vec![1.0], vec![0.5]], // second row short
            x_series: vec![vec![1.0, 0.0], vec![0.0, 1.0]],
            g_from: vec![vec![0.0; 2]; 2],
            b_from: vec![vec![0.0; 2]; 2],
            g_to: vec![vec![0.0; 2]; 2],
            b_to: vec![vec![0.0; 2]; 2],
            i_max: Some(Vec::new()),
            s_max: None,
            extras: Extras::new(),
        };
        let t = DistTransformer {
            name: "t1".into(),
            windings: vec![
                Winding {
                    bus: "sb".into(),
                    terminal_map: strings(&["1", "2"]),
                    conn: WindingConn::Wye,
                    v_ref: 2400.0,
                    s_rating: 25e3,
                    r_pct: 0.5,
                    tap: 1.0,
                },
                Winding {
                    bus: "b2".into(),
                    terminal_map: strings(&["1", "2"]),
                    conn: WindingConn::Wye,
                    v_ref: 240.0,
                    s_rating: 25e3,
                    r_pct: 0.5,
                    tap: 1.0,
                },
            ],
            xsc_pct: Vec::new(),
            phases: 1,
            extras: Extras::new(),
        };
        let net = DistNetwork {
            base_frequency: 60.0,
            buses: vec![b, bus("b2", &["1", "2"], &[])],
            sources: vec![vs],
            linecodes: vec![lc],
            transformers: vec![t],
            ..DistNetwork::default()
        };
        let out = write_dss(&net); // must not panic
        assert!(out.text.contains("rmatrix=(1 | 0.5 0)"), "{}", out.text);
        assert!(out.text.contains("xhl=0"), "{}", out.text);
        let has = |needle: &str| out.warnings.iter().any(|w| w.contains(needle));
        assert!(has("shorter than the lower triangle"), "{:?}", out.warnings);
        assert!(has("xsc_pct is empty"), "{:?}", out.warnings);
        assert!(has("i_max is empty"), "{:?}", out.warnings);
    }

    #[test]
    fn two_phase_capacitor_kvar_uses_line_to_line_kv() {
        // The reader treats wye capacitor kv as line to line for 2 and 3
        // phase; the kvar fallback must invert with the same convention.
        let (b, vs) = three_phase_source(2400.0);
        let b_phase = 1e-3;
        let sh = DistShunt {
            name: "c1".into(),
            bus: "sb".into(),
            terminal_map: strings(&["1", "2"]),
            g: vec![vec![0.0; 2]; 2],
            b: vec![vec![b_phase, 0.0], vec![0.0, b_phase]],
            extras: Extras::new(),
        };
        let net = DistNetwork {
            base_frequency: 60.0,
            buses: vec![b],
            sources: vec![vs],
            shunts: vec![sh],
            ..DistNetwork::default()
        };
        let out = write_dss(&net);
        let kv = 2400.0 * 3f64.sqrt() / 1e3;
        let v_phase = kv * 1e3 / 3f64.sqrt();
        let expected = b_phase * v_phase * v_phase * 2.0 / 1e3;
        let line = out
            .text
            .lines()
            .find(|l| l.contains("Capacitor.c1"))
            .unwrap();
        assert!(line.contains(&format!("kvar={}", num(expected))), "{line}");
    }

    #[test]
    fn inductive_shunt_regenerates_as_a_reactor() {
        // A negative diagonal susceptance is the grounding-reactor sign; it
        // must emit `New Reactor`, not a capacitor, with the positive kvar
        // rating recovered from |b| v^2.
        let (b, vs) = three_phase_source(2400.0);
        let b_phase = -1e-3;
        let sh = DistShunt {
            name: "rx".into(),
            bus: "sb".into(),
            terminal_map: strings(&["1", "2", "3"]),
            g: vec![vec![0.0; 3]; 3],
            b: vec![
                vec![b_phase, 0.0, 0.0],
                vec![0.0, b_phase, 0.0],
                vec![0.0, 0.0, b_phase],
            ],
            extras: Extras::new(),
        };
        let net = DistNetwork {
            base_frequency: 60.0,
            buses: vec![b],
            sources: vec![vs],
            shunts: vec![sh],
            ..DistNetwork::default()
        };
        let out = write_dss(&net);
        let line = out
            .text
            .lines()
            .find(|l| l.contains("Reactor.rx"))
            .unwrap_or_else(|| panic!("no reactor emitted in:\n{}", out.text));
        assert!(!out.text.contains("Capacitor.rx"), "{}", out.text);
        let kv = 2400.0 * 3f64.sqrt() / 1e3;
        let v_phase = kv * 1e3 / 3f64.sqrt();
        let expected = b_phase.abs() * v_phase * v_phase * 3.0 / 1e3;
        assert!(line.contains(&format!("kvar={}", num(expected))), "{line}");
    }

    #[test]
    fn conductive_shunt_regenerates_as_grounding_reactor() {
        let (_, vs) = three_phase_source(2400.0);
        let b = bus("sb", &["1", "2", "3", "4"], &[]);
        let sh = DistShunt {
            name: "gnd".into(),
            bus: "sb".into(),
            terminal_map: strings(&["4"]),
            g: vec![vec![1.0 / 0.3]],
            b: vec![vec![0.0]],
            extras: Extras::new(),
        };
        let net = DistNetwork {
            base_frequency: 60.0,
            buses: vec![b],
            sources: vec![vs],
            shunts: vec![sh],
            ..DistNetwork::default()
        };
        let out = write_dss(&net);
        let line = out
            .text
            .lines()
            .find(|l| l.contains("Reactor.gnd"))
            .unwrap_or_else(|| panic!("no reactor emitted in:\n{}", out.text));
        assert!(line.contains("bus1=sb.4"), "{line}");
        assert!(line.contains("bus2=sb.0"), "{line}");
        assert!(line.contains("phases=1"), "{line}");
        assert!(line.contains("r=0.3"), "{line}");
        assert!(line.contains("x=0"), "{line}");
        assert!(
            !line.contains("x=-0"),
            "negative zero must canonicalize: {line}"
        );
    }

    #[test]
    fn delta_shunt_regenerates_conn_delta() {
        let (b, vs) = three_phase_source(2400.0);
        let b_branch = 2e-4;
        let bmat = vec![
            vec![2.0 * b_branch, -b_branch, -b_branch],
            vec![-b_branch, 2.0 * b_branch, -b_branch],
            vec![-b_branch, -b_branch, 2.0 * b_branch],
        ];
        let mut extras = Extras::new();
        extras.insert("conn".into(), serde_json::json!("delta"));
        extras.insert("phases".into(), serde_json::json!("3"));
        let sh = DistShunt {
            name: "capd".into(),
            bus: "sb".into(),
            terminal_map: strings(&["1", "2", "3"]),
            g: vec![vec![0.0; 3]; 3],
            b: bmat,
            extras,
        };
        let net = DistNetwork {
            base_frequency: 60.0,
            buses: vec![b],
            sources: vec![vs],
            shunts: vec![sh],
            ..DistNetwork::default()
        };
        let out = write_dss(&net);
        let line = out
            .text
            .lines()
            .find(|l| l.contains("Capacitor.capd"))
            .unwrap_or_else(|| panic!("no capacitor emitted in:\n{}", out.text));
        assert!(line.contains("phases=3 conn=delta"), "{line}");
        assert!(
            !out.warnings.iter().any(|w| w.contains("off diagonal")),
            "{:?}",
            out.warnings
        );
    }

    #[test]
    fn non_scalar_delta_matrix_is_not_inferred_silently() {
        let (b, vs) = three_phase_source(2400.0);
        let bmat = vec![
            vec![0.003, -0.001, -0.002],
            vec![-0.001, 0.003, -0.002],
            vec![-0.002, -0.002, 0.004],
        ];
        let sh = DistShunt {
            name: "capx".into(),
            bus: "sb".into(),
            terminal_map: strings(&["1", "2", "3"]),
            g: vec![vec![0.0; 3]; 3],
            b: bmat,
            extras: Extras::new(),
        };
        let net = DistNetwork {
            base_frequency: 60.0,
            buses: vec![b],
            sources: vec![vs],
            shunts: vec![sh],
            ..DistNetwork::default()
        };
        let out = write_dss(&net);
        let line = out
            .text
            .lines()
            .find(|l| l.contains("Capacitor.capx"))
            .unwrap_or_else(|| panic!("no capacitor emitted in:\n{}", out.text));
        assert!(line.contains("conn=wye"), "{line}");
        assert!(
            out.warnings.iter().any(|w| w.contains("off diagonal")),
            "{:?}",
            out.warnings
        );
    }

    #[test]
    fn stashed_delta_matrix_warns_when_scalar_emission_is_lossy() {
        let (b, vs) = three_phase_source(2400.0);
        let bmat = vec![
            vec![0.003, -0.001, -0.002],
            vec![-0.001, 0.003, -0.002],
            vec![-0.002, -0.002, 0.004],
        ];
        let mut extras = Extras::new();
        extras.insert("conn".into(), serde_json::json!("delta"));
        extras.insert("phases".into(), serde_json::json!("3"));
        let sh = DistShunt {
            name: "capx".into(),
            bus: "sb".into(),
            terminal_map: strings(&["1", "2", "3"]),
            g: vec![vec![0.0; 3]; 3],
            b: bmat,
            extras,
        };
        let net = DistNetwork {
            base_frequency: 60.0,
            buses: vec![b],
            sources: vec![vs],
            shunts: vec![sh],
            ..DistNetwork::default()
        };
        let out = write_dss(&net);
        let line = out
            .text
            .lines()
            .find(|l| l.contains("Capacitor.capx"))
            .unwrap_or_else(|| panic!("no capacitor emitted in:\n{}", out.text));
        assert!(line.contains("conn=delta"), "{line}");
        assert!(
            out.warnings
                .iter()
                .any(|w| w.contains("no scalar capacitor expression")),
            "{:?}",
            out.warnings
        );
    }

    #[test]
    fn option_values_choose_a_wrapper_the_lexer_undoes() {
        let src = "Clear\n\
                   New Circuit.c1 basekv=12.47 pu=1 angle=0 phases=3 bus1=sb\n\
                   Set foo=[a!b]\n\
                   Set bar=[(abc]\n\
                   Set baz=(x ] y)\n\
                   Set qux=[a ) b]\n\
                   Solve\n";
        let net = parse_dss_str(src);
        let first = write_dss(&net);
        for line in [
            "Set foo=(a!b)",
            "Set bar=((abc)",
            "Set baz=(x ] y)",
            "Set qux=[a ) b]",
        ] {
            assert!(
                first.text.contains(line),
                "{line} missing in {}",
                first.text
            );
        }
        assert!(
            !first
                .warnings
                .iter()
                .any(|w| w.contains("emitted as written")),
            "{:?}",
            first.warnings
        );
        // The reader strips the wrapper back off...
        let reparsed = parse_dss_str(&first.text);
        let opt = |k: &str| {
            reparsed
                .options
                .iter()
                .find(|(name, _)| name == k)
                .map(|(_, v)| v.as_str())
        };
        assert_eq!(opt("foo"), Some("a!b"));
        assert_eq!(opt("bar"), Some("(abc"));
        assert_eq!(opt("baz"), Some("x ] y"));
        assert_eq!(opt("qux"), Some("a ) b"));
        // ...and the second write picks the same wrapper from the bare value.
        let second = write_dss(&reparsed);
        assert_eq!(first.text, second.text);
    }

    #[test]
    fn extras_tail_values_wrap_like_options() {
        let (b, vs) = three_phase_source(2400.0);
        let mut load = load_on("sb", &["1", "2", "3", "4"], Configuration::Wye);
        load.extras
            .insert("daily".into(), serde_json::json!("a ) b"));
        let net = DistNetwork {
            base_frequency: 60.0,
            buses: vec![b],
            sources: vec![vs],
            loads: vec![load],
            ..DistNetwork::default()
        };
        let (first, second) = roundtrip(&net);
        // A paren wrapper would close at the `)` and land `b)` on the next
        // positional property (duty); brackets survive.
        assert!(first.contains("daily=[a ) b]"), "{first}");
        assert_eq!(first, second);
        let back = parse_dss_str(&first);
        assert_eq!(
            back.loads[0]
                .extras
                .get("daily")
                .and_then(serde_json::Value::as_str),
            Some("a ) b")
        );
    }

    #[test]
    fn unrepresentable_values_emit_as_written_and_warn() {
        // Every quote closer appears, and the spaces split a bare scan: no
        // emitted form reparses to this value.
        let bad = "a )]}\"' b";
        let (b, vs) = three_phase_source(2400.0);
        let mut load = load_on("sb", &["1", "2", "3", "4"], Configuration::Wye);
        load.extras.insert("daily".into(), serde_json::json!(bad));
        let mut net = DistNetwork {
            base_frequency: 60.0,
            buses: vec![b],
            sources: vec![vs],
            loads: vec![load],
            ..DistNetwork::default()
        };
        net.options.push(("foo".into(), bad.into()));
        let out = write_dss(&net);
        assert!(out.text.contains(&format!("Set foo={bad}")), "{}", out.text);
        assert!(out.text.contains(&format!("daily={bad}")), "{}", out.text);
        let warned = |needle: &str| {
            out.warnings
                .iter()
                .any(|w| w.contains(needle) && w.contains("emitted as written"))
        };
        assert!(warned("option `foo`"), "{:?}", out.warnings);
        assert!(warned("`daily`"), "{:?}", out.warnings);
    }

    #[test]
    fn empty_extras_values_wrap_instead_of_eating_the_next_token() {
        let dss = "clear\nnew circuit.c basekv=12.47 bus1=sb\n\
                   new load.ld bus1=sb.1 phases=1 kv=7.2 kw=10 daily=() duty=sh\nsolve\n";
        let net = parse_dss_str(dss);
        let load = &net.loads[0];
        assert_eq!(load.extras.get("daily").and_then(|v| v.as_str()), Some(""));
        let w1 = write_dss(&net).text;
        let again = parse_dss_str(&w1);
        let load2 = &again.loads[0];
        assert_eq!(load2.extras.get("daily").and_then(|v| v.as_str()), Some(""));
        assert_eq!(
            load2.extras.get("duty").and_then(|v| v.as_str()),
            Some("sh")
        );
        assert_eq!(w1, write_dss(&again).text);
    }

    #[test]
    fn sub_unique_option_prefixes_re_emit_instead_of_vanishing() {
        // "ca" is CapkVAR and "default" is DefaultDaily in the engine's
        // option table; neither may be skipped as a derived key, and
        // `Set default=2.5` must not change the base frequency.
        let dss = "clear\nnew circuit.c basekv=12.47 bus1=sb\n\
                   Set ca=600\nSet default=2.5\nsolve\n";
        let net = parse_dss_str(dss);
        assert!((net.base_frequency - 60.0).abs() < 1e-12);
        let out = write_dss(&net).text;
        assert!(out.contains("Set ca=600"), "{out}");
        assert!(out.contains("Set default=2.5"), "{out}");
    }

    #[test]
    fn abbreviated_derived_options_skip_and_set_the_frequency() {
        // The engine resolves Set names by unique prefix, so volt= IS
        // Voltagebases and defaultb= IS DefaultBaseFrequency.
        let src = "Clear\n\
                   New Circuit.c1 basekv=12.47 pu=1 angle=0 phases=3 bus1=sb\n\
                   Set volt=[115, 132]\n\
                   Set defaultb=50\n\
                   Solve\n";
        let net = parse_dss_str(src);
        assert!((net.base_frequency - 50.0).abs() < 1e-12);
        let out = write_dss(&net);
        assert!(
            out.text.contains("Set DefaultBaseFrequency=50"),
            "{}",
            out.text
        );
        assert_eq!(
            out.text
                .to_lowercase()
                .matches("defaultbasefrequency")
                .count(),
            1,
            "{}",
            out.text
        );
        assert_eq!(
            out.text.matches("Set VoltageBases").count(),
            1,
            "{}",
            out.text
        );
        assert!(!out.text.contains("Set volt="), "{}", out.text);
        assert!(!out.text.contains("Set defaultb="), "{}", out.text);
        let second = write_dss(&parse_dss_str(&out.text));
        assert_eq!(out.text, second.text);
    }

    #[test]
    fn non_numeric_source_extras_warn_before_falling_back() {
        let (b, mut vs) = three_phase_source(2400.0);
        vs.extras
            .insert("basekv".into(), serde_json::json!("@base"));
        vs.extras.insert("pu".into(), serde_json::json!("unity"));
        vs.extras.insert("angle".into(), serde_json::json!([0.0]));
        let net = DistNetwork {
            base_frequency: 60.0,
            buses: vec![b],
            sources: vec![vs],
            ..DistNetwork::default()
        };
        let out = write_dss(&net);
        for key in ["basekv", "pu", "angle"] {
            assert!(
                out.warnings
                    .iter()
                    .any(|w| w.contains(&format!("{key} extra")) && w.contains("does not parse")),
                "{key}: {:?}",
                out.warnings
            );
        }
        // The derived values substitute.
        let line = out.text.lines().find(|l| l.contains("Circuit.")).unwrap();
        assert!(line.contains("pu=1 angle=0"), "{line}");
    }

    #[test]
    fn de_energized_source_phase_keeps_its_conductor() {
        let (b, mut vs) = three_phase_source(2400.0);
        vs.v_magnitude[2] = 0.0; // de-energized, but still a phase conductor
        let net = DistNetwork {
            name: Some("t".into()),
            base_frequency: 60.0,
            buses: vec![b],
            sources: vec![vs],
            ..DistNetwork::default()
        };
        let (first, second) = roundtrip(&net);
        let line = first.lines().find(|l| l.contains("Circuit.")).unwrap();
        // phases=2 against the 4 node dot list would drop a node on reparse.
        assert!(line.contains("phases=3"), "{line}");
        assert!(line.contains("bus1=sb.1.2.3.0"), "{line}");
        assert_eq!(first, second);
        let out = write_dss(&net);
        assert!(
            out.warnings
                .iter()
                .any(|w| w.contains("phases=3") && w.contains("positive")),
            "{:?}",
            out.warnings
        );
    }

    #[test]
    fn multiple_sources_keep_named_vsource_when_source_exists() {
        let third = 2.0 * std::f64::consts::FRAC_PI_3;
        let source = VoltageSource {
            name: "source".into(),
            bus: "Bx".into(),
            terminal_map: strings(&["1", "2", "3", "4"]),
            v_magnitude: vec![20_000.0, 20_000.0, 20_000.0, 0.0],
            v_angle: vec![0.0, -third, third, 0.0],
            extras: Extras::new(),
        };
        let wind = VoltageSource {
            name: "WindGen1".into(),
            bus: "Bg".into(),
            terminal_map: strings(&["1", "2", "3", "4"]),
            v_magnitude: vec![400.0, 400.0, 400.0, 0.0],
            v_angle: vec![
                -std::f64::consts::FRAC_PI_3,
                std::f64::consts::PI,
                third / 2.0,
                0.0,
            ],
            extras: Extras::new(),
        };
        let net = DistNetwork {
            name: Some("dg".into()),
            base_frequency: 60.0,
            buses: vec![
                bus("Bg", &["1", "2", "3", "4"], &["4"]),
                bus("Bx", &["1", "2", "3", "4"], &["4"]),
            ],
            sources: vec![wind, source],
            ..DistNetwork::default()
        };

        let out = write_dss(&net).text;
        let circuit = out.lines().find(|l| l.starts_with("New Circuit")).unwrap();
        assert!(circuit.contains("bus1=Bx.1.2.3.0"), "{circuit}");
        assert!(
            out.lines()
                .any(|l| l.starts_with("New Vsource.WindGen1") && l.contains("bus1=Bg.1.2.3.0")),
            "{out}"
        );
        let reparsed = parse_dss_str(&out);
        assert!(
            reparsed
                .sources
                .iter()
                .any(|vs| vs.name.eq_ignore_ascii_case("WindGen1")),
            "{:?}",
            reparsed.sources
        );
    }

    #[test]
    fn source_phases_stash_wins_and_does_not_double_emit() {
        let (b, mut vs) = three_phase_source(2400.0);
        vs.extras.insert("phases".into(), serde_json::json!("3"));
        let net = DistNetwork {
            base_frequency: 60.0,
            buses: vec![b],
            sources: vec![vs],
            ..DistNetwork::default()
        };
        let out = write_dss(&net);
        let line = out.text.lines().find(|l| l.contains("Circuit.")).unwrap();
        assert!(line.contains("phases=3"), "{line}");
        assert_eq!(line.matches("phases=").count(), 1, "{line}");
    }

    #[test]
    fn foreign_maps_without_a_neutral_warn_and_converge_at_write2() {
        // A vsource/wye load map with no grounded terminal: the engine's
        // nconds fill extends the reparsed bus with a grounded neutral, so
        // write1 is not a fixed point. The writer must say so.
        let third = 2.0 * std::f64::consts::FRAC_PI_3;
        let vs = VoltageSource {
            name: "source".into(),
            bus: "sb".into(),
            terminal_map: strings(&["1", "2", "3"]),
            v_magnitude: vec![2400.0; 3],
            v_angle: vec![0.0, -third, third],
            extras: Extras::new(),
        };
        let load = load_on("sb", &["1"], Configuration::Wye);
        let net = DistNetwork {
            name: Some("t".into()),
            base_frequency: 60.0,
            buses: vec![bus("sb", &["1", "2", "3"], &[])],
            sources: vec![vs],
            loads: vec![load],
            ..DistNetwork::default()
        };
        let first = write_dss(&net);
        let hits = |warnings: &[String], name: &str| {
            warnings
                .iter()
                .any(|w| w.contains(name) && w.contains("materializes a grounded neutral"))
        };
        assert!(
            hits(&first.warnings, "vsource source"),
            "{:?}",
            first.warnings
        );
        assert!(hits(&first.warnings, "load ld"), "{:?}", first.warnings);
        let second = write_dss(&parse_dss_str(&first.text));
        assert_ne!(first.text, second.text);
        assert!(!hits(&second.warnings, "vsource"), "{:?}", second.warnings);
        assert!(!hits(&second.warnings, "load"), "{:?}", second.warnings);
        let third_write = write_dss(&parse_dss_str(&second.text));
        assert_eq!(second.text, third_write.text);
    }

    #[test]
    fn generator_phases_and_conn_match_the_load_rules() {
        let (b, vs) = three_phase_source(2400.0);
        let g = DistGenerator {
            name: "g1".into(),
            bus: "sb".into(),
            terminal_map: strings(&["1", "2", "3"]),
            configuration: Configuration::Delta,
            p_nom: vec![1e3; 3],
            q_nom: vec![0.0; 3],
            p_min: None,
            p_max: None,
            q_min: None,
            q_max: None,
            cost: None,
            extras: Extras::from([
                ("kv".to_string(), serde_json::json!("4.16")),
                ("phases".to_string(), serde_json::json!("2")),
            ]),
        };
        let net = DistNetwork {
            base_frequency: 60.0,
            buses: vec![b],
            sources: vec![vs],
            generators: vec![g],
            ..DistNetwork::default()
        };
        let out = write_dss(&net);
        let line = out
            .text
            .lines()
            .find(|l| l.contains("Generator.g1"))
            .unwrap();
        assert!(line.contains("phases=2 conn=delta"), "{line}");
        assert_eq!(line.matches("phases=").count(), 1, "{line}");
    }
}