litz-board 0.5.1

Board runtime for Litz: flatten a diagram, resolve nets, and drive parts from pin levels.
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
//! Analog co-simulation over the board's flat nets.
//!
//! The digital runtime resolves every net to one of three levels. That is the
//! right model for logic, and it is deliberately the only model a digital-only
//! run pays for. This module adds an *optional* view on top of the same nets:
//! each net becomes a node in a [`litz_analog::Netlist`], the parts with an
//! electrical model become elements, and the solver gives every node a real
//! voltage — a DC operating point by default, or a backward-Euler transient
//! when the board is advanced over time.
//!
//! Two mappings are fixed:
//!
//! * **nets to nodes.** One node per net. The net holding `$gnd` is node 0.
//!   `$v33`, `$v5` and `$vin` are ideal sources to ground (3.3 V, 5 V and 5 V
//!   unless the [`AnalogConfig`] says otherwise). A net that no element and
//!   no active driver reaches is left out of the solve entirely, so its
//!   voltage is `None` — high impedance, not 0 V.
//! * **parts to elements.** A resistor is a resistor; an LED is a diode with a
//!   colour-dependent forward voltage plus a small series resistance; a
//!   potentiometer is two resistors with the wiper between them; a capacitor
//!   and an inductor are the corresponding reactive elements; a switch is a
//!   small resistance closed and a large one open; an NTC or photoresistor is
//!   a two-resistor divider whose ratio follows its host control; and the
//!   generic `bjt`, `mosfet` and `opamp` engines become their nonlinear
//!   devices. A part with no electrical model is skipped.
//!
//! Mixed mode is the point of the exercise. A chip pin that drives a net is
//! stamped as a Thevenin source — 3.3 V or 0 V behind a small driver
//! resistance — and a high-impedance pin contributes nothing. The solved
//! voltage on a part's analog pin is then what the chip's ADC reads.
//!
//! A chip pin is identified by `(board, GPIO)`, the same pair the runtime
//! uses, so two development boards' GPIO 4 are distinct nodes even though
//! they share a number. A net that joins the two boards' pins carries one
//! voltage, as a wire between them would.
//!
//! The solve is pure: [`solve`] only reads the flat circuit, the chip's
//! drives and the parts' host-visible state. It never changes the digital
//! runtime, which is why an analog-off board is bit-for-bit the board it was
//! before this module existed.
//!
//! # Transient state
//!
//! [`build`] with `transient = true` connects capacitor terminals for the
//! purpose of deciding which nets are solvable (a capacitor is a path at AC,
//! not at DC). The caller owns the [`litz_analog::Transient`]; [`Circuit`]
//! holds only the net-to-node map, so a new operating point can be extracted
//! from every step without rebuilding the netlist.

use crate::flatten::{Endpoint, Engine, FlatBoard, FlatPart, Rail};
use litz_analog::{
    BjtModel, DiodeModel, Element, ElementId, MosfetModel, Netlist, OpAmpModel,
    Solution as NetlistSolution, THERMAL_VOLTAGE,
};
use litz_core::{Drive, Level, Part, PartState, PinId, Strength};
use std::collections::{BTreeMap, BTreeSet};

/// The smallest resistance the solver is given. A potentiometer at either end
/// of its travel is a short; a tiny resistance keeps the netlist well formed
/// without changing the result at the precision a board run needs.
const MIN_OHMS: f64 = 1e-3;

/// A closed pushbutton or switch contact, in ohms.
const SWITCH_CLOSED_OHMS: f64 = 0.1;

/// An open pushbutton or switch contact, in ohms. Ten megohms is large enough
/// to read as an open circuit against any sane pull resistor and small enough
/// that the node keeps a well-defined DC solution.
const SWITCH_OPEN_OHMS: f64 = 10_000_000.0;

/// Track resistance used for a sensor's output divider when the manifest does
/// not say otherwise. It sets the divider's output impedance, not its ratio.
const SENSOR_OHMS: f64 = 10_000.0;

/// Voltages and resistances used to turn board parts into elements.
///
/// The defaults describe the dev boards in the built-in catalog: a 3.3 V logic
/// rail, a 5 V USB rail, a 50 Ω chip output and a 10 kΩ potentiometer. A
/// caller that knows better (a 1.8 V part, a higher-impedance source) sets its
/// own with [`crate::Board::set_analog_config`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct AnalogConfig {
    /// Voltage of `$v33`, in volts.
    pub v33: f64,
    /// Voltage of `$v5`, in volts.
    pub v5: f64,
    /// Voltage of `$vin` when the diagram does not configure it, in volts.
    pub vin: f64,
    /// Series resistance of a driven chip pin, in ohms.
    pub driver_ohms: f64,
    /// Series resistance bundled into an LED model, in ohms.
    pub led_series_ohms: f64,
    /// Current above which an LED counts as lit, in amperes.
    pub led_lit_amps: f64,
    /// Track resistance of a potentiometer whose manifest does not say one.
    pub pot_ohms: f64,
}

impl Default for AnalogConfig {
    fn default() -> Self {
        Self {
            v33: 3.3,
            v5: 5.0,
            vin: 5.0,
            driver_ohms: 50.0,
            led_series_ohms: 20.0,
            led_lit_amps: 1e-4,
            pot_ohms: 10_000.0,
        }
    }
}

/// A solved operating point, addressed the way a test or an adapter asks.
///
/// Every accessor returns `None` when the net is not part of the solve. That
/// is the high-impedance case: a pin wired to nothing, or to a part that no
/// source or ground path reaches. It is deliberately not `Some(0.0)`.
#[derive(Clone, Debug, Default)]
pub struct AnalogSolution {
    /// Voltage by flat-net id. `None` means the net was not solved.
    net_volts: Vec<Option<f64>>,
    /// Voltage by `(part index, pin index)` for every solved part pin.
    pin_volts: BTreeMap<(u16, u16), f64>,
    /// Voltage by `(board, chip GPIO)`, so two boards' GPIO 4 stay apart.
    gpio_volts: BTreeMap<(u16, u8), f64>,
    /// Current through a part's main element, in amperes.
    part_currents: BTreeMap<u16, f64>,
    /// Parts that carry an LED model, lit or not.
    leds: BTreeSet<u16>,
    /// Parts whose LED is lit.
    lit: BTreeSet<u16>,
    /// Part ids by flat index, so a name can be resolved without the board.
    part_ids: Vec<String>,
    /// Pin names by flat index, parallel to the part list.
    pin_names: Vec<Vec<String>>,
}

impl AnalogSolution {
    /// Voltage on one named pin of a named part, in volts.
    ///
    /// `None` when the part or pin does not exist, or when that node is
    /// floating (not reached by the solve).
    pub fn node_voltage(&self, part: &str, pin: &str) -> Option<f64> {
        let index = self.part_index(part)?;
        let pin = self
            .pin_names
            .get(index as usize)?
            .iter()
            .position(|name| name == pin)? as u16;
        self.node_voltage_pin(index, pin)
    }

