nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
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
//! Additional complete supplied-model requests; arithmetic remains in Compositions.
use super::{Domain, ElectricalQueries};
use crate::plugins::{integer_queries, model_coordinates};
use crate::{Context, Error, Outcome, re};
use num_rational::BigRational;
use num_traits::{One, Signed, ToPrimitive, Zero};
use std::cmp::Ordering;

fn current_target(target: &str) -> String {
    let Some(c) = re!(r"(?i)^(pico|nano|micro|milli|kilo|mega|giga|tera)?(?:amps?|amperes?)$")
        .captures(target.trim())
    else {
        return target.to_owned();
    };
    let prefix = match c
        .get(1)
        .map(|prefix| prefix.as_str().to_ascii_lowercase())
        .as_deref()
    {
        Some("pico") => "p",
        Some("nano") => "n",
        Some("micro") => "µ",
        Some("milli") => "m",
        Some("kilo") => "k",
        Some("mega") => "M",
        Some("giga") => "G",
        Some("tera") => "T",
        _ => "",
    };
    format!("{prefix}A")
}

impl ElectricalQueries {
    fn network_label(label: &str) -> bool {
        matches!(
            label,
            "total resistance"
                | "source current"
                | "parallel network voltage"
                | "first parallel resistor voltage"
                | "second parallel resistor voltage"
                | "series resistor voltage"
                | "first parallel resistor current"
                | "second parallel resistor current"
                | "series resistor power"
                | "first parallel resistor power"
                | "second parallel resistor power"
                | "total power"
                | "source power"
        )
    }
    const MIXED_LABELS: [&'static str; 8] = [
        "equivalent resistance",
        "source current",
        "series resistor current",
        "series resistor voltage",
        "first parallel resistor current",
        "first parallel resistor voltage",
        "second parallel resistor current",
        "second parallel resistor voltage",
    ];
    const MIXED_POWER_LABELS: [&'static str; 7] = [
        "total resistance",
        "source current",
        "series resistor voltage",
        "parallel network voltage",
        "series resistor power",
        "first parallel resistor power",
        "second parallel resistor power",
    ];
    fn mixed_network(
        &self,
        series: &str,
        first: &str,
        second: &str,
        supply: &str,
        context: &Context,
    ) -> Result<(String, String, String, String, String, String), Error> {
        let series = self.role(series, "Ω", Domain::Nonnegative, context)?;
        let first = self.role(first, "Ω", Domain::Positive, context)?;
        let second = self.role(second, "Ω", Domain::Positive, context)?;
        let supply = self.role(supply, "V", Domain::Signed, context)?;
        let parallel = format!("(1/(1/{first}+1/{second}))");
        let total = self.role(
            &format!("{series}+{parallel}"),
            "Ω",
            Domain::Positive,
            context,
        )?;
        Ok((series, first, second, supply, parallel, total))
    }
    fn transformer_turns(
        &self,
        primary: &str,
        secondary: &str,
    ) -> Result<(num_bigint::BigInt, num_bigint::BigInt), Error> {
        let primary = integer_queries::value(primary)?;
        let secondary = integer_queries::value(secondary)?;
        if !primary.is_positive() || !secondary.is_positive() {
            return Err(Error("invalid_physical_value".into()));
        }
        Ok((primary, secondary))
    }

    fn network_projection(
        &self,
        series_input: &str,
        first_input: &str,
        second_input: &str,
        supply_input: &str,
        goals: &str,
        context: &Context,
    ) -> Result<String, Error> {
        let (series, first, second, voltage, parallel, total) = self.mixed_network(
            series_input,
            first_input,
            second_input,
            supply_input,
            context,
        )?;
        let current = format!("{voltage}/{total}");
        let network_voltage = format!("({current})*{parallel}");
        let requested = re!(r"(?i),\s*(?:and\s+)?|\s+and\s+")
            .split(goals)
            .map(str::trim)
            .collect::<Vec<_>>();
        let mut fields = Vec::new();
        for goal in requested {
            let mut add = |label, unit, expression| fields.push((label, unit, expression));
            match goal.to_ascii_lowercase().as_str() {
                "total resistance"
                | "equivalent resistance"
                | "total equivalent resistance"
                | "circuit resistance" => add("total resistance", "Ω", total.clone()),
                "source current"
                | "supply current"
                | "current from the source"
                | "total current" => add("source current", "A", current.clone()),
                "parallel-section voltage"
                | "parallel network voltage"
                | "voltage on the parallel network"
                | "voltage across the parallel pair"
                | "branch voltage" => add("parallel network voltage", "V", network_voltage.clone()),
                "voltage across each branch" | "voltage across both branches" => {
                    add(
                        "first parallel resistor voltage",
                        "V",
                        network_voltage.clone(),
                    );
                    add(
                        "second parallel resistor voltage",
                        "V",
                        network_voltage.clone(),
                    );
                }
                "branch currents"
                | "current in each branch"
                | "currents in both branches"
                | "both branch currents"
                | "each parallel-branch current"
                | "current through each branch"
                | "currents" => {
                    add(
                        "first parallel resistor current",
                        "A",
                        format!("({network_voltage})/{first}"),
                    );
                    add(
                        "second parallel resistor current",
                        "A",
                        format!("({network_voltage})/{second}"),
                    );
                }
                "total power" | "total resistor power" => {
                    add("total power", "W", format!("{voltage}*{current}"))
                }
                "source power" => add("source power", "W", format!("{voltage}*{current}")),
                "power in every resistor" | "power dissipated by each resistor" => {
                    add(
                        "series resistor power",
                        "W",
                        format!("square({current})*{series}"),
                    );
                    add(
                        "first parallel resistor power",
                        "W",
                        format!("square({network_voltage})/{first}"),
                    );
                    add(
                        "second parallel resistor power",
                        "W",
                        format!("square({network_voltage})/{second}"),
                    );
                }
                "power in the series resistor" => add(
                    "series resistor power",
                    "W",
                    format!("square({current})*{series}"),
                ),
                _ => {
                    let reference = re!(r"(?i)^power in the (.+?) resistor$")
                        .captures(goal)
                        .ok_or_else(|| Error("invalid_expression".into()))?;
                    if self.same_role(&reference[1], series_input, "Ω", context)? {
                        add(
                            "series resistor power",
                            "W",
                            format!("square({current})*{series}"),
                        );
                    } else if self.same_role(&reference[1], first_input, "Ω", context)? {
                        add(
                            "first parallel resistor power",
                            "W",
                            format!("square({network_voltage})/{first}"),
                        );
                    } else if self.same_role(&reference[1], second_input, "Ω", context)? {
                        add(
                            "second parallel resistor power",
                            "W",
                            format!("square({network_voltage})/{second}"),
                        );
                    } else {
                        return Err(Error("invalid_physical_value".into()));
                    }
                }
            }
        }
        if fields.len() < 5 || fields.len() > 11 {
            return Err(Error("invalid_expression".into()));
        }
        self.report(&fields, context)
    }
    fn elapsed_charge_duration(&self, input: &str, context: &Context) -> Result<String, Error> {
        if let Some(c) =
            re!(r"(?i)^(.+?)\s+(hours?|hrs?|h)\s+(?:and\s+)?(.+?)\s+(minutes?|mins?|min)$")
                .captures(input.trim())
        {
            let hours = self.role(
                &format!("{} {}", &c[1], &c[2]),
                "seconds",
                Domain::Nonnegative,
                context,
            )?;
            let minutes = self.role(
                &format!("{} {}", &c[3], &c[4]),
                "seconds",
                Domain::Nonnegative,
                context,
            )?;
            return Ok(format!("({hours} + {minutes})"));
        }
        self.role(input, "seconds", Domain::Nonnegative, context)
    }