    /// Voltage on GPIO `gpio` of board 0, in volts. `None` when the pin is
    /// floating. Board 0 is what a one-board test or adapter asks for.
    pub fn node_voltage_gpio(&self, gpio: u8) -> Option<f64> {
        self.node_voltage_gpio_on(0, gpio)
    }

    /// Voltage on GPIO `gpio` of board `board`, in volts. `None` when the pin
    /// is floating.
    pub fn node_voltage_gpio_on(&self, board: u16, gpio: u8) -> Option<f64> {
        self.gpio_volts.get(&(board, gpio)).copied()
    }

    /// Voltage on a flat net, in volts. `None` when the net was not solved.
    pub fn node_voltage_net(&self, net: u16) -> Option<f64> {
        self.net_volts.get(net as usize).copied().flatten()
    }

    /// Voltage on a part pin by flat indices.
    pub fn node_voltage_pin(&self, part: u16, pin: u16) -> Option<f64> {
        self.pin_volts.get(&(part, pin)).copied()
    }

    /// Whether a named pin is floating: it exists but has no solved voltage.
    /// `None` when the part or pin does not exist at all.
    pub fn node_is_high_z(&self, part: &str, pin: &str) -> Option<bool> {
        let index = self.part_index(part)?;
        let pin = self
            .pin_names
            .get(index as usize)?
            .iter()
            .position(|name| name == pin)? as u16;
        Some(!self.pin_volts.contains_key(&(index, pin)))
    }

    /// Current through a named part's main element, in amperes.
    ///
    /// For an LED this is the forward current through the junction; for a
    /// resistor it is the current from its first pin to its second.
    pub fn current(&self, part: &str) -> Option<f64> {
        let index = self.part_index(part)?;
        self.part_currents.get(&index).copied()
    }

    /// Whether a named part is an LED, and whether it is lit. `None` when the
    /// part is not an LED model.
    pub fn is_lit(&self, part: &str) -> Option<bool> {
        let index = self.part_index(part)?;
        self.leds
            .contains(&index)
            .then(|| self.lit.contains(&index))
    }

    /// The number of nets this solution covers, for a caller that wants to
    /// inspect [`AnalogSolution::node_voltage_net`] over the whole board.
    pub fn net_count(&self) -> usize {
        self.net_volts.len()
    }

    fn part_index(&self, part: &str) -> Option<u16> {
        self.part_ids
            .iter()
            .position(|id| id == part)
            .map(|i| i as u16)
    }
}

/// Solve the board's DC operating point.
///
/// `drives` is the chip's current output state, `parts` is the runtime's part
/// list (the potentiometer's position lives in its [`PartState`]), and
/// `config` supplies the rail and driver values. The result is deterministic:
/// nodes are numbered in net order, elements are added in part order, and the
/// solver itself has no nondeterminism.
pub(crate) fn solve(
    flat: &FlatBoard,
    drives: &BTreeMap<(u16, u8), Drive>,
    parts: &[Box<dyn Part>],
    config: &AnalogConfig,
) -> Result<AnalogSolution, String> {
    build_operating(flat, drives, parts, config, false)?.solve_dc(config)
}

/// Build the circuit at its operating point, with every regulated source that
/// is over its current limit folded back to that limit.
///
/// The first build assumes constant voltage. If the load then draws more than
/// a supply allows, that supply is modelled as a current source and the circuit
/// is built again; folding one supply back can push another over, so the set
/// only grows and the loop ends after at most one build per limiting supply.
/// The mode is fixed for the lifetime of the returned circuit, which is what a
/// transient run wants: a load change rebuilds the circuit anyway.
pub(crate) fn build_operating(
    flat: &FlatBoard,
    drives: &BTreeMap<(u16, u8), Drive>,
    parts: &[Box<dyn Part>],
    config: &AnalogConfig,
    transient: bool,
) -> Result<Circuit, String> {
    let mut limited = BTreeSet::new();
    loop {
        let circuit = build(flat, drives, parts, config, transient, &limited)?;
        let solution = circuit.solve_dc(config)?;
        let folded = folded_sources(flat, parts, &solution);
        let grown: BTreeSet<u16> = limited.union(&folded).copied().collect();
        if grown == limited {
            return Ok(circuit);
        }
        limited = grown;
    }
}

/// Supplies whose load draws more than their current limit.
fn folded_sources(
    flat: &FlatBoard,
    parts: &[Box<dyn Part>],
    solution: &AnalogSolution,
) -> BTreeSet<u16> {
    parts
        .iter()
        .enumerate()
        .filter_map(|(index, part)| {
            let limit = part.current_limit()?;
            // `part_currents` follows the element's first-terminal-to-second
            // sense: a source delivering to its load reads negative.
            let delivered = -solution.current(flat.parts.get(index)?.id.as_str())?;
            (delivered > f64::from(limit) + 1e-9).then_some(index as u16)
        })
        .collect()
}

/// Whether an engine is an analog-only element this build maps but does not
/// (yet) have a digital part for.
///
/// `parts::build` rejects an unknown builtin engine. A capacitor, inductor,
/// transistor or op-amp has no digital behaviour at all, so a board may run
/// with one before the builtin engine lands; the analog view reads its
/// attributes directly and only needs the pins to exist. Once the engine is
/// registered, `parts::build` succeeds and this fallback is never reached.
pub(crate) fn is_analog_only_engine(part: &FlatPart) -> bool {
    matches!(
        &part.engine,
        Engine::Builtin(engine)
            if matches!(
                engine.as_str(),
                "capacitor" | "inductor" | "bjt" | "mosfet" | "opamp" | "op-amp"
            )
    )
}

/// The netlist plus everything needed to read a solution back out, built once
/// and reused by every transient step.
///
/// The netlist is static for a run: a chip drive, a press, a control change or
/// a new [`AnalogConfig`] discards the whole circuit (and the transient state
/// with it) rather than patching it, which keeps the numeric history and the
/// topology consistent.
pub(crate) struct Circuit {
    netlist: Netlist,
    /// Node number for a flat net; `None` when the net is floating.
    node_of_net: Vec<Option<usize>>,
    /// The flat board's endpoints, copied so a solved node can be reported on
    /// every pin and chip pad tied to it.
    nets: Vec<Vec<Endpoint>>,
    net_count: usize,
    part_ids: Vec<String>,
    pin_names: Vec<Vec<String>>,
    current_elements: Vec<(u16, ElementId)>,
    leds: BTreeSet<u16>,
}

impl Circuit {
    /// The netlist a transient run steps.
    pub(crate) fn netlist(&self) -> &Netlist {
        &self.netlist
    }

    /// Solve the circuit's DC operating point.
    pub(crate) fn solve_dc(&self, config: &AnalogConfig) -> Result<AnalogSolution, String> {
        if self.netlist.is_empty() {
            return Ok(self.blank());
        }
        let solved = self
            .netlist
            .solve_dc()
            .map_err(|e| format!("analog: the netlist could not be solved: {e}"))?;
        Ok(self.solution(&solved, config))
    }