    fn capacitor_coefficient(input: &str) -> String {
        // A written coefficient times a power of ten is one authored scalar.
        // Keep its exponent attached to the scalar before the typed unit parser.
        let input = re!(r"(?P<coefficient>[+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*[×*]\s*10\s*\^\s*(?P<exponent>[+-]?\d+)")
            .replace_all(input.trim(), "${coefficient}e${exponent}");
        input.replace('×', "*")
    }

    fn capacitor_input(input: &str) -> String {
        let input = Self::capacitor_coefficient(input);
        input
            .strip_suffix(" F")
            .map_or_else(|| input.clone(), |value| format!("{value} farads"))
    }

    fn capacitor_role(&self, input: &str, context: &Context) -> Result<String, Error> {
        // F is capacitance only in a complete capacitor role, not a global unit alias.
        let input = Self::capacitor_input(input);
        self.role(&input, "farads", Domain::Positive, context)
    }

    fn same_role(
        &self,
        left: &str,
        right: &str,
        unit: &str,
        context: &Context,
    ) -> Result<bool, Error> {
        // Validate the demanded role, then share typed equality's bounded roundoff policy.
        self.compositions.quantity_value(left, unit, context)?;
        self.compositions.quantity_value(right, unit, context)?;
        Ok(self.compositions.quantity_order(left, right, context)? == Ordering::Equal)
    }

    fn require_branch(
        &self,
        selected: &str,
        branches: &[&str],
        context: &Context,
    ) -> Result<(), Error> {
        for branch in branches {
            if self.same_role(selected, branch, "Ω", context)? {
                return Ok(());
            }
        }
        Err(Error("invalid_physical_value".into()))
    }

    fn require_consistent(
        &self,
        stated: &str,
        implied: &str,
        unit: &str,
        context: &Context,
    ) -> Result<(), Error> {
        if self.same_role(stated, implied, unit, context)? {
            Ok(())
        } else {
            Err(Error("invalid_physical_value".into()))
        }
    }

    fn require_elapsed_equivalence(
        &self,
        left: &str,
        right: &str,
        context: &Context,
    ) -> Result<(), Error> {
        let left_coordinate =
            model_coordinates::read(left, "seconds", &self.compositions, context)?;
        let right_coordinate =
            model_coordinates::read(right, "seconds", &self.compositions, context)?;
        if left_coordinate.authored && right_coordinate.authored {
            if left_coordinate.value == right_coordinate.value {
                Ok(())
            } else {
                Err(Error("invalid_physical_value".into()))
            }
        } else {
            self.require_consistent(left, right, "seconds", context)
        }
    }

    fn report(&self, fields: &[(&str, &str, String)], context: &Context) -> Result<String, Error> {
        let mixed = fields.len() == Self::MIXED_LABELS.len()
            && fields
                .iter()
                .zip(Self::MIXED_LABELS)
                .all(|(field, label)| field.0 == label);
        let mixed_power = fields.len() == Self::MIXED_POWER_LABELS.len()
            && fields
                .iter()
                .zip(Self::MIXED_POWER_LABELS)
                .all(|(field, label)| field.0 == label);
        let projection = (5..=11).contains(&fields.len())
            && fields
                .iter()
                .all(|(label, _, _)| Self::network_label(label))
            && {
                let mut labels = fields.iter().map(|field| field.0).collect::<Vec<_>>();
                labels.sort_unstable();
                labels.dedup();
                labels.len() == fields.len()
            };
        if fields.len() > 4 && !mixed && !mixed_power && !projection {
            return Err(Error("invalid_expression".into()));
        }
        for (label, target, expression) in fields {
            self.validate_report_field(label, target, expression, context)?;
        }
        let result = format!(
            "{}({})",
            if mixed {
                "electrical_mixed_summary"
            } else if mixed_power {
                "electrical_power_summary"
            } else if projection {
                "electrical_network_projection"
            } else {
                "electrical_summary"
            },
            fields
                .iter()
                .map(|(label, target, expression)| {
                    // Natural current reports use SI symbols without changing the
                    // requested prefix, field order, or standard unit presentation.
                    let target = if matches!(
                        *label,
                        "current" | "first branch current" | "second branch current"
                    ) {
                        current_target(target)
                    } else {
                        target.to_string()
                    };
                    format!("{label}|{target}|{expression}")
                })
                .collect::<Vec<_>>()
                .join(";")
        );
        if result.len() > 4096 {
            return Err(Error("invalid_expression".into()));
        }
        Ok(result)
    }

    fn validate_report_field(
        &self,
        label: &str,
        target: &str,
        expression: &str,
        context: &Context,
    ) -> Result<(), Error> {
        let reference = match label {
            "current"
            | "source current"
            | "total current"
            | "first branch current"
            | "second branch current"
            | "series resistor current"
            | "first parallel resistor current"
            | "second parallel resistor current"
            | "secondary current" => "A",
            "power"
            | "load power"
            | "source power"
            | "combined power"
            | "total power"
            | "series resistor power"
            | "first parallel resistor power"
            | "second parallel resistor power" => "W",
            "voltage"
            | "terminal voltage"
            | "first resistor voltage"
            | "second resistor voltage"
            | "series resistor voltage"
            | "parallel network voltage"
            | "first parallel resistor voltage"
            | "second parallel resistor voltage"
            | "secondary voltage" => "V",
            "secondary RMS voltage" => "V",
            "resistance"
            | "total resistance"
            | "equivalent resistance"
            | "effective resistance" => "Ω",
            "energy" => "J",
            "charge" => "coulombs",
            "capacitance" => "farads",
            "time constant" => "seconds",
            "standard uncertainty" => "A",
            _ => {
                let percentage = label
                    .strip_prefix("time to ")
                    .and_then(|value| value.strip_suffix('%'))
                    .ok_or_else(|| Error("invalid_expression".into()))?;
                let (n, d) = integer_queries::ratio_value(percentage)?;
                let percentage = model_coordinates::bounded(BigRational::new(n, d))?;
                if percentage < BigRational::zero()
                    || percentage >= BigRational::from_integer(100.into())
                {
                    return Err(Error("invalid_physical_value".into()));
                }
                "seconds"
            }
        };
        self.compositions
            .quantity_value(&format!("1 {target}"), reference, context)?;
        self.compositions
            .quantity_value(expression, target, context)?;
        Ok(())
    }

    pub(super) fn evaluate_models(&self, input: &str, context: &Context) -> Outcome {
        if let Some((inner, mixed, mixed_power, projection)) = input
            .strip_prefix("electrical_mixed_summary(")
            .and_then(|s| s.strip_suffix(')'))
            .map(|inner| (inner, true, false, false))
            .or_else(|| {
                input
                    .strip_prefix("electrical_power_summary(")
                    .and_then(|s| s.strip_suffix(')'))
                    .map(|inner| (inner, false, true, false))
            })
            .or_else(|| {
                input
                    .strip_prefix("electrical_network_projection(")
                    .and_then(|s| s.strip_suffix(')'))
                    .map(|inner| (inner, false, false, true))
            })
            .or_else(|| {
                input
                    .strip_prefix("electrical_summary(")
                    .and_then(|s| s.strip_suffix(')'))
                    .map(|inner| (inner, false, false, false))
            })
        {
            return Some((|| {
                if input.len() > 4096 {
                    return Err(Error("invalid_expression".into()));
                }
                let fields = inner.split(';').collect::<Vec<_>>();
                if (mixed
                    && (fields.len() != Self::MIXED_LABELS.len()
                        || fields
                            .iter()
                            .zip(Self::MIXED_LABELS)
                            .any(|(field, label)| field.split('|').next() != Some(label))))
                    || (mixed_power
                        && (fields.len() != Self::MIXED_POWER_LABELS.len()
                            || fields
                                .iter()
                                .zip(Self::MIXED_POWER_LABELS)
                                .any(|(field, label)| field.split('|').next() != Some(label))))
                    || (projection
                        && (!(5..=11).contains(&fields.len()) || {
                            let mut labels = fields
                                .iter()
                                .map(|field| field.split('|').next().unwrap_or(""))
                                .collect::<Vec<_>>();
                            if labels.iter().any(|label| !Self::network_label(label)) {
                                true
                            } else {
                                labels.sort_unstable();
                                labels.dedup();
                                labels.len() != fields.len()
                            }
                        }))
                    || (!mixed && !mixed_power && !projection && !(2..=4).contains(&fields.len()))
                {
                    return Err(Error("invalid_expression".into()));
                }
                let mut output = Vec::new();
                for field in fields {
                    let parts = field.split('|').collect::<Vec<_>>();
                    if parts.len() != 3 {
                        return Err(Error("invalid_expression".into()));
                    }
                    let (label, target, expression) = (parts[0], parts[1], parts[2]);
                    self.validate_report_field(label, target, expression, context)?;
                    let display =
                        self.calculate(&format!("({expression}) in {target}"), context)?;
                    output.push(format!("{label}: {display}"));
                }
                Ok(output.join("; "))
            })());
        }
        let (kind, inner) = if let Some(inner) = input
            .strip_prefix("electrical_battery_check(")
            .and_then(|s| s.strip_suffix(')'))
        {
            ("battery", inner)
        } else {
            let inner = input
                .strip_prefix("electrical_power_triangle(")
                .and_then(|s| s.strip_suffix(')'))?;
            ("triangle", inner)
        };
        Some((|| {
            let args = super::super::named_quantities::function_arguments(inner, false)?;
            if kind == "battery" && args.len() == 3 {
                let v = self.role(args[0], "V", Domain::Nonnegative, context)?;
                let i = self.role(args[1], "A", Domain::Nonnegative, context)?;
                let r = self.role(args[2], "Ω", Domain::Positive, context)?;
                self.require_consistent(&v, &format!("{i} * {r}"), "V", context)?;
                let power = self.calculate(&format!("({v} * {i}) in W"), context)?;
                Ok(format!("battery power: {power}; consistent: true"))
            } else if kind == "triangle" && args.len() == 2 {
                let s = self.role(args[0], "VA", Domain::Positive, context)?;
                let p = self.role(args[1], "W", Domain::Nonnegative, context)?;
                if self.compositions.quantity_order(&p, &s, context)? == Ordering::Greater {
                    return Err(Error("invalid_physical_value".into()));
                }
                let factor = self.calculate(&format!("{p} / {s}"), context)?;
                let reactive =
                    self.calculate(&format!("sqrt(square({s}) - square({p})) in var"), context)?;
                Ok(format!(
                    "power factor: {factor}; reactive power magnitude: {reactive}"
                ))
            } else {
                Err(Error("invalid_expression".into()))
            }
        })())
    }