    /// Turn a solver result into the board-addressed view.
    pub(crate) fn solution(
        &self,
        solved: &NetlistSolution,
        config: &AnalogConfig,
    ) -> AnalogSolution {
        let mut solution = self.blank();
        for (net, node) in self.node_of_net.iter().enumerate() {
            if let Some(node) = *node {
                solution.net_volts[net] = solved.node_volts.get(node).copied();
            }
        }
        self.place_endpoints(&mut solution);
        for &(part, element) in &self.current_elements {
            if let Ok(amps) = solved.probe_current(element) {
                solution.part_currents.insert(part, amps);
                if self.leds.contains(&part) && amps > config.led_lit_amps {
                    solution.lit.insert(part);
                }
            }
        }
        solution.leds.clone_from(&self.leds);
        solution
    }

    /// The `t = 0` solution of a zero-state transient: every solved node is
    /// 0 V until the first step moves it.
    pub(crate) fn initial_solution(&self) -> AnalogSolution {
        let mut solution = self.blank();
        for (net, node) in self.node_of_net.iter().enumerate() {
            if node.is_some() {
                solution.net_volts[net] = Some(0.0);
            }
        }
        self.place_endpoints(&mut solution);
        solution.leds.clone_from(&self.leds);
        solution
    }

    fn blank(&self) -> AnalogSolution {
        AnalogSolution {
            net_volts: vec![None; self.net_count],
            part_ids: self.part_ids.clone(),
            pin_names: self.pin_names.clone(),
            ..AnalogSolution::default()
        }
    }

    /// Copy every solved net voltage onto the chip and part pins on that net.
    fn place_endpoints(&self, solution: &mut AnalogSolution) {
        for (net, members) in self.nets.iter().enumerate() {
            let Some(volts) = solution.net_volts.get(net).copied().flatten() else {
                continue;
            };
            for endpoint in members {
                match *endpoint {
                    Endpoint::Chip(gpio) => {
                        solution.gpio_volts.insert((0, gpio), volts);
                    }
                    Endpoint::ChipOn { board, pin } => {
                        solution.gpio_volts.insert((board, pin), volts);
                    }
                    Endpoint::Part { part, pin } => {
                        solution.pin_volts.insert((part, pin), volts);
                    }
                    Endpoint::Rail(_) => {}
                }
            }
        }
    }
}

/// Build the netlist for the current board state.
///
/// `transient` decides only which elements count for *reachability*: a
/// capacitor is an open circuit at DC, so a net reached solely through one is
/// left floating in a DC solve, while a transient needs it as a node. Element
/// set and node numbering are otherwise identical, so a DC solve and the first
/// transient step describe the same circuit.
pub(crate) fn build(
    flat: &FlatBoard,
    drives: &BTreeMap<(u16, u8), Drive>,
    parts: &[Box<dyn Part>],
    config: &AnalogConfig,
    transient: bool,
    limited: &BTreeSet<u16>,
) -> Result<Circuit, String> {
    let net_count = flat.nets.len();
    let ground = net_count;
    let mut sets = DisjointSet::new(net_count + 1);

    // Rail nets are fixed nodes. `$gnd` is node 0; the other rails are ideal
    // sources to ground, so they are electrically tied to it for the purpose
    // of deciding which components are solvable.
    let mut rail_nets: BTreeMap<Rail, usize> = BTreeMap::new();
    for (net, members) in flat.nets.iter().enumerate() {
        for endpoint in members {
            if let Endpoint::Rail(rail) = *endpoint {
                rail_nets.entry(rail).or_insert(net);
            }
        }
    }
    for net in rail_nets.values() {
        sets.union(*net, ground);
    }

    // Chip drivers are Thevenin sources to ground; a high-impedance pin adds
    // no path at all. `chip_drive` is keyed by `(board, GPIO)`.
    for (net, members) in flat.nets.iter().enumerate() {
        for endpoint in members {
            if let Some((board, gpio)) = endpoint.chip_pin()
                && chip_volts(
                    drives.get(&(board, gpio)).copied().unwrap_or(Drive::HIGH_Z),
                    config,
                )
                .is_some()
            {
                sets.union(net, ground);
            }
        }
    }

    let mut models = Vec::new();
    for (index, part) in flat.parts.iter().enumerate() {
        if let Some(model) =
            part_model(flat, parts, index as u16, part, config, &rail_nets, limited)
        {
            model.union(&mut sets, transient);
            models.push(model);
        }
    }

    let ground_root = sets.find(ground);
    let mut solvable = |net: usize| sets.find(net) == ground_root;

    // Node 0 is ground. A net tied to ground by a rail gets node 0; any other
    // net in that component gets its own node. A component with no ground is
    // left out, so its nodes stay `None` (high impedance).
    let ground_net = rail_nets.get(&Rail::Gnd).copied();
    let mut node_of_net = vec![None; net_count];
    let mut next_node = 1usize;
    for (net, slot) in node_of_net.iter_mut().enumerate() {
        if !solvable(net) {
            continue;
        }
        if Some(net) == ground_net {
            *slot = Some(0);
        } else {
            *slot = Some(next_node);
            next_node += 1;
        }
    }

    // Count the internal nodes a model needs: one for an LED's series
    // resistor, one for a chip driver's Thevenin resistance.
    let mut internal = 0usize;
    for model in &models {
        internal += model.internal_nodes(&node_of_net);
    }
    for (net, members) in flat.nets.iter().enumerate() {
        if node_of_net[net].is_none() {
            continue;
        }
        for endpoint in members {
            if let Some((board, gpio)) = endpoint.chip_pin()
                && chip_volts(
                    drives.get(&(board, gpio)).copied().unwrap_or(Drive::HIGH_Z),
                    config,
                )
                .is_some()
            {
                internal += 1;
            }
        }
    }

    let node_count = next_node + internal;
    let mut netlist = Netlist::new(node_count);
    let mut next_internal = next_node;
    let mut alloc = || {
        let node = next_internal;
        next_internal += 1;
        node
    };

    // Rails. `$gnd` is the reference and needs no element.
    for (&rail, &net) in &rail_nets {
        if rail == Rail::Gnd {
            continue;
        }
        let Some(node) = node_of_net[net] else {
            continue;
        };
        netlist
            .add(Element::VoltageSource {
                p: node,
                n: 0,
                volts: rail_volts(rail, config),
            })
            .map_err(|e| format!("analog: rail {rail:?}: {e}"))?;
    }

    // Driven chip pins: a voltage behind the driver's output resistance.
    for (net, members) in flat.nets.iter().enumerate() {
        let Some(node) = node_of_net[net] else {
            continue;
        };
        for endpoint in members {
            let Some((board, gpio)) = endpoint.chip_pin() else {
                continue;
            };
            let Some(volts) = chip_volts(
                drives.get(&(board, gpio)).copied().unwrap_or(Drive::HIGH_Z),
                config,
            ) else {
                continue;
            };
            let source = alloc();
            netlist
                .add(Element::VoltageSource {
                    p: source,
                    n: 0,
                    volts,
                })
                .map_err(|e| format!("analog: {} driver: {e}", chip_label(board, gpio)))?;
            netlist
                .add(Element::Resistor {
                    a: source,
                    b: node,
                    ohms: config.driver_ohms,
                })
                .map_err(|e| format!("analog: {} driver: {e}", chip_label(board, gpio)))?;
        }
    }

    let mut current_elements: Vec<(u16, ElementId)> = Vec::new();
    let mut leds = BTreeSet::new();
    for model in &models {
        model.build(
            &mut netlist,
            &node_of_net,
            &mut alloc,
            config,
            &mut current_elements,
            &mut leds,
        )?;
    }

    Ok(Circuit {
        netlist,
        node_of_net,
        nets: flat.nets.clone(),
        net_count,
        part_ids: flat.parts.iter().map(|part| part.id.clone()).collect(),
        pin_names: flat.parts.iter().map(|part| part.pins.clone()).collect(),
        current_elements,
        leds,
    })
}

/// The voltage a chip pin holds as a Thevenin source. High-Z and weak drives
/// return `None`: an input is not a source.
fn chip_volts(drive: Drive, config: &AnalogConfig) -> Option<f64> {
    if drive.strength != Strength::Strong {
        return None;
    }
    match drive.level {
        Level::High => Some(config.v33),
        Level::Low => Some(0.0),
        Level::HighZ => None,
    }
}

/// A chip pin as an error message names it. Board 0 keeps the plain GPIO the
/// single-board messages always used; another board is prefixed so a fault is
/// not attributed to the wrong chip.
fn chip_label(board: u16, gpio: u8) -> String {
    if board == 0 {
        format!("GPIO{gpio}")
    } else {
        format!("board {board} GPIO{gpio}")
    }
}

fn rail_volts(rail: Rail, config: &AnalogConfig) -> f64 {
    match rail {
        Rail::Gnd => 0.0,
        Rail::V33 => config.v33,
        Rail::V5 => config.v5,
        Rail::Vin => config.vin,
    }
}

/// One part's electrical model, with each terminal already resolved to a flat
/// net when its pin is wired.
enum Model {
    Resistor {
        part: u16,
        a: Option<usize>,
        b: Option<usize>,
        ohms: f64,
    },
    Led {
        part: u16,
        anode: Option<usize>,
        cathode: Option<usize>,
        color: String,
    },
    Potentiometer {
        end1: Option<usize>,
        wiper: Option<usize>,
        end3: Option<usize>,
        total_ohms: f64,
        travel: f64,
    },
    Diode {
        part: u16,
        anode: Option<usize>,
        cathode: Option<usize>,
        model: DiodeModel,
    },
    VoltageSource {
        part: u16,
        p: Option<usize>,
        n: Option<usize>,
        volts: f64,
    },
    CurrentSource {
        part: u16,
        p: Option<usize>,
        n: Option<usize>,
        amps: f64,
    },
    Capacitor {
        part: u16,
        a: Option<usize>,
        b: Option<usize>,
        farads: f64,
    },
    Inductor {
        part: u16,
        a: Option<usize>,
        b: Option<usize>,
        henries: f64,
    },
    /// A pushbutton: two contacts, each with two internally joined legs.
    Pushbutton {
        part: u16,
        /// `[[1.l, 1.r], [2.l, 2.r]]` resolved to nets.
        contacts: [[Option<usize>; 2]; 2],
        closed: bool,
    },
    /// An SPDT slide switch: common `2` rests on throw `1` or throw `3`.
    SlideSwitch {
        part: u16,
        throw1: Option<usize>,
        common: Option<usize>,
        throw3: Option<usize>,
        on: bool,
    },
    /// An NTC or photoresistor module's output, as a divider between a
    /// reference rail and ground at the part's control fraction.
    SensorDivider {
        ao: Option<usize>,
        reference: Option<usize>,
        ground: Option<usize>,
        fraction: f64,
        total_ohms: f64,
    },
    Bjt {
        part: u16,
        collector: Option<usize>,
        base: Option<usize>,
        emitter: Option<usize>,
        model: BjtModel,
    },
    Mosfet {
        part: u16,
        drain: Option<usize>,
        gate: Option<usize>,
        source: Option<usize>,
        model: MosfetModel,
    },
    OpAmp {
        plus: Option<usize>,
        minus: Option<usize>,
        out: Option<usize>,
        model: OpAmpModel,
    },
}

impl Model {
    /// Connectivity for deciding which components the solve can reference.
    fn union(&self, sets: &mut DisjointSet, transient: bool) {
        match self {
            Model::Resistor {
                a: Some(a),
                b: Some(b),
                ..
            } => sets.union(*a, *b),
            Model::Led {
                anode: Some(a),
                cathode: Some(c),
                ..
            }
            | Model::Diode {
                anode: Some(a),
                cathode: Some(c),
                ..
            } => sets.union(*a, *c),
            Model::Potentiometer {
                end1, wiper, end3, ..
            } => {
                if let (Some(a), Some(w)) = (end1, wiper) {
                    sets.union(*a, *w);
                }
                if let (Some(w), Some(b)) = (wiper, end3) {
                    sets.union(*w, *b);
                }
            }
            // An ideal voltage source ties its terminals together for this
            // purpose; a current source does not conduct and so does not.
            Model::VoltageSource {
                p: Some(p),
                n: Some(n),
                ..
            } => sets.union(*p, *n),
            // A capacitor is a connection only when time is part of the
            // analysis; at DC it is an open circuit.
            Model::Capacitor {
                a: Some(a),
                b: Some(b),
                ..
            } if transient => sets.union(*a, *b),
            Model::Inductor {
                a: Some(a),
                b: Some(b),
                ..
            } => sets.union(*a, *b),
            Model::Pushbutton {
                contacts, closed, ..
            } => {
                for contact in contacts {
                    if let (Some(a), Some(b)) = (contact[0], contact[1]) {
                        sets.union(a, b);
                    }
                }
                if *closed
                    && let (Some(a), Some(b)) =
                        (first_wired(&contacts[0]), first_wired(&contacts[1]))
                {
                    sets.union(a, b);
                }
            }
            Model::SlideSwitch {
                throw1,
                common: Some(common),
                throw3,
                on,
                ..
            } => {
                let selected = if *on { *throw3 } else { *throw1 };
                if let Some(selected) = selected {
                    sets.union(*common, selected);
                }
            }
            Model::SensorDivider {
                ao: Some(ao),
                reference,
                ground,
                ..
            } => {
                if let Some(reference) = *reference {
                    sets.union(*ao, reference);
                }
                if let Some(ground) = *ground {
                    sets.union(*ao, ground);
                }
            }
            // A BJT conducts between all three terminals; an NMOS channel
            // conducts drain to source. An insulated gate and an op-amp input
            // are deliberately not tied to anything: a node with no DC path is
            // a wiring fault the solver reports rather than a silent short.
            Model::Bjt {
                collector: Some(c),
                base: Some(b),
                emitter: Some(e),
                ..
            } => {
                sets.union(*c, *e);
                sets.union(*b, *e);
            }
            Model::Mosfet {
                drain: Some(d),
                source: Some(s),
                ..
            } => sets.union(*d, *s),
            _ => {}
        }
    }