    pub(super) fn lower_models(
        &self,
        input: &str,
        context: &Context,
    ) -> Result<Option<String>, Error> {
        if let Some(c) = re!(r"(?i)^a sensor reports (.+?) with independent standard uncertainty (.+?), and a (.+?)-ohm resistor has independent standard uncertainty (.+?); using I\s*=\s*V\s*/\s*R and first-order uncertainty propagation, report current and its standard uncertainty$").captures(input) {
            let resistance_input = format!("{} ohms", &c[3]);
            let voltage = self.role(&c[1], "V", Domain::Signed, context)?;
            self.role(&c[2], "V", Domain::Nonnegative, context)?;
            let resistance = self.role(&resistance_input, "Ω", Domain::Positive, context)?;
            self.role(&c[4], "Ω", Domain::Nonnegative, context)?;

            let v = model_coordinates::read(&c[1], "V", &self.compositions, context)?;
            let uv = model_coordinates::read(&c[2], "V", &self.compositions, context)?;
            let r = model_coordinates::read(&resistance_input, "Ω", &self.compositions, context)?;
            let ur = model_coordinates::read(&c[4], "Ω", &self.compositions, context)?;
            let current = model_coordinates::bounded(&v.value / &r.value)?;
            let voltage_term = model_coordinates::bounded(&uv.value / &r.value)?;
            let resistance_term = model_coordinates::bounded(
                &v.value * &ur.value / (&r.value * &r.value),
            )?;
            let variance = model_coordinates::bounded(
                model_coordinates::bounded(&voltage_term * &voltage_term)?
                    + model_coordinates::bounded(&resistance_term * &resistance_term)?,
            )?;
            let uncertainty = model_coordinates::computed_root(variance, |expression| {
                self.compositions.quantity_value(expression, "1", context)
            })?;
            let uncertainty_float = uncertainty
                .to_f64()
                .filter(|value| value.is_finite())
                .ok_or_else(|| Error("numeric_overflow".into()))?;
            if !uncertainty.is_zero() && uncertainty_float == 0.0 {
                return Err(Error("numeric_underflow".into()));
            }
            let current_expression = if v.authored && r.authored {
                format!("(rational({},{}) A)", current.numer(), current.denom())
            } else {
                format!("{voltage}/{resistance}")
            };
            return self.report(&[
                ("current", "A", current_expression),
                ("standard uncertainty", "A", format!("real({uncertainty_float:e}) A")),
            ], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^an ideal transformer has (.+?) primary turns, (.+?) secondary turns, and primary voltage (.+?) AC\. (?:find|calculate) secondary voltage and secondary current if primary current is (.+)$")
            .captures(input)
        {
            let (primary, secondary) = self.transformer_turns(&c[1], &c[2])?;
            let voltage = self.role(&c[3], "V", Domain::Nonnegative, context)?;
            let current = self.role(&c[4], "A", Domain::Nonnegative, context)?;
            return self.report(
                &[
                    (
                        "secondary voltage",
                        "V",
                        format!("{voltage} * rational({secondary},{primary})"),
                    ),
                    (
                        "secondary current",
                        "A",
                        format!("{current} * rational({primary},{secondary})"),
                    ),
                ],
                context,
            ).map(Some);
        }
        if let Some(c) = re!(r"(?i)^an ideal transformer has (.+?) primary turns, (.+?) secondary turns, and (.+?) RMS across the primary\. use Vs\s*/\s*Vp\s*=\s*Ns\s*/\s*Np to find the secondary RMS voltage; with a (.+?) resistive load, find secondary current and load power$").captures(input) {
            let (primary, secondary) = self.transformer_turns(&c[1], &c[2])?;
            let voltage = self.role(&c[3], "V", Domain::Nonnegative, context)?;
            let load = self.role(&c[4], "Ω", Domain::Positive, context)?;
            let secondary_voltage = format!("{voltage}*rational({secondary},{primary})");
            return self.report(&[
                ("secondary RMS voltage", "V", secondary_voltage.clone()),
                ("secondary current", "A", format!("({secondary_voltage})/{load}")),
                ("load power", "W", format!("square({secondary_voltage})/{load}")),
            ], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a capacitor of (.+?) is charged through a (.+?) resistor\. (?:calculate|find) the RC time constant in (seconds|s) and the time to reach (.+?) of (?:the )?final voltage, using t\s*=\s*-\s*RC\s*\*\s*ln\s*\(\s*1\s*-\s*(.+?)\s*\)$")
            .captures(input)
        {
            let invalid = || Error("invalid_expression".into());
            let stated = re!(r"(?i)^(.+?)(?:%|\s+percent)$")
                .captures(c[4].trim())
                .ok_or_else(invalid)?;
            let ratio = |value: &str| {
                let (numerator, denominator) = integer_queries::ratio_value(value)?;
                model_coordinates::bounded(BigRational::new(numerator, denominator))
            };
            let fraction = ratio(&stated[1])? / BigRational::from_integer(100.into());
            let authored = ratio(&c[5])?;
            if fraction != authored {
                return Err(Error("invalid_physical_value".into()));
            }
            if fraction < BigRational::zero() || fraction >= BigRational::one() {
                return Err(Error("invalid_physical_value".into()));
            }
            let capacitance = self.capacitor_role(&c[1], context)?;
            // The resistor role alone admits the ordinary hyphenated SI prefix.
            let resistor = c[2].replace("-ohm", "ohm");
            let resistance = self.role(&resistor, "Ω", Domain::Positive, context)?;
            let r = model_coordinates::read(&resistance, "Ω", &self.compositions, context)?;
            let cap = model_coordinates::read(&capacitance, "farads", &self.compositions, context)?;
            let tau = model_coordinates::bounded(r.value * cap.value)?;
            let tau_float = tau.to_f64().ok_or_else(|| Error("numeric_overflow".into()))?;
            let mut time_scale = tau_float;
            let log = if fraction.is_zero() {
                0.0
            } else if fraction < BigRational::new(1.into(), 2.into()) {
                let part = fraction.to_f64().ok_or_else(|| Error("numeric_underflow".into()))?;
                if part.is_normal() {
                    -(-part).ln_1p()
                } else {
                    // For a subnormal fraction, -ln(1-f)/f rounds to one.
                    // Multiply exact scales first so a finite time survives.
                    time_scale = model_coordinates::bounded(&tau * &fraction)?
                        .to_f64().ok_or_else(|| Error("numeric_overflow".into()))?;
                    1.0
                }
            } else {
                let remaining = BigRational::one() - &fraction;
                if let Some(value) = remaining.to_f64().filter(|value| value.is_normal()) {
                    -value.ln()
                } else {
                    // An exact positive complement can be smaller than binary64
                    // while its logarithm is finite. Normalize before the kernel.
                    let exponent = remaining.numer().bits() as i64 - remaining.denom().bits() as i64;
                    let power = num_bigint::BigInt::one() << exponent.unsigned_abs() as usize;
                    let scale = if exponent < 0 {
                        BigRational::from_integer(power)
                    } else {
                        BigRational::new(1.into(), power)
                    };
                    let normalized = model_coordinates::bounded(remaining * scale)?
                        .to_f64().ok_or_else(|| Error("numeric_overflow".into()))?;
                    -normalized.ln() - exponent as f64 * std::f64::consts::LN_2
                }
            };
            let charging_time = time_scale * log;
            if !charging_time.is_finite() {
                return Err(Error("numeric_overflow".into()));
            }
            if !fraction.is_zero() && charging_time == 0.0 {
                return Err(Error("numeric_underflow".into()));
            }
            let label = format!("time to {}%", stated[1].trim());
            return self.report(
                &[
                    ("time constant", "s", format!("{resistance} * {capacitance}")),
                    (&label, "s", format!("real({charging_time:e}) s")),
                ],
                context,
            ).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a capacitor stores E\s*=\s*CV(?:²|\^2)\s*/\s*2; use C\s*=\s*(.+?) and V\s*=\s*(.+?) to give the finite energy in (.+)$").captures(input) {
            let capacitance = self.capacitor_role(&c[1], context)?;
            let voltage_input = Self::capacitor_coefficient(&c[2]);
            let voltage = self.role(&voltage_input, "V", Domain::Nonnegative, context)?;
            self.compositions.quantity_value(&format!("1 {}", &c[3]), "J", context)?;
            let exact_capacitance = model_coordinates::read(
                &Self::capacitor_input(&c[1]), "farads", &self.compositions, context,
            )?;
            let exact_voltage = model_coordinates::read(
                &voltage_input, "V", &self.compositions, context,
            )?;
            let energy = if exact_capacitance.authored && exact_voltage.authored {
                let joules = model_coordinates::bounded(
                    exact_capacitance.value * exact_voltage.value.clone() * exact_voltage.value
                        / BigRational::from_integer(2.into()),
                )?;
                format!("(rational({},{}) J)", joules.numer(), joules.denom())
            } else {
                format!("({capacitance}*square({voltage})/2)")
            };
            self.compositions.quantity_value(&energy, "J", context)?;
            return Ok(Some(format!("{energy} in {}", &c[3])));
        }
        macro_rules! q {
            ($c:ident, $n:literal, $unit:literal, $domain:ident) => {
                self.role(&$c[$n], $unit, Domain::$domain, context)?
            };
        }
        macro_rules! rule {
            ($pattern:literal, $target:expr, $c:ident, $formula:expr) => {
                if let Some($c) = re!($pattern).captures(input) {
                    let expression = $formula;
                    return Ok(Some(format!("({expression}) in {}", $target)));
                }
            };
        }
        if let Some(c) = re!(r"(?i)^a battery supplies (.+?) for (.+?)\. how many (.+?) and (.+?) of charge is that, using (.+?)\s*=\s*(.+)$")
            .captures(input)
        {
            let charge_target = |target: &str| {
                let target = target.trim().to_ascii_lowercase().replace('-', " ");
                match target.as_str() {
                    "amp hour" | "amp hours" | "ah" => Some("Ah"),
                    "coulomb" | "coulombs" => Some("coulombs"),
                    _ => None,
                }
            };
            let first = charge_target(&c[3])
                .ok_or_else(|| Error("invalid_expression".into()))?;
            let second = charge_target(&c[4])
                .filter(|target| *target != first)
                .ok_or_else(|| Error("invalid_expression".into()))?;
            self.require_elapsed_equivalence(&c[5], &c[6], context)?;
            let current = q!(c, 1, "A", Nonnegative);
            let duration = self.elapsed_charge_duration(&c[2], context)?;
            let charge = format!("{current} * {duration}");
            return self.report(
                &[("charge", first, charge.clone()), ("charge", second, charge)],
                context,
            ).map(Some);
        }
        // The stated DC equations are part of this request, and the goal order is power first.
        if let Some(c) = re!(r"(?i)^for the model P\s*=\s*V\s*\^\s*2\s*/\s*R with V\s*=\s*(.+?) and R\s*=\s*(.+?), calculate power and the current given I\s*=\s*V\s*/\s*R$").captures(input) {
            let voltage = q!(c, 1, "V", Nonnegative);
            let resistance = q!(c, 2, "Ω", Positive);
            return self.report(&[("power", "W", format!("square({voltage}) / {resistance}")),
                ("current", "A", format!("{voltage} / {resistance}"))], context).map(Some);
        }
        // The final unit applies to all three stated resistances, as in a measured list.
        if let Some(c) = re!(r"(?i)^three resistors (.+?), (.+?), and (.+?) ohms are in parallel across an ideal (.+?) source; report equivalent resistance, total current, and total power$").captures(input) {
            let first = self.role(&format!("{} ohms", &c[1]), "Ω", Domain::Positive, context)?;
            let second = self.role(&format!("{} ohms", &c[2]), "Ω", Domain::Positive, context)?;
            let third = self.role(&format!("{} ohms", &c[3]), "Ω", Domain::Positive, context)?;
            let voltage = q!(c, 4, "V", Nonnegative);
            let equivalent = format!("1 / (1 / {first} + 1 / {second} + 1 / {third})");
            let current = format!("{voltage} / ({equivalent})");
            return self.report(&[("equivalent resistance", "Ω", equivalent),
                ("total current", "A", current.clone()),
                ("total power", "W", format!("{voltage} * ({current})"))], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) source is connected across a (.+?) resistor; what current flows in (.+?) and what power is dissipated in (.+)$").captures(input) {
            let voltage = q!(c, 1, "V", Nonnegative);
            let resistance = q!(c, 2, "Ω", Positive);
            let current = format!("{voltage}/{resistance}");
            return self.report(&[("current", &c[3], current.clone()),
                ("power", &c[4], format!("{voltage}*({current})"))], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) battery supplies a (.+?) load for (.+?); how much energy is used in (.+?) and (.+?), given (.+?)\s*=\s*(.+)$").captures(input) {
            let voltage = q!(c, 1, "V", Nonnegative);
            let current = q!(c, 2, "A", Nonnegative);
            let duration = q!(c, 3, "seconds", Nonnegative);
            // A supplied energy equivalence is evidence, never a local registry override.
            self.require_consistent(&c[6], &c[7], "J", context)?;
            let energy = format!("{voltage}*{current}*{duration}");
            let target = |input: &str| {
                let name = input.replace('-', " ");
                self.compositions.units.unit(&name).map(|unit| unit.symbol)
                    .unwrap_or(name)
            };
            return self.report(&[("energy", &target(&c[4]), energy.clone()),
                ("energy", &target(&c[5]), energy)], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) resistor and a (.+?) resistor are in series across (.+?); (?:find|calculate) total resistance, current, and voltage across each$").captures(input) {
            let first = q!(c, 1, "Ω", Nonnegative);
            let second = q!(c, 2, "Ω", Nonnegative);
            let voltage = q!(c, 3, "V", Signed);
            let total = self.role(&format!("{first}+{second}"), "Ω", Domain::Positive, context)?;
            let current = format!("{voltage}/{total}");
            return self.report(&[("total resistance", "Ω", total), ("current", "A", current.clone()),
                ("first resistor voltage", "V", format!("({current})*{first}")),
                ("second resistor voltage", "V", format!("({current})*{second}"))], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) source is connected to (.+?) and (.+?) in series\. (?:find|calculate|give) equivalent resistance, circuit current, and voltage drop across each resistor$").captures(input) {
            let voltage = q!(c, 1, "V", Signed);
            let first = q!(c, 2, "Ω", Nonnegative);
            let second = q!(c, 3, "Ω", Nonnegative);
            let total = self.role(&format!("{first}+{second}"), "Ω", Domain::Positive, context)?;
            let current = format!("{voltage}/{total}");
            return self.report(&[("equivalent resistance", "Ω", total),
                ("total current", "A", current.clone()),
                ("first resistor voltage", "V", format!("({current})*{first}")),
                ("second resistor voltage", "V", format!("({current})*{second}"))], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^two resistors of (.+?) and (.+?) are in parallel across an ideal (.+?) supply\. (?:give|report|find) equivalent resistance, total current, and current through each branch$").captures(input) {
            let first = q!(c, 1, "Ω", Positive);
            let second = q!(c, 2, "Ω", Positive);
            let voltage = q!(c, 3, "V", Signed);
            let equivalent = format!("1/(1/{first}+1/{second})");
            let first_current = format!("{voltage}/{first}");
            let second_current = format!("{voltage}/{second}");
            return self.report(&[("equivalent resistance", "Ω", equivalent),
                ("total current", "A", format!("({first_current})+({second_current})")),
                ("first branch current", "A", first_current),
                ("second branch current", "A", second_current)], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^an ideal (.+?) resistor is in series with a parallel pair of (.+?) and (.+?), supplied by (.+?); calculate equivalent resistance, source current, and the current and voltage for each resistor$").captures(input) {
            let (series, first, second, voltage, parallel, total) =
                self.mixed_network(&c[1], &c[2], &c[3], &c[4], context)?;
            let source_current = format!("{voltage}/{total}");
            let series_voltage = format!("({source_current})*{series}");
            let parallel_voltage = format!("({source_current})*{parallel}");
            return self.report(&[
                ("equivalent resistance", "Ω", total),
                ("source current", "A", source_current.clone()),
                ("series resistor current", "A", source_current),
                ("series resistor voltage", "V", series_voltage),
                ("first parallel resistor current", "A", format!("({parallel_voltage})/{first}")),
                ("first parallel resistor voltage", "V", parallel_voltage.clone()),
                ("second parallel resistor current", "A", format!("({parallel_voltage})/{second}")),
                ("second parallel resistor voltage", "V", parallel_voltage),
            ], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) ideal source drives a (.+?) resistor in series with a parallel network of (.+?) and (.+?) resistors\. find total resistance, source current, voltage across each series element and the parallel network, and power in all three resistors$").captures(input) {
            let (series, first, second, voltage, parallel, total) =
                self.mixed_network(&c[2], &c[3], &c[4], &c[1], context)?;
            let current = format!("{voltage}/{total}");
            let series_voltage = format!("({current})*{series}");
            let network_voltage = format!("({current})*{parallel}");
            return self.report(&[
                ("total resistance", "Ω", total),
                ("source current", "A", current.clone()),
                ("series resistor voltage", "V", series_voltage.clone()),
                ("parallel network voltage", "V", network_voltage.clone()),
                ("series resistor power", "W", format!("square({current})*{series}")),
                ("first parallel resistor power", "W", format!("square({network_voltage})/{first}")),
                ("second parallel resistor power", "W", format!("square({network_voltage})/{second}")),
            ], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^connect a (.+?) ideal supply to a (.+?) resistor in series with parallel (.+?) and (.+?) resistors\. report (.+)$").captures(input) {
            return self.network_projection(&c[2], &c[3], &c[4], &c[1], &c[5], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) ideal source feeds a (.+?) resistor in series with a parallel pair of (.+?) and (.+?) resistors\. find (.+)$").captures(input) {
            return self.network_projection(&c[2], &c[3], &c[4], &c[1], &c[5], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^an ideal (.+?) battery drives a (.+?) series resistor followed by (.+?) and (.+?) resistors in parallel\. calculate (.+)$").captures(input) {
            return self.network_projection(&c[2], &c[3], &c[4], &c[1], &c[5], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^with an ideal (.+?) source, put (.+?) in series with a parallel combination of (.+?) and (.+?)\. determine (.+)$").captures(input) {
            return self.network_projection(&c[2], &c[3], &c[4], &c[1], &c[5], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) ideal source is connected to (.+?) in series with parallel (.+?) and (.+?)\. find (.+)$").captures(input) {
            return self.network_projection(&c[2], &c[3], &c[4], &c[1], &c[5], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^an ideal (.+?) supply feeds a (.+?) series resistor and parallel branches of (.+?) and (.+?)\. give (.+)$").captures(input) {
            return self.network_projection(&c[2], &c[3], &c[4], &c[1], &c[5], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^for a (.+?) ideal supply with (.+?) in series and (.+?) parallel to (.+?), calculate (.+)$").captures(input) {
            return self.network_projection(&c[2], &c[3], &c[4], &c[1], &c[5], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) ideal source feeds a (.+?) resistor in series with parallel (.+?) and (.+?) resistors\. report (.+)$").captures(input) {
            return self.network_projection(&c[2], &c[3], &c[4], &c[1], &c[5], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^two (.+?) resistors are in parallel and connected in series with (.+?) across (.+?); (?:calculate|find) total resistance and source current$").captures(input) {
            let branch = q!(c, 1, "Ω", Positive);
            let series = q!(c, 2, "Ω", Nonnegative);
            let voltage = q!(c, 3, "V", Signed);
            // Two equal parallel branches share half of the supplied branch resistance.
            let total = format!("{branch}/2+{series}");
            return self.report(&[("total resistance", "Ω", total.clone()),
                ("source current", "A", format!("{voltage}/({total})"))], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) and (.+?) resistor are in parallel across (.+?); report equivalent resistance, branch currents, and total power$").captures(input) {
            let first = q!(c, 1, "Ω", Positive);
            let second = q!(c, 2, "Ω", Positive);
            let voltage = q!(c, 3, "V", Signed);
            let equivalent = format!("1/(1/{first}+1/{second})");
            let first_current = format!("{voltage}/{first}");
            let second_current = format!("{voltage}/{second}");
            return self.report(&[("equivalent resistance", "Ω", equivalent),
                ("first branch current", "A", first_current.clone()), ("second branch current", "A", second_current.clone()),
                ("total power", "W", format!("{voltage}*(({first_current})+({second_current}))"))], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) supply drives (.+?) through a device for (.+?); (?:calculate|find) resistance, power, charge, and energy$").captures(input) {
            let voltage = q!(c, 1, "V", Signed);
            let current = q!(c, 2, "A", Positive);
            let duration = q!(c, 3, "seconds", Nonnegative);
            let power = format!("{voltage}*{current}");
            return self.report(&[("resistance", "Ω", format!("{voltage}/{current}")),
                ("power", "W", power.clone()), ("charge", "coulombs", format!("{current}*{duration}")),
                ("energy", "J", format!("({power})*{duration}"))], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) capacitor is charged to (.+?); (?:find|calculate) capacitance in (.+?), charge, and stored energy$").captures(input) {
            let capacitance = self.capacitor_role(&c[1], context)?;
            let voltage = q!(c, 2, "V", Signed);
            return self.report(&[("capacitance", &c[3], capacitance.clone()),
                ("charge", "coulombs", format!("{capacitance}*{voltage}")),
                ("energy", "J", format!("{capacitance}*square({voltage})/2"))], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?), (.+?) appliance draws what current and has what effective resistance assuming fixed resistance$").captures(input) {
            let voltage = q!(c, 1, "V", Positive);
            let power = q!(c, 2, "W", Positive);
            return self.report(&[("current", "A", format!("{power}/{voltage}")),
                ("effective resistance", "Ω", format!("square({voltage})/{power}"))], context).map(Some);
        }
        if let Some(c) =
            re!(r"(?i)^a (.+?) heater runs for (.+?); report energy in (.+?) and (.+)$")
                .captures(input)
        {
            let power = q!(c, 1, "W", Nonnegative);
            let duration = q!(c, 2, "seconds", Nonnegative);
            let energy = format!("{power} * {duration}");
            return self
                .report(
                    &[("energy", &c[3], energy.clone()), ("energy", &c[4], energy)],
                    context,
                )
                .map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) battery with internal resistance (.+?) supplies a (.+?) load; (?:determine|find|calculate) current and terminal voltage$").captures(input) {
            let emf = q!(c, 1, "V", Nonnegative);
            let internal = q!(c, 2, "Ω", Nonnegative);
            let load = q!(c, 3, "Ω", Nonnegative);
            let total = self.role(&format!("{internal} + {load}"), "Ω", Domain::Positive, context)?;
            let current = format!("{emf}/{total}");
            return self.report(&[("current", "A", current.clone()), ("terminal voltage", "V", format!("({current})*{load}"))], context).map(Some);
        }
        if let Some(c) =
            re!(r"(?i)^a (.+?) capacitor at (.+?) stores what charge in (.+?) and energy in (.+)$")
                .captures(input)
        {
            let capacitance = self.capacitor_role(&c[1], context)?;
            let voltage = q!(c, 2, "V", Signed);
            return self
                .report(
                    &[
                        ("charge", &c[3], format!("{capacitance}*{voltage}")),
                        (
                            "energy",
                            &c[4],
                            format!("{capacitance}*square({voltage})/2"),
                        ),
                    ],
                    context,
                )
                .map(Some);
        }
        if let Some(c) = re!(r"(?i)^(?:calculate|find) the capacitance needed to store (.+?) at (.+?), in (.+?) and (.+)$").captures(input) {
            // C is coulombs only in this complete stored-charge role; global C stays unchanged.
            let charge = if let Some(number) = c[1].trim().strip_suffix(" C") {
                format!("{number} coulombs")
            } else { c[1].to_owned() };
            let charge = self.role(&charge, "coulombs", Domain::Nonnegative, context)?;
            let voltage = q!(c, 2, "V", Positive);
            let capacitance = format!("{charge}/{voltage}");
            return self.report(&[("capacitance", &c[3], capacitance.clone()), ("capacitance", &c[4], capacitance)], context).map(Some);
        }
        // Complete finite DC requests assign roles before selecting their goals.
        if let Some(c) = re!(r"(?i)^a (.+?) resistor is connected to (.+?); (?:find|calculate) current in (.+?) and (.+?) and the power in (.+)$").captures(input) {
            let r = q!(c, 1, "Ω", Positive);
            let v = q!(c, 2, "V", Nonnegative);
            let current = format!("{v} / {r}");
            return self.report(&[("current", &c[3], current.clone()),
                ("current", &c[4], current.clone()),
                ("power", &c[5], format!("{v} * ({current})"))], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^with voltage (.+?) and current (.+?), (?:determine|find|calculate) resistance and electrical power, including units$").captures(input) {
            let v = q!(c, 1, "V", Nonnegative);
            let i = q!(c, 2, "A", Positive);
            return self.report(&[("resistance", "Ω", format!("{v} / {i}")),
                ("power", "W", format!("{v} * {i}"))], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) current flows through (.+?) for (.+?); (?:calculate|find) voltage and energy in (.+)$").captures(input) {
            let i = q!(c, 1, "A", Nonnegative);
            let r = q!(c, 2, "Ω", Nonnegative);
            let t = q!(c, 3, "seconds", Nonnegative);
            return self.report(&[("voltage", "V", format!("{i} * {r}")),
                ("energy", &c[4], format!("square({i}) * {r} * {t}"))], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) resistor and a (.+?) resistor are connected in parallel across (.+?); (?:calculate|find) branch currents and combined power$").captures(input) {
            let a = q!(c, 1, "Ω", Positive);
            let b = q!(c, 2, "Ω", Positive);
            let v = q!(c, 3, "V", Nonnegative);
            let first = format!("{v} / {a}");
            let second = format!("{v} / {b}");
            return self.report(&[("first branch current", "A", first.clone()),
                ("second branch current", "A", second.clone()),
                ("combined power", "W", format!("{v} * (({first}) + ({second}))"))], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^for a (.+?) source and (.+?) load, (?:determine|find|calculate) current and power from the ideal Ohm[’']s law model$").captures(input) {
            let v = q!(c, 1, "V", Nonnegative);
            let r = q!(c, 2, "Ω", Positive);
            let current = format!("{v} / {r}");
            return self.report(&[("current", "A", current.clone()),
                ("power", "W", format!("{v} * ({current})"))], context).map(Some);
        }
        rule!(
            r"(?i)^a component has (.+?) across it and carries (.+?); (?:calculate|find) its resistance using V\s*=\s*IR$",
            "Ω",
            c,
            format!(
                "{} / {}",
                q!(c, 1, "V", Nonnegative),
                q!(c, 2, "A", Positive)
            )
        );
        if let Some(c) = re!(r"(?i)^a (.+?) resistor carries (.+?) for (.+?); (?:find|calculate) voltage, power, and energy$").captures(input) {
            let r = q!(c, 1, "Ω", Nonnegative);
            let i = q!(c, 2, "A", Nonnegative);
            let t = q!(c, 3, "seconds", Nonnegative);
            let power = format!("square({i}) * {r}");
            return self.report(&[("voltage", "V", format!("{i} * {r}")),
                ("power", "W", power.clone()),
                ("energy", "J", format!("({power}) * {t}"))], context).map(Some);
        }
        // Constant supplied DC measurements; role validation precedes every goal.
        rule!(
            r"(?i)^a battery rated (.+?) drives (.+?) for (.+?); (?:calculate|find) electrical energy in (.+?) using power times elapsed seconds$",
            &c[4],
            c,
            {
                let v = q!(c, 1, "V", Positive);
                let i = q!(c, 2, "A", Nonnegative);
                let t = q!(c, 3, "seconds", Nonnegative);
                format!("{v} * {i} * {t}")
            }
        );
        rule!(
            r"(?i)^at (.+?), a resistor with resistance (.+?) carries what current according to Ohm[’']s law$",
            "A",
            c,
            format!(
                "{} / {}",
                q!(c, 1, "V", Nonnegative),
                q!(c, 2, "Ω", Positive)
            )
        );
        if let Some(c) = re!(r"(?i)^use Ohm[’']s law to find current for (.+?) across (.+?), then (?:calculate|find) the power dissipated$").captures(input) {
            let v = q!(c, 1, "V", Nonnegative);
            let r = q!(c, 2, "Ω", Positive);
            let current = format!("{v} / {r}");
            return self.report(&[("current", "A", current.clone()),
                ("power", "W", format!("{v} * ({current})"))], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a circuit draws (.+?) from a (.+?) supply for (.+?); report energy in (.+?) and (.+)$").captures(input) {
            let i = q!(c, 1, "A", Nonnegative);
            let v = q!(c, 2, "V", Nonnegative);
            let t = q!(c, 3, "seconds", Nonnegative);
            let energy = format!("{v} * {i} * {t}");
            // Natural compound unit words use hyphens; the registry's aliases
            // use spaces. Preserve both requested targets, then render canonically.
            let first = c[4].replace('-', " ");
            let second = c[5].replace('-', " ");
            return self.report(&[("energy", &first, energy.clone()),
                ("energy", &second, energy)], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a capacitor charge is (.+?) at (.+?); (?:determine|calculate|find) capacitance in (.+?) and (.+)$").captures(input) {
            let charge = q!(c, 1, "coulombs", Nonnegative);
            let v = q!(c, 2, "V", Positive);
            let capacitance = format!("{charge} / {v}");
            return self.report(&[("capacitance", &c[3], capacitance.clone()),
                ("capacitance", &c[4], capacitance)], context).map(Some);
        }
        rule!(
            r"(?i)^simplify (.+?) DC across a (.+?) resistor in series with a parallel pair of (.+?) and (.+?): give the total current in (.+?)$",
            &c[5],
            c,
            {
                let v = q!(c, 1, "V", Nonnegative);
                let series = q!(c, 2, "Ω", Nonnegative);
                let a = q!(c, 3, "Ω", Positive);
                let b = q!(c, 4, "Ω", Positive);
                format!("{v} / ({series} + 1 / (1 / {a} + 1 / {b}))")
            }
        );
        rule!(
            r"(?i)^for an ideal (.+?) battery supplying (.+?) for (.+?), calculate the energy delivered in (.+?), assuming constant voltage and current$",
            &c[4],
            c,
            {
                let v = q!(c, 1, "V", Positive);
                let i = q!(c, 2, "A", Nonnegative);
                let t = q!(c, 3, "seconds", Nonnegative);
                format!("{v} * {i} * {t}")
            }
        );
        rule!(
            r"(?i)^a (.+?) RMS AC source feeds a (.+?) resistor\. what RMS current flows$",
            "A",
            c,
            format!(
                "{} / {}",
                q!(c, 1, "V", Nonnegative),
                q!(c, 2, "Ω", Positive)
            )
        );
        // A complete three-branch network; each branch is separately typed.
        rule!(
            r"(?i)^find the equivalent resistance of (.+?), (.+?), and (.+?) resistors connected in parallel$",
            "Ω",
            c,
            format!(
                "1 / (1 / {} + 1 / {} + 1 / {})",
                q!(c, 1, "Ω", Positive),
                q!(c, 2, "Ω", Positive),
                q!(c, 3, "Ω", Positive)
            )
        );
        rule!(
            r"(?i)^three resistors, (.+?), (.+?), and (.+?), are in series across (.+?) DC\. find the voltage across the (.+?) resistor$",
            "V",
            c,
            {
                let a = q!(c, 1, "Ω", Nonnegative);
                let b = q!(c, 2, "Ω", Nonnegative);
                let d = q!(c, 3, "Ω", Nonnegative);
                let v = q!(c, 4, "V", Nonnegative);
                let branch = q!(c, 5, "Ω", Nonnegative);
                self.require_branch(&branch, &[&a, &b, &d], context)?;
                let total = format!("sum({a},{b},{d})");
                self.role(&total, "Ω", Domain::Positive, context)?;
                format!("{v} * {branch} / {total}")
            }
        );
        rule!(
            r"(?i)^an ideal (.+?) battery drives a (.+?) resistor for (.+?)\. calculate charge transferred in (?:C|coulombs?)$",
            "coulombs",
            c,
            format!(
                "{} / {} * {}",
                q!(c, 1, "V", Nonnegative),
                q!(c, 2, "Ω", Positive),
                q!(c, 3, "seconds", Nonnegative)
            )
        );
        rule!(
            r"(?i)^a rated ideal (.+?), (.+?) battery supplies a constant (.+?) load\. calculate runtime in (.+?), assuming its full rated capacity is usable$",
            &c[4],
            c,
            {
                let _voltage = q!(c, 1, "V", Positive);
                let capacity = q!(c, 2, "Ah", Nonnegative);
                let current = q!(c, 3, "A", Positive);
                format!("{capacity} / {current}")
            }
        );
        rule!(
            r"(?i)^for an ideal (.+?) battery rated (.+?), calculate stored energy in (.+?), assuming the rated voltage stays constant throughout discharge$",
            &c[3],
            c,
            {
                let v = q!(c, 1, "V", Positive);
                let capacity = q!(c, 2, "Ah", Nonnegative);
                format!("{v} * {capacity}")
            }
        );
        // These equations are supplied explicitly; no waveform relation is inferred.
        rule!(
            r"(?i)^at (.+?) RMS, a load draws (.+?) RMS with power factor (.+?) lagging\. calculate reactive power in var, using Q = V I sqrt\(1 [−-] PF[²2]\)$",
            "var",
            c,
            format!(
                "{} * {} * sqrt(1 - square({}))",
                q!(c, 1, "V", Nonnegative),
                q!(c, 2, "A", Nonnegative),
                q!(c, 3, "1", PowerFactor)
            )
        );
        if let Some(c) =
            re!(r"(?i)^given (.+?) RMS, (.+?) RMS, and real power (.+?), compute the power factor$")
                .captures(input)
        {
            let v = q!(c, 1, "V", Positive);
            let i = q!(c, 2, "A", Positive);
            let p = q!(c, 3, "W", Nonnegative);
            let expression = format!("{p} / ({v} * {i})");
            self.role(&expression, "1", Domain::PowerFactor, context)?;
            return Ok(Some(expression));
        }
        rule!(
            r"(?i)^a purely resistive (.+?) load receives (.+?)\. calculate its RMS voltage$",
            "V",
            c,
            format!(
                "sqrt({} * {})",
                q!(c, 1, "Ω", Positive),
                q!(c, 2, "W", Nonnegative)
            )
        );
        if let Some(c)=re!(r"(?i)^a (.+?) DC battery delivers (.+?) through a series network whose total resistance is (.+?)\. calculate battery power and check whether the stated current is consistent with Ohm[’']s law$").captures(input) {
            let v=q!(c,1,"V",Nonnegative);
            let i=q!(c,2,"A",Nonnegative);
            let r=q!(c,3,"Ω",Positive);
            self.require_consistent(&v,&format!("{i} * {r}"),"V",context)?;
            return Ok(Some(format!("electrical_battery_check({v},{i},{r})")));
        }
        if let Some(c)=re!(r"(?i)^the load has (.+?) apparent power and (.+?) real power\. calculate power factor and reactive power magnitude using Q = sqrt\(S[²2] [−-] P[²2]\)$").captures(input) {
            let s=q!(c,1,"VA",Positive);
            let p=q!(c,2,"W",Nonnegative);
            if self.compositions.quantity_order(&p,&s,context)?==Ordering::Greater {
                return Err(Error("invalid_physical_value".into()));
            }
            return Ok(Some(format!("electrical_power_triangle({s},{p})")));
        }
        if let Some(c)=re!(r"(?i)^a (.+?) RMS source feeds a (.+?) load at PF (.+?)\. find current assuming the load is a series resistor; state whether that assumption is compatible with PF (.+?)$").captures(input) {
            let v=q!(c,1,"V",Nonnegative);
            let r=q!(c,2,"Ω",Positive);
            let pf=q!(c,3,"1",PowerFactor);
            let repeated=q!(c,4,"1",PowerFactor);
            self.require_consistent(&pf,&repeated,"1",context)?;
            self.require_consistent(&pf,"1","1",context)?;
            return Ok(Some(format!("({v} / {r}) in A")));
        }
        rule!(
            r"(?i)^a (.+?) DC source has a (.+?) series resistor followed by (.+?) parallel to (.+?)\. what is the current in the (.+?) leg$",
            "A",
            c,
            {
                let v = q!(c, 1, "V", Nonnegative);
                let series = q!(c, 2, "Ω", Nonnegative);
                let a = q!(c, 3, "Ω", Positive);
                let b = q!(c, 4, "Ω", Positive);
                let branch = q!(c, 5, "Ω", Positive);
                self.require_branch(&branch, &[&a, &b], context)?;
                let parallel = format!("(1 / (1 / {a} + 1 / {b}))");
                format!("{v} / ({series} + {parallel}) * {parallel} / {branch}")
            }
        );
        if let Some(c)=re!(r"(?i)^a (.+?) ideal battery is connected directly across an ideal (.+?) short circuit; calculate current and explain whether it is finite$").captures(input) {
            let _v=q!(c,1,"V",Nonnegative);
            let _r=q!(c,2,"Ω",Nonnegative);
            // The ideal short gives no uniquely determined finite current, even at zero V.
            return Err(Error("invalid_physical_value".into()));
        }
        if let Some(c)=re!(r"(?i)^a load at (.+?) RMS draws (.+?) RMS at PF (.+?) while also being specified to consume (.+?); identify whether all three specifications can hold simultaneously$").captures(input) {
            let v=q!(c,1,"V",Nonnegative);
            let i=q!(c,2,"A",Nonnegative);
            let pf=q!(c,3,"1",PowerFactor);
            let p=q!(c,4,"W",Nonnegative);
            self.require_consistent(&p,&format!("{v} * {i} * {pf}"),"W",context)?;
            return Ok(Some("true".into()));
        }
        if let Some(c)=re!(r"(?i)^a (.+?) resistor is said to dissipate (.+?) while carrying (.+?) DC; check whether the power and current agree$").captures(input) {
            let r=q!(c,1,"Ω",Nonnegative);
            let p=q!(c,2,"W",Nonnegative);
            let i=q!(c,3,"A",Nonnegative);
            self.require_consistent(&p,&format!("square({i}) * {r}"),"W",context)?;
            return Ok(Some("true".into()));
        }
        if let Some(c) =
            re!(r"(?i)^convert (.+?) into ohms using the definition (.+?) = (.+?)$").captures(input)
        {
            // A supplied unit definition must be true; it cannot change physical dimensions.
            let _left = q!(c, 2, "seconds", Positive);
            let _right = q!(c, 3, "seconds", Positive);
            self.require_consistent(&c[2], &c[3], "seconds", context)?;
            return Ok(Some(format!("({}) in ohms", &c[1])));
        }
        if let Some(c) = re!(
            r"(?i)^a (.+?) RMS source feeds a (.+?) resistor and asks for the current in (.+?)$"
        )
        .captures(input)
        {
            let v = q!(c, 1, "V", Nonnegative);
            let r = q!(c, 2, "Ω", Positive);
            return Ok(Some(format!("({v} / {r}) in {}", &c[3])));
        }
        Ok(None)
    }
}