    fn internal_nodes(&self, node_of_net: &[Option<usize>]) -> usize {
        match self {
            Model::Led {
                anode: Some(a),
                cathode: Some(c),
                ..
            } => usize::from(
                node_of_net.get(*a).copied().flatten().is_some()
                    && node_of_net.get(*c).copied().flatten().is_some(),
            ),
            _ => 0,
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn build(
        &self,
        netlist: &mut Netlist,
        node_of_net: &[Option<usize>],
        alloc: &mut impl FnMut() -> usize,
        config: &AnalogConfig,
        currents: &mut Vec<(u16, ElementId)>,
        leds: &mut BTreeSet<u16>,
    ) -> Result<(), String> {
        let node = |net: Option<usize>| -> Option<usize> {
            let net = net?;
            node_of_net.get(net).copied().flatten()
        };
        let add = |netlist: &mut Netlist, element: Element, what: &str| {
            netlist
                .add(element)
                .map_err(|e| format!("analog: {what}: {e}"))
        };

        match self {
            Model::Resistor { part, a, b, ohms } => {
                if let (Some(a), Some(b)) = (node(*a), node(*b)) {
                    let id = add(
                        netlist,
                        Element::Resistor {
                            a,
                            b,
                            ohms: (*ohms).max(MIN_OHMS),
                        },
                        "resistor",
                    )?;
                    currents.push((*part, id));
                }
            }
            Model::Led {
                part,
                anode,
                cathode,
                color,
            } => {
                if let (Some(anode), Some(cathode)) = (node(*anode), node(*cathode)) {
                    let junction = alloc();
                    let model = led_model(color);
                    let id = add(
                        netlist,
                        Element::Diode {
                            anode,
                            cathode: junction,
                            model,
                        },
                        "LED",
                    )?;
                    add(
                        netlist,
                        Element::Resistor {
                            a: junction,
                            b: cathode,
                            ohms: config.led_series_ohms.max(MIN_OHMS),
                        },
                        "LED series resistance",
                    )?;
                    currents.push((*part, id));
                    leds.insert(*part);
                }
            }
            Model::Potentiometer {
                end1,
                wiper,
                end3,
                total_ohms,
                travel,
            } => {
                let Some(wiper) = node(*wiper) else {
                    return Ok(());
                };
                // The track runs from 1 to 3. At travel 0 the wiper sits on
                // end 1, at 1 it sits on end 3.
                if let Some(end1) = node(*end1) {
                    add(
                        netlist,
                        Element::Resistor {
                            a: end1,
                            b: wiper,
                            ohms: (total_ohms * travel).max(MIN_OHMS),
                        },
                        "potentiometer track",
                    )?;
                }
                if let Some(end3) = node(*end3) {
                    add(
                        netlist,
                        Element::Resistor {
                            a: wiper,
                            b: end3,
                            ohms: (total_ohms * (1.0 - travel)).max(MIN_OHMS),
                        },
                        "potentiometer track",
                    )?;
                }
            }
            Model::Diode {
                part,
                anode,
                cathode,
                model,
            } => {
                if let (Some(anode), Some(cathode)) = (node(*anode), node(*cathode)) {
                    let id = add(
                        netlist,
                        Element::Diode {
                            anode,
                            cathode,
                            model: *model,
                        },
                        "diode",
                    )?;
                    currents.push((*part, id));
                }
            }
            Model::VoltageSource { part, p, n, volts } => {
                if let (Some(p), Some(n)) = (node(*p), node(*n)) {
                    let id = add(
                        netlist,
                        Element::VoltageSource {
                            p,
                            n,
                            volts: *volts,
                        },
                        "source",
                    )?;
                    currents.push((*part, id));
                }
            }
            Model::CurrentSource { part, p, n, amps } => {
                if let (Some(p), Some(n)) = (node(*p), node(*n)) {
                    let id = add(
                        netlist,
                        Element::CurrentSource { p, n, amps: *amps },
                        "source",
                    )?;
                    // A source that folds back reads out like a supply: the
                    // caller sees the current it is actually delivering.
                    currents.push((*part, id));
                }
            }
            Model::Capacitor { part, a, b, farads } => {
                if let (Some(a), Some(b)) = (node(*a), node(*b)) {
                    let id = add(
                        netlist,
                        Element::Capacitor {
                            a,
                            b,
                            farads: (*farads).max(f64::MIN_POSITIVE),
                        },
                        "capacitor",
                    )?;
                    currents.push((*part, id));
                }
            }
            Model::Inductor {
                part,
                a,
                b,
                henries,
            } => {
                if let (Some(a), Some(b)) = (node(*a), node(*b)) {
                    let id = add(
                        netlist,
                        Element::Inductor {
                            a,
                            b,
                            henries: (*henries).max(f64::MIN_POSITIVE),
                        },
                        "inductor",
                    )?;
                    currents.push((*part, id));
                }
            }
            Model::Pushbutton {
                part,
                contacts,
                closed,
            } => {
                // Each contact is one conductor; legs are joined by a tiny
                // resistance so a wire to either leg reaches the switch.
                for contact in contacts {
                    if let (Some(a), Some(b)) = (node(contact[0]), node(contact[1])) {
                        add(
                            netlist,
                            Element::Resistor {
                                a,
                                b,
                                ohms: MIN_OHMS,
                            },
                            "pushbutton contact",
                        )?;
                    }
                }
                let a = node(first_wired(&contacts[0]));
                let b = node(first_wired(&contacts[1]));
                if let (Some(a), Some(b)) = (a, b) {
                    let id = add(
                        netlist,
                        Element::Resistor {
                            a,
                            b,
                            ohms: contact_ohms(*closed),
                        },
                        "pushbutton",
                    )?;
                    currents.push((*part, id));
                }
            }
            Model::SlideSwitch {
                part,
                throw1,
                common,
                throw3,
                on,
            } => {
                let Some(common) = node(*common) else {
                    return Ok(());
                };
                if let Some(throw1) = node(*throw1) {
                    let id = add(
                        netlist,
                        Element::Resistor {
                            a: common,
                            b: throw1,
                            ohms: contact_ohms(!*on),
                        },
                        "slide switch",
                    )?;
                    if !*on {
                        currents.push((*part, id));
                    }
                }
                if let Some(throw3) = node(*throw3) {
                    let id = add(
                        netlist,
                        Element::Resistor {
                            a: common,
                            b: throw3,
                            ohms: contact_ohms(*on),
                        },
                        "slide switch",
                    )?;
                    if *on {
                        currents.push((*part, id));
                    }
                }
            }
            Model::SensorDivider {
                ao,
                reference,
                ground,
                fraction,
                total_ohms,
            } => {
                let (Some(ao), Some(reference), Some(ground)) =
                    (node(*ao), node(*reference), node(*ground))
                else {
                    return Ok(());
                };
                // V(ao) = reference · fraction when nothing loads the divider.
                let fraction = fraction.clamp(0.0, 1.0);
                add(
                    netlist,
                    Element::Resistor {
                        a: reference,
                        b: ao,
                        ohms: (total_ohms * (1.0 - fraction)).max(MIN_OHMS),
                    },
                    "sensor divider",
                )?;
                add(
                    netlist,
                    Element::Resistor {
                        a: ao,
                        b: ground,
                        ohms: (total_ohms * fraction).max(MIN_OHMS),
                    },
                    "sensor divider",
                )?;
            }
            Model::Bjt {
                part,
                collector,
                base,
                emitter,
                model,
            } => {
                if let (Some(collector), Some(base), Some(emitter)) =
                    (node(*collector), node(*base), node(*emitter))
                {
                    let id = add(
                        netlist,
                        Element::Bjt {
                            collector,
                            base,
                            emitter,
                            model: *model,
                        },
                        "BJT",
                    )?;
                    currents.push((*part, id));
                }
            }
            Model::Mosfet {
                part,
                drain,
                gate,
                source,
                model,
            } => {
                if let (Some(drain), Some(gate), Some(source)) =
                    (node(*drain), node(*gate), node(*source))
                {
                    let id = add(
                        netlist,
                        Element::Mosfet {
                            drain,
                            gate,
                            source,
                            model: *model,
                        },
                        "MOSFET",
                    )?;
                    currents.push((*part, id));
                }
            }
            Model::OpAmp {
                plus,
                minus,
                out,
                model,
            } => {
                if let (Some(plus), Some(minus), Some(out)) =
                    (node(*plus), node(*minus), node(*out))
                {
                    add(
                        netlist,
                        Element::OpAmp {
                            plus,
                            minus,
                            out,
                            model: *model,
                        },
                        "op-amp",
                    )?;
                }
            }
        }
        Ok(())
    }
}

fn first_wired(legs: &[Option<usize>; 2]) -> Option<usize> {
    legs[0].or(legs[1])
}

fn contact_ohms(closed: bool) -> f64 {
    if closed {
        SWITCH_CLOSED_OHMS
    } else {
        SWITCH_OPEN_OHMS
    }
}

/// Read one part's electrical model from its engine and attributes.
fn part_model(
    flat: &FlatBoard,
    parts: &[Box<dyn Part>],
    index: u16,
    part: &FlatPart,
    config: &AnalogConfig,
    rail_nets: &BTreeMap<Rail, usize>,
    limited: &BTreeSet<u16>,
) -> Option<Model> {
    let Engine::Builtin(engine) = &part.engine else {
        return None;
    };
    let pin = |names: &[&str]| {
        names
            .iter()
            .find_map(|name| part.pins.iter().position(|candidate| candidate == name))
            .map(|pin| pin as u16)
    };
    let net = |pin: Option<u16>| -> Option<usize> {
        let pin = pin?;
        flat.endpoint_net
            .get(&Endpoint::Part { part: index, pin })
            .map(|net| *net as usize)
    };
    let attr = |name: &str| part.attrs.get(name).map(String::as_str);
    let state = || parts.get(index as usize).map(|part| part.state());

    match engine.as_str() {
        "resistor" => {
            let ohms = attr("value").and_then(parse_resistance).unwrap_or(220.0);
            Some(Model::Resistor {
                part: index,
                a: net(pin(&["1"]).or(Some(0))),
                b: net(pin(&["2"]).or(Some(1))),
                ohms,
            })
        }
        "led" => Some(Model::Led {
            part: index,
            anode: net(pin(&["A", "anode"])),
            cathode: net(pin(&["C", "cathode"])),
            color: attr("color").unwrap_or("red").to_string(),
        }),
        "potentiometer" => {
            let total_ohms = attr("resistance")
                .and_then(parse_resistance)
                .unwrap_or(config.pot_ohms);
            let travel = match state() {
                Some(PartState::Knob { permille }) => f64::from(permille) / 1000.0,
                _ => attr("value").map_or(0.5, parse_percent),
            };
            Some(Model::Potentiometer {
                end1: net(pin(&["1"])),
                wiper: net(pin(&["2", "W", "wiper"])),
                end3: net(pin(&["3"])),
                total_ohms,
                travel: travel.clamp(0.0, 1.0),
            })
        }
        "diode" => {
            let model = attr("vf")
                .or_else(|| attr("forward_voltage"))
                .or_else(|| attr("forward-voltage"))
                .and_then(parse_volts)
                .map_or_else(DiodeModel::silicon, diode_at_forward_volts);
            Some(Model::Diode {
                part: index,
                anode: net(pin(&["A", "anode"])),
                cathode: net(pin(&["C", "cathode"])),
                model,
            })
        }
        "voltage-source" | "dc-source" | "vsource" | "battery" => {
            let positive = pin(&["+", "V+", "P", "p", "1"]);
            let negative = pin(&["-", "V-", "N", "n", "2"]);
            // A bench supply reports its live setting; the attribute is the
            // starting point and a part without a live reading falls back to
            // it. A battery or a plain source has no control and never does.
            let volts = parts
                .get(index as usize)
                .and_then(|part| positive.and_then(|pin| part.analog(PinId(pin))))
                .map_or_else(
                    || {
                        attr("voltage")
                            .or_else(|| attr("volts"))
                            .or_else(|| attr("value"))
                            .and_then(parse_volts)
                            .unwrap_or(0.0)
                    },
                    f64::from,
                );
            if limited.contains(&index) {
                // Fold-back: hold the current, let the voltage land where the
                // load puts it. Current flows from the negative terminal
                // through the supply to the positive one, so the element's
                // `p`-to-`n` current is negative.
                let amps = parts
                    .get(index as usize)
                    .and_then(|part| part.current_limit())
                    .map_or(0.0, |limit| -f64::from(limit));
                return Some(Model::CurrentSource {
                    part: index,
                    p: net(positive),
                    n: net(negative),
                    amps,
                });
            }
            Some(Model::VoltageSource {
                part: index,
                p: net(positive),
                n: net(negative),
                volts,
            })
        }
        "signal-generator" => {
            // The engine owns the waveform; the source's value is whatever it
            // reports on OUT at the current phase. A pin that reports no
            // voltage contributes no source to the solve.
            let out_pin = pin(&["OUT"])?;
            let volts = parts.get(index as usize)?.analog(PinId(out_pin))?;
            Some(Model::VoltageSource {
                part: index,
                p: net(Some(out_pin)),
                n: net(pin(&["GND"])),
                volts: f64::from(volts),
            })
        }
        "current-source" | "isource" => {
            let amps = attr("amps")
                .or_else(|| attr("current"))
                .or_else(|| attr("value"))
                .and_then(parse_volts)
                .unwrap_or(0.0);
            Some(Model::CurrentSource {
                part: index,
                p: net(pin(&["+", "P", "p", "1"])),
                n: net(pin(&["-", "N", "n", "2"])),
                amps,
            })
        }
        "capacitor" => {
            let farads = attr("value")
                .or_else(|| attr("capacitance"))
                .and_then(parse_capacitance)
                .unwrap_or(1e-6);
            Some(Model::Capacitor {
                part: index,
                a: net(pin(&["1", "A", "+"])),
                b: net(pin(&["2", "B", "-"])),
                farads,
            })
        }
        "inductor" => {
            let henries = attr("value")
                .or_else(|| attr("inductance"))
                .and_then(parse_inductance)
                .unwrap_or(1e-3);
            Some(Model::Inductor {
                part: index,
                a: net(pin(&["1", "A"])),
                b: net(pin(&["2", "B"])),
                henries,
            })
        }
        "pushbutton" => {
            let legs = [
                [net(pin(&["1.l"])), net(pin(&["1.r"]))],
                [net(pin(&["2.l"])), net(pin(&["2.r"]))],
            ];
            let closed = matches!(state(), Some(PartState::Button { pressed: true }));
            Some(Model::Pushbutton {
                part: index,
                contacts: legs,
                closed,
            })
        }
        "slide-switch" => {
            let on = matches!(state(), Some(PartState::Switch { on: true }));
            Some(Model::SlideSwitch {
                part: index,
                throw1: net(pin(&["1"])),
                common: net(pin(&["2"])),
                throw3: net(pin(&["3"])),
                on,
            })
        }
        "ntc-temperature-sensor" => {
            let fraction = match state() {
                Some(PartState::Knob { permille }) => f64::from(permille) / 1000.0,
                _ => {
                    let celsius = attr("temperature")
                        .and_then(|text| text.trim().parse::<f64>().ok())
                        .unwrap_or(25.0);
                    ((celsius + 20.0) / 120.0).clamp(0.0, 1.0)
                }
            };
            Some(Model::SensorDivider {
                ao: net(pin(&["AO"])),
                reference: net(pin(&["VCC", "V+", "Vdd", "VDD"]))
                    .or_else(|| rail_net(rail_nets, Rail::V33)),
                ground: net(pin(&["GND", "G"])).or_else(|| rail_net(rail_nets, Rail::Gnd)),
                fraction,
                total_ohms: SENSOR_OHMS,
            })
        }
        "photoresistor-sensor" => {
            let fraction = match state() {
                Some(PartState::Knob { permille }) => f64::from(permille) / 1000.0,
                _ => attr("light")
                    .and_then(|text| text.trim().parse::<f64>().ok())
                    .map_or(0.5, |light| (light / 1000.0).clamp(0.0, 1.0)),
            };
            Some(Model::SensorDivider {
                ao: net(pin(&["AO"])),
                reference: net(pin(&["VCC", "V+", "Vdd", "VDD"]))
                    .or_else(|| rail_net(rail_nets, Rail::V33)),
                ground: net(pin(&["GND", "G"])).or_else(|| rail_net(rail_nets, Rail::Gnd)),
                fraction,
                total_ohms: SENSOR_OHMS,
            })
        }
        "bjt" => {
            // The solver's Ebers-Moll model is NPN. A PNP device is not the
            // mirror of these equations, so leave it unsolved rather than
            // compute a wrong operating point.
            if attr("polarity").is_some_and(|polarity| polarity.eq_ignore_ascii_case("pnp")) {
                return None;
            }
            let beta = attr("beta")
                .and_then(|text| text.trim().parse::<f64>().ok())
                .unwrap_or(100.0);
            let vbe_on = attr("vbe")
                .or_else(|| attr("vbe_on"))
                .and_then(parse_volts)
                .unwrap_or(0.7);
            let early_voltage = attr("early_voltage")
                .and_then(|text| text.trim().parse::<f64>().ok())
                .unwrap_or(100.0);
            Some(Model::Bjt {
                part: index,
                collector: net(pin(&["C", "collector", "c"])),
                base: net(pin(&["B", "base", "b"])),
                emitter: net(pin(&["E", "emitter", "e"])),
                model: BjtModel {
                    beta,
                    vbe_on,
                    early_voltage,
                },
            })
        }
        "mosfet" => {
            // The solver's level-1 model is NMOS; a P-channel device needs
            // sign-flipped equations the solver does not have.
            if attr("channel").is_some_and(|channel| channel.eq_ignore_ascii_case("p")) {
                return None;
            }
            let threshold = attr("vth")
                .or_else(|| attr("threshold"))
                .and_then(|text| text.trim().parse::<f64>().ok())
                .unwrap_or(2.0);
            let k = attr("k")
                .or_else(|| attr("beta"))
                .and_then(|text| text.trim().parse::<f64>().ok())
                .unwrap_or(1e-2);
            let lambda = attr("lambda")
                .and_then(|text| text.trim().parse::<f64>().ok())
                .unwrap_or(0.0);
            Some(Model::Mosfet {
                part: index,
                drain: net(pin(&["D", "drain", "d"])),
                gate: net(pin(&["G", "gate", "g"])),
                source: net(pin(&["S", "source", "s"])),
                model: MosfetModel {
                    threshold,
                    k,
                    lambda,
                },
            })
        }
        "opamp" | "op-amp" => {
            let gain = attr("gain")
                .and_then(|text| text.trim().parse::<f64>().ok())
                .unwrap_or(1e5);
            let rail_low = attr("rail_low")
                .and_then(|text| text.trim().parse::<f64>().ok())
                .unwrap_or(0.0);
            let rail_high = attr("rail_high")
                .and_then(|text| text.trim().parse::<f64>().ok())
                .unwrap_or(config.v33);
            Some(Model::OpAmp {
                plus: net(pin(&["+", "plus", "IN+", "INP", "P"])),
                minus: net(pin(&["-", "minus", "IN-", "INN", "N"])),
                out: net(pin(&["OUT", "out", "O"])),
                model: OpAmpModel {
                    gain,
                    rail_low,
                    rail_high,
                },
            })
        }
        _ => None,
    }
}

fn rail_net(rail_nets: &BTreeMap<Rail, usize>, rail: Rail) -> Option<usize> {
    rail_nets.get(&rail).copied()
}

/// An LED's forward voltage by colour, in volts. The values are the usual
/// through-hole part's nominal drop at its rated current.
fn led_forward_volts(color: &str) -> f64 {
    match color.to_ascii_lowercase().as_str() {
        "red" => 1.8,
        "green" => 2.0,
        "yellow" => 2.0,
        "orange" => 2.0,
        "blue" => 3.0,
        "white" => 3.2,
        "purple" | "pink" => 3.0,
        "cyan" => 3.0,
        _ => 1.8,
    }
}

/// A Shockley diode that drops `vf` at 20 mA, which is how an LED datasheet
/// states its forward voltage.
fn led_model(color: &str) -> DiodeModel {
    diode_at_forward_volts(led_forward_volts(color))
}

fn diode_at_forward_volts(vf: f64) -> DiodeModel {
    const NOMINAL_AMPS: f64 = 0.02;
    const IDEALITY: f64 = 2.0;
    let scale = (vf / (IDEALITY * THERMAL_VOLTAGE)).exp() - 1.0;
    let saturation_current = if scale > 0.0 {
        NOMINAL_AMPS / scale
    } else {
        1e-14
    };
    DiodeModel::led(saturation_current, IDEALITY)
}

/// Parse a resistance as a diagram writes it: `220`, `10k`, `4k7`, `1M`,
/// `2.2k`, `4R7`. Returns `None` for text that is not a number.
pub(crate) fn parse_resistance(text: &str) -> Option<f64> {
    let cleaned = text.trim().replace([' ', '_'], "");
    let mut text = cleaned.as_str();
    for suffix in ["ohms", "ohm", "Ohms", "Ohm", "OHM", "OHMS", "Ω", "ω"] {
        if let Some(stripped) = text.strip_suffix(suffix) {
            text = stripped.trim();
            break;
        }
    }
    if text.is_empty() {
        return None;
    }
    // Plain decimal or scientific notation, including "220" and "1e3".
    if let Ok(value) = text.parse::<f64>() {
        return (value > 0.0).then_some(value);
    }
    let split = text.find(|c: char| c.is_ascii_alphabetic())?;
    let (leading, rest) = text.split_at(split);
    let mut chars = rest.chars();
    let prefix = chars.next()?;
    let trailing = chars.as_str();
    let factor = match prefix {
        'k' | 'K' => 1e3,
        'M' => 1e6,
        'm' => 1e-3,
        'G' | 'g' => 1e9,
        'R' | 'r' => 1.0,
        _ => return None,
    };
    let value: f64 = if trailing.is_empty() {
        leading.parse().ok()?
    } else {
        format!("{leading}.{trailing}").parse().ok()?
    };
    let ohms = value * factor;
    (ohms > 0.0).then_some(ohms)
}

/// Parse a capacitance as a diagram writes it: `100n`, `100nF`, `4.7u`,
/// `2.2µF`, `10p`, `1mF`. A suffix without a unit letter is the common
/// shorthand and means farads. Returns `None` for text that is not a number.
pub(crate) fn parse_capacitance(text: &str) -> Option<f64> {
    parse_si_value(text, &["F", "f"])
}

/// Parse an inductance as a diagram writes it: `10u`, `10uH`, `4.7mH`,
/// `100nH`. As with [`parse_capacitance`], the trailing `H` is optional.
pub(crate) fn parse_inductance(text: &str) -> Option<f64> {
    parse_si_value(text, &["H", "h"])
}

/// Parse a value with an SI prefix and an optional unit letter.
fn parse_si_value(text: &str, units: &[&str]) -> Option<f64> {
    // Normalise the micro sign freely: diagrams use `u` and the two Unicode
    // spellings interchangeably.
    let cleaned = text.trim().replace([' ', '_'], "").replace(['µ', 'μ'], "u");
    let mut text = cleaned.as_str();
    for unit in units {
        if let Some(stripped) = text.strip_suffix(unit) {
            text = stripped;
            break;
        }
    }
    if text.is_empty() {
        return None;
    }
    if let Ok(value) = text.parse::<f64>() {
        return (value > 0.0).then_some(value);
    }
    let split = text.find(|c: char| c.is_ascii_alphabetic())?;
    let (leading, rest) = text.split_at(split);
    let mut chars = rest.chars();
    let prefix = chars.next()?;
    let trailing = chars.as_str();
    let factor = match prefix {
        'p' | 'P' => 1e-12,
        'n' | 'N' => 1e-9,
        'u' | 'U' => 1e-6,
        'm' => 1e-3,
        'k' | 'K' => 1e3,
        'M' => 1e6,
        'G' | 'g' => 1e9,
        _ => return None,
    };
    let value: f64 = if trailing.is_empty() {
        leading.parse().ok()?
    } else {
        format!("{leading}.{trailing}").parse().ok()?
    };
    let value = value * factor;
    (value > 0.0).then_some(value)
}

/// Parse a voltage as a diagram writes it: `5`, `3.3`, `5V`.
fn parse_volts(text: &str) -> Option<f64> {
    let text = text.trim().trim_end_matches(['V', 'v']);
    text.trim().parse().ok()
}

/// The catalog writes a potentiometer's initial position as 0–100 percent.
fn parse_percent(text: &str) -> f64 {
    text.trim()
        .parse::<f64>()
        .map_or(0.5, |percent| (percent / 100.0).clamp(0.0, 1.0))
}

/// Union-find over net indices plus one sentinel for ground.
struct DisjointSet {
    parent: Vec<usize>,
}

impl DisjointSet {
    fn new(len: usize) -> Self {
        Self {
            parent: (0..len).collect(),
        }
    }

    fn find(&mut self, mut index: usize) -> usize {
        while self.parent[index] != index {
            self.parent[index] = self.parent[self.parent[index]];
            index = self.parent[index];
        }
        index
    }

    fn union(&mut self, a: usize, b: usize) {
        let (a, b) = (self.find(a), self.find(b));
        if a != b {
            self.parent[a.max(b)] = a.min(b);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn resistance_text_uses_electronics_notation() {
        assert_eq!(parse_resistance("220"), Some(220.0));
        assert_eq!(parse_resistance("10k"), Some(10_000.0));
        assert_eq!(parse_resistance("4k7"), Some(4_700.0));
        assert_eq!(parse_resistance("4K7"), Some(4_700.0));
        assert_eq!(parse_resistance("2.2k"), Some(2_200.0));
        assert_eq!(parse_resistance("1M"), Some(1_000_000.0));
        assert_eq!(parse_resistance("4R7"), Some(4.7));
        assert_eq!(parse_resistance("1e3"), Some(1_000.0));
        assert_eq!(parse_resistance("10 k"), Some(10_000.0));
        assert_eq!(parse_resistance("4k7Ω"), Some(4_700.0));
        assert_eq!(parse_resistance("nonsense"), None);
        assert_eq!(parse_resistance("0"), None);
    }

    #[test]
    fn capacitance_and_inductance_text_accept_si_prefixes() {
        // The prefix multiplication is not exact in binary, so compare to a
        // relative tolerance rather than bit-for-bit.
        let close = |actual: Option<f64>, expected: f64| {
            let actual = actual.expect("the text parses");
            assert!(
                (actual - expected).abs() <= expected.abs() * 1e-12,
                "{actual:e} F/H is not {expected:e}"
            );
        };
        close(parse_capacitance("100n"), 100e-9);
        close(parse_capacitance("100nF"), 100e-9);
        close(parse_capacitance("4.7u"), 4.7e-6);
        close(parse_capacitance("2.2µF"), 2.2e-6);
        close(parse_capacitance("10p"), 10e-12);
        close(parse_capacitance("1mF"), 1e-3);
        assert_eq!(parse_capacitance("nonsense"), None);
        close(parse_inductance("10uH"), 10e-6);
        close(parse_inductance("4.7mH"), 4.7e-3);
        close(parse_inductance("100n"), 100e-9);
    }

    #[test]
    fn an_led_model_drops_its_forward_voltage_at_the_rated_current() {
        let model = led_model("green");
        let vf = 2.0 * THERMAL_VOLTAGE * (0.02 / model.saturation_current + 1.0).ln();
        assert!((vf - 2.0).abs() < 1e-9, "{vf}");
    }
}