nucleide-nuclei 0.15.0

Nuclide identification, naming conventions, and reaction names
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
//! Static nuclear reference data: atomic masses (AME2020 plus ENDF-derived
//! isomer masses), natural abundances, radioactive half-lives, decay branches,
//! screening-level cross sections, neutron scattering lengths, mean decay
//! energies, and dose factors.
//!
//! # Provenance
//!
//! - Atomic masses: the [AME2020 atomic mass evaluation][ame] (Huang et al.,
//!   *Chinese Physics C* **45**, 030002/030003, 2021; data courtesy the
//!   IAEA-supported AMDC), condensed into the compact [`crate::data`]
//!   tables below. Isomer rows add the ENDF/B-VIII.0 File-1 MT451 `ELIS`
//!   excitation energy: `m = m_ground + E*/931.49410242 u` (ENDF excitation
//!   energies only; no NUBASE import; isomer tapes with unset `ELIS` carry
//!   the ground-state mass).
//! - Natural abundances: standard isotopic compositions from the
//!   ENDF/B-VIII.0 evaluation, expressed as fractions in 0..1.
//! - Half-lives: ENDF/B-VIII.0 decay evaluations (distributed via the IAEA
//!   and BNL/NNDC), expressed in seconds.
//! - Decay branches (`decay_branches.tsv`): per-branch daughters from the
//!   ENDF/B-VIII.0 decay sublibrary (MF8/MT457 NDK records: RTYP decay-mode
//!   code, RFS daughter state flag, BR branching fraction). RTYP digits
//!   apply in emission order (ENDF-102 §8.4; OpenMC `decay.py` digit table):
//!   beta- gives Z+1, EC/beta+ gives Z-1, alpha gives Z-2/A-4, IT is
//!   unchanged, delayed neutrons/protons subtract the emitted nucleons.
//!   Spontaneous-fission and fission-family branches are dropped (depletion
//!   matrices skip `sf` gains); zero-half-life and stable-flagged tapes
//!   yield no rows, so effectively-stable entries stay absent, matching the
//!   half-life table's stable-absent convention.
//!   *unchanged carries of ENDF/B-VII.1 evaluations* per their README.txt —
//!   mostly England et al. ENDF-349 (EVAL-JUL89), plus the Chadwick–Kawano
//!   Pu-239 evaluation — with the Mattera–Sonzogni cumulative-yield
//!   correction **not** applied; values are verbatim from the tapes.
//! - Simple cross sections (`simple_xs.tsv`): **total** microscopic cross
//!   sections in barns. Thermal values combine NIST NCNR 2200 m/s bound
//!   scattering/absorption converted to free-atom totals via
//!   `xs·(A/(A+1))² + xs_a` (ENDF File 3 alone is background-only inside
//!   resonance ranges); 14-MeV values are ENDF/B-VII.1 MF3/MT1 interpolated
//!   per the tape INT laws. Screening-level; use evaluated libraries for
//!   transport, never for safety calculations.
//! - Scattering lengths (`scattering_lengths.tsv`): bound coherent /
//!   incoherent lengths in femtometres from the NIST NCNR tabulation of
//!   Sears, *Neutron News* **3**(3) (1992) and its update; complex
//!   (absorbing) lengths enter by real part, incoherent lengths otherwise
//!   derive from the tabulated spin-incoherent cross section via
//!   `b_inc = 10·sqrt(σ_i/4π)` fm. Isotopes the table does not tabulate
//!   (and non-monoisotopic element rows) are absent.
//! - Decay energies (`decay_energy.tsv`): mean *prompt* recoverable energy
//!   per decay in MeV from ENDF/B-VII.1 decay tapes (MF8/MT457 summary
//!   components, paired uncertainties skipped; delayed-neutron kinetic
//!   energy included, neutrinos never appear). Daughter gammas belong to
//!   the daughter row — chain codes must sum members (e.g. Cs137 prompt
//!   plus Ba137_m1 662 keV). Not for spectroscopy or safety use.
//! - Dose factors (`dose_factors.tsv`): external-air/soil, ingestion, and
//!   inhalation factors from the BSD-3 PyNE `dbgen/dosefactors*.csv` tables
//!   (HNF-SD-WM-TI-707 Rev.1 / HNF-5636 App. O; GENII/EPA/DOE are 3 parallel
//!   evaluations). `+D` folds into the parent. Air is EPA-only: GENII/DOE
//!   air rows are `-1` sentinels (PyNE convention); accessors return the
//!   stored `-1` and dose analytics treat negative factors as missing.
//!   Not for safety decisions (upstream PyNE disclaimer).
//!
//! The screening tables are generated by
//! `scripts/gen-nuclear-data.py` (stdlib-only; run `--help` for the
//! upstream download URLs) — never hand-edit a value, regenerate.
//!
//! All tables are vendored as tab-separated text under `src/data/` and
//! embedded with `include_str!`; no runtime dependencies beyond `std`.
//! Parsing happens lazily on first lookup into fixed static maps.
//!
//! Table contents:
//!
//! - `data/ame2020.tsv`: one row per ground-state nuclide (`nucid`,
//!   `mass_u`, `uncertainty_u`), covering all 3 557 nuclides with `Z >= 1`
//!   (the free-neutron row of the source file is dropped), plus one row per
//!   ENDF/B-VIII.0 isomer tape (full state-bearing nucid, 738 rows):
//!   `m = m_ground + ELIS/931.49410242 u` (4 295 rows total).
//! - `data/natural_abundance.tsv`: `GNDS name` → `fraction`, including the
//!   lone naturally occurring isomer Ta180_m1.
//! - `data/half_life.tsv`: `GNDS name` → `half_life_seconds`, for every
//!   radionuclide in the evaluation (stable nuclides are simply absent).
//! - `data/decay_branches.tsv`: `parent_GNDS` → (`progeny_GNDS`, `bf`,
//!   `mode`) per kept branch (5 068 rows over 3 541 parents; SF/fission
//!   branches dropped, so strong SF emitters sum to `1 - BR(SF)`).
//! - `data/fission_yields.tsv`: (`parent_GNDS`, `origin`, `kind`,
//!   `energy_eV`) → per-product (`daughter_GNDS`, `Y`, `dY`) rows from the
//!   ENDF/B-VIII.0 neutron-induced and spontaneous fission-yield
//!   sublibraries (151 490 rows over 36 parents and 122 incident-energy
//!   sets; MF8/MT454 independent + MF8/MT459 cumulative, values verbatim —
//!   both sublibraries are unchanged carries of ENDF/B-VII.1 evaluations
//!   per the tapes' README.txt). `dY = 0` is the no-uncertainty sentinel
//!   and occurs exactly on the zero-yield rows of this sublibrary.
//! - `data/simple_xs.tsv`: `GNDS name` → (`thermal_barn`, `fast14mev_barn`)
//!   total cross sections (241 rows; resonance nuclides without a NIST row
//!   and isomers are absent by construction).
//! - `data/scattering_lengths.tsv`: `GNDS name` → (`b_coherent_fm`,
//!   `b_incoherent_fm`) bound scattering lengths (267 rows, NIST-tabulated
//!   isotopes plus monoisotopic element attributions).
//! - `data/decay_energy.tsv`: `GNDS name` → `mev_per_decay` mean prompt
//!   recoverable decay energy (3 557 rows covering every ENDF/B-VII.1 decay
//!   tape with nonzero heat data, isomers with prompt gammas such as
//!   Ba137_m1 included). Basis note: this table stays on ENDF/B-VII.1
//!   while `half_life.tsv` and `decay_branches.tsv` use ENDF/B-VIII.0.
//! - `data/dose_factors.tsv`: (`GNDS name`, `pathway`, `source`) → (`factor`,
//!   `f1`, `lung_model`) dose factors (1 116 rows: 93 folded nuclides × 4
//!   pathways × 3 sources; `f1` set only on ingest rows, `lung_model` only
//!   on inhale rows).
//!
//! Masses are keyed by the canonical [`NuclideId`] nucid layout, including
//! the metastable state: isomers with their own ENDF/B-VIII.0 tape resolve
//! to `m_ground + E*/931.49410242 u`, while isomers without a tape fall back
//! to the ground-state mass (the missing excitation energy is at most MeV
//! against a GeV-scale mass). Q-value helpers stay ground-state-only by
//! design (see [`q_value_neutron_capture`]): they combine tabulated atomic
//! masses per the textbook formulas, and isomer-resolved Q-values would need
//! excitation bookkeeping beyond this screening-level scope.
//!
//! [ame]: https://doi.org/10.1088/1674-1137/abddaf
//!
//! Ownership note: this module + its data files only — do NOT edit `lib.rs`.

use std::collections::BTreeMap;
use std::sync::OnceLock;

use crate::NuclideId;

const AME2020_TSV: &str = include_str!("data/ame2020.tsv");
const NATURAL_ABUNDANCE_TSV: &str = include_str!("data/natural_abundance.tsv");
const HALF_LIFE_TSV: &str = include_str!("data/half_life.tsv");
const SIMPLE_XS_TSV: &str = include_str!("data/simple_xs.tsv");
const SCATTERING_LENGTHS_TSV: &str = include_str!("data/scattering_lengths.tsv");
const DECAY_ENERGY_TSV: &str = include_str!("data/decay_energy.tsv");
const DECAY_BRANCHES_TSV: &str = include_str!("data/decay_branches.tsv");
const DOSE_FACTORS_TSV: &str = include_str!("data/dose_factors.tsv");
const FISSION_YIELDS_TSV: &str = include_str!("data/fission_yields.tsv");

static MASSES: OnceLock<BTreeMap<u32, f64>> = OnceLock::new();
static ABUNDANCES: OnceLock<BTreeMap<u32, f64>> = OnceLock::new();
static HALF_LIVES: OnceLock<BTreeMap<u32, f64>> = OnceLock::new();
static SIMPLE_XS: OnceLock<BTreeMap<u32, (f64, f64)>> = OnceLock::new();
static SCATTERING_LENGTHS: OnceLock<BTreeMap<u32, (f64, f64)>> = OnceLock::new();
static DECAY_ENERGIES: OnceLock<BTreeMap<u32, f64>> = OnceLock::new();
static DECAY_BRANCHES: OnceLock<BTreeMap<u32, Vec<DecayBranch>>> = OnceLock::new();
static DOSE_FACTORS: OnceLock<BTreeMap<(u32, DosePathway, DoseSource), DoseEntry>> =
    OnceLock::new();
static FISSION_YIELDS: OnceLock<BTreeMap<FissionYieldKey, Vec<FissionYieldSet>>> = OnceLock::new();

/// MeV per unified atomic mass unit `c²` (2022 CODATA consistent with
/// AME2020 usage).
pub const MEV_PER_U: f64 = 931.494_102_42;

/// Free-neutron atomic mass in u (AME2020: 1.00866491595 u).
pub const NEUTRON_MASS_U: f64 = 1.008_664_915_95;

/// Helium-4 atomic mass in u (AME2020), for alpha-decay Q-values.
pub const HELIUM4_MASS_U: f64 = 4.002_603_254_13;

/// The free neutron's mass, in u.
///
/// See [`NEUTRON_MASS_U`].
pub const fn neutron_mass_u() -> f64 {
    NEUTRON_MASS_U
}

/// Parse `nucid \t mass_u [\t uncertainty_u]` rows, skipping comment lines.
fn parse_masses(tsv: &str) -> BTreeMap<u32, f64> {
    tsv.lines()
        .filter(|line| !line.is_empty() && !line.starts_with('#'))
        .filter_map(|line| {
            let mut cols = line.split('\t');
            let nucid = cols.next()?.parse().ok()?;
            let mass = cols.next()?.parse().ok()?;
            Some((nucid, mass))
        })
        .collect()
}

/// Parse `GNDS name \t fraction` rows into nucid-keyed fractions.
///
/// Malformed rows are skipped silently, matching [`parse_masses`]; the
/// embedded files are compile-time constants and a corrupt row should not
/// panic library consumers.
fn parse_abundances(tsv: &str) -> BTreeMap<u32, f64> {
    tsv.lines()
        .filter(|line| !line.is_empty() && !line.starts_with('#'))
        .filter_map(|line| {
            let mut cols = line.split('\t');
            let name = cols.next()?;
            let fraction: f64 = cols.next()?.parse().ok()?;
            let nucid = NuclideId::from_name(name).ok()?;
            Some((nucid.nucid(), fraction))
        })
        .collect()
}

/// Parse `GNDS name \t half_life_seconds` rows into nucid-keyed seconds.
///
/// Malformed rows are skipped silently, matching [`parse_masses`]; the
/// embedded files are compile-time constants and a corrupt row should not
/// panic library consumers.
fn parse_half_lives(tsv: &str) -> BTreeMap<u32, f64> {
    tsv.lines()
        .filter(|line| !line.is_empty() && !line.starts_with('#'))
        .filter_map(|line| {
            let mut cols = line.split('\t');
            let name = cols.next()?;
            let seconds: f64 = cols.next()?.parse().ok()?;
            let nucid = NuclideId::from_name(name).ok()?;
            Some((nucid.nucid(), seconds))
        })
        .collect()
}

fn masses() -> &'static BTreeMap<u32, f64> {
    MASSES.get_or_init(|| parse_masses(AME2020_TSV))
}

fn abundances() -> &'static BTreeMap<u32, f64> {
    ABUNDANCES.get_or_init(|| parse_abundances(NATURAL_ABUNDANCE_TSV))
}

fn half_lives() -> &'static BTreeMap<u32, f64> {
    HALF_LIVES.get_or_init(|| parse_half_lives(HALF_LIFE_TSV))
}

/// Parse `GNDS name \t thermal_barn \t fast14mev_barn` rows into
/// nucid-keyed `(thermal, fast)` pairs.
///
/// Malformed rows are skipped silently, matching [`parse_masses`].
fn parse_simple_xs(tsv: &str) -> BTreeMap<u32, (f64, f64)> {
    tsv.lines()
        .filter(|line| !line.is_empty() && !line.starts_with('#'))
        .filter_map(|line| {
            let mut cols = line.split('\t');
            let name = cols.next()?;
            let thermal: f64 = cols.next()?.parse().ok()?;
            let fast: f64 = cols.next()?.parse().ok()?;
            let nucid = NuclideId::from_name(name).ok()?;
            Some((nucid.nucid(), (thermal, fast)))
        })
        .collect()
}

/// Parse `GNDS name \t b_coherent_fm \t b_incoherent_fm` rows into
/// nucid-keyed `(coherent, incoherent)` pairs.
///
/// Malformed rows are skipped silently, matching [`parse_masses`].
fn parse_scattering_lengths(tsv: &str) -> BTreeMap<u32, (f64, f64)> {
    tsv.lines()
        .filter(|line| !line.is_empty() && !line.starts_with('#'))
        .filter_map(|line| {
            let mut cols = line.split('\t');
            let name = cols.next()?;
            let coherent: f64 = cols.next()?.parse().ok()?;
            let incoherent: f64 = cols.next()?.parse().ok()?;
            let nucid = NuclideId::from_name(name).ok()?;
            Some((nucid.nucid(), (coherent, incoherent)))
        })
        .collect()
}

/// Parse `GNDS name \t mev_per_decay` rows into nucid-keyed MeV.
///
/// Malformed rows are skipped silently, matching [`parse_masses`].
fn parse_decay_energies(tsv: &str) -> BTreeMap<u32, f64> {
    tsv.lines()
        .filter(|line| !line.is_empty() && !line.starts_with('#'))
        .filter_map(|line| {
            let mut cols = line.split('\t');
            let name = cols.next()?;
            let mev: f64 = cols.next()?.parse().ok()?;
            let nucid = NuclideId::from_name(name).ok()?;
            Some((nucid.nucid(), mev))
        })
        .collect()
}

fn simple_xs_map() -> &'static BTreeMap<u32, (f64, f64)> {
    SIMPLE_XS.get_or_init(|| parse_simple_xs(SIMPLE_XS_TSV))
}

fn scattering_length_map() -> &'static BTreeMap<u32, (f64, f64)> {
    SCATTERING_LENGTHS.get_or_init(|| parse_scattering_lengths(SCATTERING_LENGTHS_TSV))
}

fn decay_energy_map() -> &'static BTreeMap<u32, f64> {
    DECAY_ENERGIES.get_or_init(|| parse_decay_energies(DECAY_ENERGY_TSV))
}

/// The full AME2020 ground-state mass table, keyed by nucid (in u).
pub fn mass_table() -> &'static BTreeMap<u32, f64> {
    masses()
}

/// The full natural-abundance table, keyed by nucid (fraction in 0..1).
pub fn abundance_table() -> &'static BTreeMap<u32, f64> {
    abundances()
}

/// The full half-life table in seconds, keyed by nucid.
pub fn half_life_table() -> &'static BTreeMap<u32, f64> {
    half_lives()
}

/// The full simple cross-section table, keyed by nucid:
/// `(thermal_barn, fast14mev_barn)` total cross sections.
pub fn simple_xs_table() -> &'static BTreeMap<u32, (f64, f64)> {
    simple_xs_map()
}

/// The full bound scattering-length table, keyed by nucid:
/// `(b_coherent_fm, b_incoherent_fm)`.
pub fn scattering_length_table() -> &'static BTreeMap<u32, (f64, f64)> {
    scattering_length_map()
}

/// The full mean-recoverable-decay-energy table in MeV, keyed by nucid.
pub fn decay_energy_table() -> &'static BTreeMap<u32, f64> {
    decay_energy_map()
}

/// Total microscopic cross sections `(thermal_barn, fast14mev_barn)` for the
/// given `nucid`.
///
/// Screening-level values (see [`simple_xs_table`]); returns `None` for
/// nuclides outside the table — notably resonance absorbers without a NIST
/// row (Cs137, Co60, I135, Xe135) and isomers.
pub fn simple_xs(nucid: u32) -> Option<(f64, f64)> {
    simple_xs_map().get(&nucid).copied()
}

/// Approximate total microscopic cross sections of a named nuclide (see
/// [`NuclideId::from_name`]): `(thermal_barn, fast14mev_barn)`.
pub fn simple_xs_by_name(name: &str) -> Option<(f64, f64)> {
    simple_xs(NuclideId::from_name(name).ok()?.nucid())
}

/// Bound neutron scattering lengths `(b_coherent_fm, b_incoherent_fm)` for
/// the given `nucid`.
///
/// Returns `None` for nuclides outside the NIST-tabulated set (see
/// [`scattering_length_table`]).
pub fn scattering_length(nucid: u32) -> Option<(f64, f64)> {
    scattering_length_map().get(&nucid).copied()
}

/// Bound neutron scattering lengths of a named nuclide (see
/// [`NuclideId::from_name`]): `(b_coherent_fm, b_incoherent_fm)`.
pub fn scattering_length_by_name(name: &str) -> Option<(f64, f64)> {
    scattering_length(NuclideId::from_name(name).ok()?.nucid())
}

/// Mean prompt recoverable decay energy per decay of the given `nucid`, in
/// MeV (see [`decay_energy_table`]).
///
/// Returns `None` for nuclides outside the table, including stable nuclides
/// such as O16 and Fe56.
pub fn decay_energy_mev(nucid: u32) -> Option<f64> {
    decay_energy_map().get(&nucid).copied()
}

/// Mean recoverable decay energy per decay of a named nuclide (see
/// [`NuclideId::from_name`]), in MeV.
pub fn decay_energy_mev_by_name(name: &str) -> Option<f64> {
    decay_energy_mev(NuclideId::from_name(name).ok()?.nucid())
}

// ---------------------------------------------------------------------------
// Decay branches
// ---------------------------------------------------------------------------

/// One decay mode token, matching the depletion-chain vocabulary (`beta-`,
/// `ec/beta+`, `alpha`, `IT`, `sf`) plus the direct nucleon-emission modes
/// (`n`, `p`) for particle-unbound light nuclei.
///
/// EC-only and beta+/EC evaluations both fold into [`Self::EcBetaPlus`].
/// `sf` never appears in the vendored table (fission branches are dropped
/// at generation) but parses for robustness.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum DecayBranchMode {
    /// Negative beta decay (Z+1 daughter, incl. delayed-neutron branches).
    BetaMinus,
    /// Electron capture and/or positron emission (Z-1 daughter).
    EcBetaPlus,
    /// Alpha decay (Z-2/A-4 daughter).
    Alpha,
    /// Isomeric transition (same Z/A daughter).
    It,
    /// Spontaneous fission (dropped at generation; parses only).
    Sf,
    /// Direct neutron emission (A-1 daughter).
    Neutron,
    /// Direct proton emission (Z-1/A-1 daughter).
    Proton,
}

impl DecayBranchMode {
    /// Canonical table token (`beta-`/`ec/beta+`/`alpha`/`IT`/`sf`/`n`/`p`).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::BetaMinus => "beta-",
            Self::EcBetaPlus => "ec/beta+",
            Self::Alpha => "alpha",
            Self::It => "IT",
            Self::Sf => "sf",
            Self::Neutron => "n",
            Self::Proton => "p",
        }
    }

    /// Parse a mode token (case-insensitive).
    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "beta-" | "beta" | "b-" => Some(Self::BetaMinus),
            "ec/beta+" | "ec" | "beta+" => Some(Self::EcBetaPlus),
            "alpha" | "a" => Some(Self::Alpha),
            "it" => Some(Self::It),
            "sf" => Some(Self::Sf),
            "n" => Some(Self::Neutron),
            "p" => Some(Self::Proton),
            _ => None,
        }
    }
}

/// One evaluated decay branch: daughter nuclide, branching fraction, mode.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DecayBranch {
    /// Daughter nucid (full state-bearing id; RFS sets the state).
    pub progeny: u32,
    /// Branching fraction in 0..1 (evaluated value, verbatim).
    pub branching_fraction: f64,
    /// Decay mode token (initial event for multi-particle branches).
    pub mode: DecayBranchMode,
}

/// Parse `parent_GNDS \t progeny_GNDS \t bf \t mode` rows into
/// parent-nucid-keyed branch lists.
///
/// Malformed rows are skipped silently, matching [`parse_masses`].
fn parse_decay_branches(tsv: &str) -> BTreeMap<u32, Vec<DecayBranch>> {
    let mut map: BTreeMap<u32, Vec<DecayBranch>> = BTreeMap::new();
    for line in tsv
        .lines()
        .filter(|line| !line.is_empty() && !line.starts_with('#'))
    {
        let mut cols = line.split('\t');
        let (Some(parent), Some(progeny), Some(bf), Some(mode)) =
            (cols.next(), cols.next(), cols.next(), cols.next())
        else {
            continue;
        };
        let (Ok(p), Ok(d), Ok(b), Some(m)) = (
            NuclideId::from_name(parent).map(|id| id.nucid()),
            NuclideId::from_name(progeny).map(|id| id.nucid()),
            bf.parse::<f64>(),
            DecayBranchMode::parse(mode),
        ) else {
            continue;
        };
        map.entry(p).or_default().push(DecayBranch {
            progeny: d,
            branching_fraction: b,
            mode: m,
        });
    }
    for branches in map.values_mut() {
        branches.sort_by_key(|b| (b.progeny, b.mode));
    }
    map
}

fn decay_branch_map() -> &'static BTreeMap<u32, Vec<DecayBranch>> {
    DECAY_BRANCHES.get_or_init(|| parse_decay_branches(DECAY_BRANCHES_TSV))
}

/// The full decay-branch table, keyed by parent nucid.
///
/// 5 068 rows over 3 541 parents from ENDF/B-VIII.0; SF/fission branches
/// are dropped, so strong SF emitters sum to `1 - BR(SF)`.
pub fn decay_branch_table() -> &'static BTreeMap<u32, Vec<DecayBranch>> {
    decay_branch_map()
}

/// Evaluated decay branches of the given parent `nucid`.
///
/// Returns `None` for nuclides with no branch rows (stable nuclides and
/// zero-half-life evaluation dummies such as Te123).
pub fn decay_branches(nucid: u32) -> Option<Vec<DecayBranch>> {
    decay_branch_map().get(&nucid).cloned()
}

/// Evaluated decay branches of a named nuclide (see [`NuclideId::from_name`]).
pub fn decay_branches_by_name(name: &str) -> Option<Vec<DecayBranch>> {
    decay_branches(NuclideId::from_name(name).ok()?.nucid())
}

/// Branching fraction from `parent` to `progeny` (both nucids), if tabulated.
pub fn branching_fraction(parent: u32, progeny: u32) -> Option<f64> {
    decay_branch_map()
        .get(&parent)?
        .iter()
        .find(|b| b.progeny == progeny)
        .map(|b| b.branching_fraction)
}

/// Branching fraction from `parent` to `progeny` (GNDS names), if tabulated.
pub fn branching_fraction_by_name(parent: &str, progeny: &str) -> Option<f64> {
    branching_fraction(
        NuclideId::from_name(parent).ok()?.nucid(),
        NuclideId::from_name(progeny).ok()?.nucid(),
    )
}

// ---------------------------------------------------------------------------
// Fission product yields
// ---------------------------------------------------------------------------

/// Fission-yield origin: neutron-induced or spontaneous fission.
///
/// Tokens (`n`/`sf`) match the depletion-chain decay vocabulary (`sf` is the
/// spontaneous-fission mode token).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub enum FissionYieldOrigin {
    /// Neutron-induced fission (the ENDF `nfy` tapes).
    #[default]
    NeutronInduced,
    /// Spontaneous fission (the ENDF `sfy` tapes).
    Spontaneous,
}

impl FissionYieldOrigin {
    /// Canonical table token (`n`/`sf`).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::NeutronInduced => "n",
            Self::Spontaneous => "sf",
        }
    }

    /// Parse an origin token (case-insensitive; `n`/`neutron`/`sf`/
    /// `spontaneous`).
    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "n" | "neutron" | "neutron-induced" => Some(Self::NeutronInduced),
            "sf" | "spontaneous" => Some(Self::Spontaneous),
            _ => None,
        }
    }
}

/// Fission-yield kind: independent or cumulative product yields.
///
/// Independent yields (MF8/MT454) are what depletion matrices consume;
/// cumulative yields (MF8/MT459) add the precursor decay-chain feed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub enum FissionYieldKind {
    /// Independent fission product yields (MF8/MT454).
    #[default]
    Independent,
    /// Cumulative fission product yields (MF8/MT459).
    Cumulative,
}

impl FissionYieldKind {
    /// Canonical table token (`independent`/`cumulative`).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Independent => "independent",
            Self::Cumulative => "cumulative",
        }
    }

    /// Parse a kind token (case-insensitive).
    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "independent" | "i" => Some(Self::Independent),
            "cumulative" | "c" => Some(Self::Cumulative),
            _ => None,
        }
    }
}

/// One evaluated fission-product row: daughter, yield fraction, uncertainty.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FissionYieldProduct {
    /// Daughter nucid (full state-bearing id; the tape's FPS flag sets the
    /// state, so isomeric products carry `_m1`/`_m2` ids).
    pub progeny: u32,
    /// Yield fraction Y (evaluated value, verbatim from the tape).
    pub yield_fraction: f64,
    /// Evaluated 1-sigma uncertainty dY \[fraction\].
    ///
    /// `0.0` is the no-uncertainty sentinel: in this sublibrary it occurs
    /// exactly on the zero-yield rows, so consumers needing an uncertainty
    /// should read `0.0` as "not evaluated", never as a zero-width
    /// distribution.
    pub uncertainty: f64,
}

/// Fission product yields at one incident neutron energy.
#[derive(Debug, Clone, PartialEq)]
pub struct FissionYieldSet {
    /// Incident neutron energy \[eV\]; `0.0` for spontaneous fission.
    pub energy_ev: f64,
    /// Product rows of this energy set, in tape (ZAFP, then FPS) order.
    pub products: Vec<FissionYieldProduct>,
}

/// Table key of [`fission_yield_table`]: parent nucid, origin, kind.
type FissionYieldKey = (u32, FissionYieldOrigin, FissionYieldKind);

/// Parse `parent_GNDS \t origin \t kind \t energy_eV \t daughter_GNDS \t Y \t dY`
/// rows into `(parent, origin, kind)`-keyed energy-set lists.
///
/// Malformed rows are skipped silently, matching [`parse_masses`].  Sets are
/// sorted by ascending incident energy (stable: tape product order is kept
/// within a set).
fn parse_fission_yields(tsv: &str) -> BTreeMap<FissionYieldKey, Vec<FissionYieldSet>> {
    let mut sets: BTreeMap<FissionYieldKey, Vec<(f64, usize, FissionYieldProduct)>> =
        BTreeMap::new();
    for line in tsv
        .lines()
        .filter(|line| !line.is_empty() && !line.starts_with('#'))
    {
        let mut cols = line.split('\t');
        let (
            Some(parent),
            Some(origin),
            Some(kind),
            Some(energy),
            Some(daughter),
            Some(y),
            Some(dy),
        ) = (
            cols.next(),
            cols.next(),
            cols.next(),
            cols.next(),
            cols.next(),
            cols.next(),
            cols.next(),
        )
        else {
            continue;
        };
        let (Ok(p), Some(o), Some(k), Ok(e), Ok(d), Ok(y), Ok(dy)) = (
            NuclideId::from_name(parent).map(|id| id.nucid()),
            FissionYieldOrigin::parse(origin),
            FissionYieldKind::parse(kind),
            energy.parse::<f64>(),
            NuclideId::from_name(daughter).map(|id| id.nucid()),
            y.parse::<f64>(),
            dy.parse::<f64>(),
        ) else {
            continue;
        };
        let entry = sets.entry((p, o, k)).or_default();
        entry.push((
            e,
            entry.len(),
            FissionYieldProduct {
                progeny: d,
                yield_fraction: y,
                uncertainty: dy,
            },
        ));
    }
    sets.into_iter()
        .map(|(key, mut rows)| {
            rows.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
            (
                key,
                rows.into_iter()
                    .fold(Vec::<FissionYieldSet>::new(), |mut acc, (e, _i, prod)| {
                        match acc.last_mut() {
                            Some(set) if set.energy_ev == e => set.products.push(prod),
                            _ => acc.push(FissionYieldSet {
                                energy_ev: e,
                                products: vec![prod],
                            }),
                        }
                        acc
                    }),
            )
        })
        .collect()
}

fn fission_yield_map() -> &'static BTreeMap<FissionYieldKey, Vec<FissionYieldSet>> {
    FISSION_YIELDS.get_or_init(|| parse_fission_yields(FISSION_YIELDS_TSV))
}

/// The full fission-yield table, keyed by `(parent nucid, origin, kind)`.
///
/// 151 490 rows over 36 parents and 122 incident-energy sets from the
/// ENDF/B-VIII.0 fission-yield sublibraries (unchanged carries of
/// ENDF/B-VII.1 evaluations per the tapes' README.txt); each value is the
/// list of energy sets, sorted by ascending incident energy.
pub fn fission_yield_table() -> &'static BTreeMap<FissionYieldKey, Vec<FissionYieldSet>> {
    fission_yield_map()
}

/// Evaluated fission product yields of the given parent `nucid`.
///
/// Returns the energy-set list for the requested `origin` and `kind`, or
/// `None` when the parent has no such evaluation (e.g. non-fissionable
/// nuclides).  The lowest-energy set of the `Independent` × `NeutronInduced`
/// block is the depletion convention — see [`default_fission_yields`].
pub fn fission_yields(
    parent: u32,
    origin: FissionYieldOrigin,
    kind: FissionYieldKind,
) -> Option<Vec<FissionYieldSet>> {
    fission_yield_map().get(&(parent, origin, kind)).cloned()
}

/// Evaluated fission product yields of a named nuclide (see
/// [`NuclideId::from_name`]).
pub fn fission_yields_by_name(
    parent: &str,
    origin: FissionYieldOrigin,
    kind: FissionYieldKind,
) -> Option<Vec<FissionYieldSet>> {
    fission_yields(NuclideId::from_name(parent).ok()?.nucid(), origin, kind)
}

/// Lowest-energy independent neutron-induced yield set of the given parent
/// `nucid`.
///
/// This is the depletion-chain convention — OpenMC's
/// `get_default_fission_yields` drives fission production with the yield
/// set at the lowest incident neutron energy.  Returns `None` when the
/// parent has no neutron-induced independent evaluation (e.g. `Cm247`).
pub fn default_fission_yields(parent: u32) -> Option<FissionYieldSet> {
    fission_yield_map()
        .get(&(
            parent,
            FissionYieldOrigin::NeutronInduced,
            FissionYieldKind::Independent,
        ))?
        .first()
        .cloned()
}

/// Lowest-energy independent neutron-induced yield set of a named nuclide
/// (see [`default_fission_yields`]).
pub fn default_fission_yields_by_name(parent: &str) -> Option<FissionYieldSet> {
    default_fission_yields(NuclideId::from_name(parent).ok()?.nucid())
}

/// Independent neutron-induced yield of one daughter at the parent's
/// lowest-energy set (see [`default_fission_yields`]).
///
/// Mirrors [`branching_fraction`]: the bare fraction; the uncertainty and
/// the other energy sets are available through [`fission_yields`].
/// Returns `None` when either nuclide is outside the table.
pub fn fission_yield(parent: u32, progeny: u32) -> Option<f64> {
    default_fission_yields(parent)?
        .products
        .iter()
        .find(|p| p.progeny == progeny)
        .map(|p| p.yield_fraction)
}

/// Independent neutron-induced yield of one daughter (GNDS names) at the
/// parent's lowest-energy set.
pub fn fission_yield_by_name(parent: &str, progeny: &str) -> Option<f64> {
    fission_yield(
        NuclideId::from_name(parent).ok()?.nucid(),
        NuclideId::from_name(progeny).ok()?.nucid(),
    )
}

// ---------------------------------------------------------------------------
// Dose factors
// ---------------------------------------------------------------------------

/// Dose pathway: external air/soil, ingestion, or inhalation.
///
/// `Air` is `ext_air` in PyNE (`mrem/h per Ci/m^3`); `Soil` is `ext_soil`
/// (`mrem/h per Ci/m^2`, 15 cm slab); `Ingest`/`Inhale` are `mrem/pCi`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum DosePathway {
    /// External dose from air submersion.
    Air,
    /// External dose from a 15 cm soil slab.
    Soil,
    /// Committed dose from ingestion.
    Ingest,
    /// Committed dose from inhalation.
    Inhale,
}

impl DosePathway {
    /// Canonical lowercase name (`air`/`soil`/`ingest`/`inhale`).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Air => "air",
            Self::Soil => "soil",
            Self::Ingest => "ingest",
            Self::Inhale => "inhale",
        }
    }

    /// Parse a pathway name (case-insensitive; `ext_air`/`ext_soil` aliases
    /// accepted for PyNE compatibility).
    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "air" | "ext_air" | "ext-air" => Some(Self::Air),
            "soil" | "ext_soil" | "ext-soil" => Some(Self::Soil),
            "ingest" | "ingestion" => Some(Self::Ingest),
            "inhale" | "inhalation" => Some(Self::Inhale),
            _ => None,
        }
    }
}

/// Dose-factor evaluation source: the three parallel HNF-5636 evaluations.
///
/// PyNE source ids are 0 = EPA (default), 1 = DOE, 2 = GENII.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum DoseSource {
    /// EPA evaluation (PyNE source id 0, the default).
    Epa,
    /// DOE evaluation (PyNE source id 1).
    Doe,
    /// GENII evaluation (PyNE source id 2).
    Genii,
}

impl DoseSource {
    /// Canonical uppercase name (`EPA`/`DOE`/`GENII`).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Epa => "EPA",
            Self::Doe => "DOE",
            Self::Genii => "GENII",
        }
    }

    /// Parse a source name (case-insensitive).
    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_uppercase().as_str() {
            "EPA" => Some(Self::Epa),
            "DOE" => Some(Self::Doe),
            "GENII" => Some(Self::Genii),
            _ => None,
        }
    }

    /// PyNE source id (0 = EPA default, 1 = DOE, 2 = GENII).
    pub fn to_int(self) -> u8 {
        match self {
            Self::Epa => 0,
            Self::Doe => 1,
            Self::Genii => 2,
        }
    }

    /// Inverse of [`DoseSource::to_int`]; anything else is `None`.
    pub fn from_int(v: u8) -> Option<Self> {
        match v {
            0 => Some(Self::Epa),
            1 => Some(Self::Doe),
            2 => Some(Self::Genii),
            _ => None,
        }
    }
}

/// One dose-factor row: the table factor plus aux columns.
///
/// `factor` is the raw table value (`-1` for GENII/DOE air, matching PyNE's
/// missing-air sentinel); `f1` (fraction to body fluids) is set only on
/// ingest rows; `lung_model` (`D`/`W`/`Y`/`V`/`O`) only on inhale rows.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DoseEntry {
    /// Raw table factor (see [`DosePathway`] for units).
    pub factor: f64,
    /// `f1` aux column (ingest rows only).
    pub f1: Option<f64>,
    /// Lung-model aux column (inhale rows only).
    pub lung_model: Option<char>,
}

/// Parse `GNDS name \t pathway \t source \t factor [\t f1 [\t lung]]` rows.
///
/// Malformed rows are skipped silently, matching [`parse_masses`].
fn parse_dose_factors(tsv: &str) -> BTreeMap<(u32, DosePathway, DoseSource), DoseEntry> {
    tsv.lines()
        .filter(|line| !line.is_empty() && !line.starts_with('#'))
        .filter_map(|line| {
            let mut cols = line.split('\t');
            let name = cols.next()?;
            let pathway = DosePathway::parse(cols.next()?)?;
            let source = DoseSource::parse(cols.next()?)?;
            let factor: f64 = cols.next()?.parse().ok()?;
            // Trailing aux columns may be absent after `strip`-style writes;
            // missing means None.
            let f1_txt = cols.next().unwrap_or("");
            let lung_txt = cols.next().unwrap_or("");
            let f1 = if f1_txt.trim().is_empty() {
                None
            } else {
                Some(f1_txt.parse().ok()?)
            };
            let lung_model = {
                let t = lung_txt.trim();
                if t.is_empty() {
                    None
                } else {
                    t.chars().next()
                }
            };
            let nucid = NuclideId::from_name(name).ok()?;
            Some((
                (nucid.nucid(), pathway, source),
                DoseEntry {
                    factor,
                    f1,
                    lung_model,
                },
            ))
        })
        .collect()
}

fn dose_factor_map() -> &'static BTreeMap<(u32, DosePathway, DoseSource), DoseEntry> {
    DOSE_FACTORS.get_or_init(|| parse_dose_factors(DOSE_FACTORS_TSV))
}

/// The full dose-factor table, keyed by `(nucid, pathway, source)`.
///
/// 1 116 rows (93 folded nuclides × 4 pathways × 3 sources).
pub fn dose_table() -> &'static BTreeMap<(u32, DosePathway, DoseSource), DoseEntry> {
    dose_factor_map()
}

/// Full dose-factor entry for the given `nucid`, `pathway`, and `source`.
///
/// Returns the stored `-1` sentinel for GENII/DOE air (PyNE convention for
/// missing air data); `None` only when the nuclide has no row at all.
pub fn dose_entry(nucid: u32, pathway: DosePathway, source: DoseSource) -> Option<DoseEntry> {
    dose_factor_map().get(&(nucid, pathway, source)).copied()
}

/// Raw dose factor for the given `nucid`, `pathway`, and `source`.
///
/// See [`dose_entry`]: GENII/DOE air resolve to `Some(-1.0)` (missing-air
/// sentinel); unknown nuclides resolve to `None` (PyNE's `-1` unknown
/// sentinel maps to `None` here).
pub fn dose_factor(nucid: u32, pathway: DosePathway, source: DoseSource) -> Option<f64> {
    dose_entry(nucid, pathway, source).map(|e| e.factor)
}

/// Raw dose factor for a named nuclide (see [`NuclideId::from_name`]).
pub fn dose_factor_by_name(name: &str, pathway: DosePathway, source: DoseSource) -> Option<f64> {
    dose_factor(NuclideId::from_name(name).ok()?.nucid(), pathway, source)
}

/// `f1` (fraction to body fluids) for an ingest row, if present.
pub fn dose_f1(nucid: u32, source: DoseSource) -> Option<f64> {
    dose_entry(nucid, DosePathway::Ingest, source)?.f1
}

/// `f1` for a named nuclide's ingest row.
pub fn dose_f1_by_name(name: &str, source: DoseSource) -> Option<f64> {
    dose_f1(NuclideId::from_name(name).ok()?.nucid(), source)
}

/// Lung model (`D`/`W`/`Y`/`V`/`O`) for an inhale row, if present.
pub fn dose_lung_model(nucid: u32, source: DoseSource) -> Option<char> {
    dose_entry(nucid, DosePathway::Inhale, source)?.lung_model
}

/// Lung model for a named nuclide's inhale row.
pub fn dose_lung_model_by_name(name: &str, source: DoseSource) -> Option<char> {
    dose_lung_model(NuclideId::from_name(name).ok()?.nucid(), source)
}

/// Atomic mass of the nuclide with the given `nucid`, in u.
///
/// Ground states resolve to the AME2020 value. Metastable states resolve to
/// their ENDF-derived isomer mass (`m_ground + E*/931.49410242 u`) when the
/// isomer has its own tape, and fall back to the ground-state mass otherwise
/// (the missing excitation energy is at most MeV against a GeV-scale mass).
/// Returns `None` for unknown nuclides and non-nuclide ids (`Z = 0`).
pub fn atomic_mass(nucid: u32) -> Option<f64> {
    if let Some(mass) = masses().get(&nucid) {
        return Some(*mass);
    }
    let id = NuclideId::from_nucid(nucid);
    if id.state() != 0 {
        let ground = (id.z() * 1000 + id.a()) * 10_000;
        return masses().get(&ground).copied();
    }
    None
}

/// Atomic mass of a named nuclide (see [`NuclideId::from_name`]), in u.
pub fn atomic_mass_by_name(name: &str) -> Option<f64> {
    atomic_mass(NuclideId::from_name(name).ok()?.nucid())
}

/// Natural abundance of the nuclide with the given `nucid`, as a fraction
/// in 0..1.
///
/// Only naturally occurring nuclides have entries, including the isomer
/// Ta180_m1; everything else returns `None`.
pub fn natural_abundance(nucid: u32) -> Option<f64> {
    abundances().get(&nucid).copied()
}

/// Natural abundance of a named nuclide, as a fraction in 0..1.
pub fn natural_abundance_by_name(name: &str) -> Option<f64> {
    natural_abundance(NuclideId::from_name(name).ok()?.nucid())
}

/// Radioactive half-life of the nuclide with the given `nucid`, in seconds.
///
/// Values come from the ENDF/B-VIII.0-derived evaluation; stable
/// nuclides and unknown ids have no entry and return `None`.
pub fn half_life(nucid: u32) -> Option<f64> {
    half_lives().get(&nucid).copied()
}

/// Half-life in seconds of a named nuclide (see [`NuclideId::from_name`]).
pub fn half_life_by_name(name: &str) -> Option<f64> {
    half_life(NuclideId::from_name(name).ok()?.nucid())
}

/// Decay constant λ = ln(2) / t½ of the given `nucid`, in inverse seconds.
///
/// Computed from [`half_life`]; `None` wherever the half-life is unknown.
pub fn decay_constant(nucid: u32) -> Option<f64> {
    half_life(nucid).map(|t_half| std::f64::consts::LN_2 / t_half)
}

/// Decay constant λ = ln(2) / t½ (inverse seconds) of a named nuclide.
pub fn decay_constant_by_name(name: &str) -> Option<f64> {
    decay_constant(NuclideId::from_name(name).ok()?.nucid())
}

/// Q-value of neutron radiative capture X(n,γ)X', in MeV.
///
/// Ground-state-only by design: the formula combines tabulated atomic
/// masses per the textbook definition, and isomer-resolved Q-values would
/// need explicit excitation-energy bookkeeping beyond this
/// screening-level scope (metastable-state and non-nuclide inputs return
/// `None` even though [`atomic_mass`] now resolves isomers).
///
/// From atomic masses (AME2020, in u):
///
/// ```text
/// Q = [m(X + A) + m_n − m(X' = Z, A+1)] · c²   (MeV/u × 931.49410242)
/// ```
///
/// using the AME2020 free-neutron mass ([`NEUTRON_MASS_U`]). Electron
/// binding differences are neglected (standard for capture Q-values).
/// Returns `None` when either ground-state mass is missing, or for
/// metastable-state or non-nuclide inputs.
pub fn q_value_neutron_capture(nucid: u32) -> Option<f64> {
    let id = NuclideId::from_nucid(nucid);
    if id.state() != 0 || id.z() == 0 {
        return None;
    }
    let product = (id.z() * 1000 + id.a() + 1) * 10_000;
    let q_u = atomic_mass(nucid)? + NEUTRON_MASS_U - atomic_mass(product)?;
    Some(q_u * MEV_PER_U)
}

/// Q-value of neutron capture on a named nuclide, in MeV.
pub fn q_value_neutron_capture_by_name(name: &str) -> Option<f64> {
    q_value_neutron_capture(NuclideId::from_name(name).ok()?.nucid())
}

/// Q-value of alpha decay X → Y + He4, in MeV.
///
/// Ground-state-only by design, like [`q_value_neutron_capture`]:
/// metastable and non-nuclide inputs return `None`.
///
/// From atomic masses (AME2020, in u):
///
/// ```text
/// Q = [m(Z,A) − m(Z−2,A−4) − m(He4)] · c²   (MeV/u × 931.49410242)
/// ```
///
/// with [`HELIUM4_MASS_U`] = 4.00260325413 u. Using neutral atomic masses,
/// the two released electrons cancel exactly to first order. Returns `None`
/// when the daughter mass is absent from the table, or for metastable or
/// non-nuclide inputs.
pub fn q_value_alpha(nucid: u32) -> Option<f64> {
    let id = NuclideId::from_nucid(nucid);
    if id.state() != 0 || id.z() <= 2 || id.a() <= 4 {
        return None;
    }
    let daughter = ((id.z() - 2) * 1000 + (id.a() - 4)) * 10_000;
    let q_u = atomic_mass(nucid)? - atomic_mass(daughter)? - HELIUM4_MASS_U;
    Some(q_u * MEV_PER_U)
}

/// Q-value of alpha decay on a named nuclide, in MeV.
pub fn q_value_alpha_by_name(name: &str) -> Option<f64> {
    q_value_alpha(NuclideId::from_name(name).ok()?.nucid())
}

/// Zero-sized façade over this module's lookups.
///
/// Standalone today; intended to satisfy the material crate's future
/// `MassProvider` trait once that integration lands (kept free of cross-crate
/// coupling for now).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct AmeMasses;

impl AmeMasses {
    /// See [`atomic_mass`].
    pub fn atomic_mass(&self, nucid: u32) -> Option<f64> {
        atomic_mass(nucid)
    }

    /// See [`atomic_mass_by_name`].
    pub fn atomic_mass_by_name(&self, name: &str) -> Option<f64> {
        atomic_mass_by_name(name)
    }

    /// See [`natural_abundance`].
    pub fn natural_abundance(&self, nucid: u32) -> Option<f64> {
        natural_abundance(nucid)
    }

    /// See [`natural_abundance_by_name`].
    pub fn natural_abundance_by_name(&self, name: &str) -> Option<f64> {
        natural_abundance_by_name(name)
    }
}

/// Zero-sized façade over the decay-data lookups ([`half_life`],
/// [`decay_constant`], [`decay_energy_mev`], [`decay_branches`],
/// [`branching_fraction`]).
///
/// Mirrors [`AmeMasses`]; standalone today, kept free of cross-crate
/// coupling for future provider-trait integration.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DecayData;

impl DecayData {
    /// See [`half_life`].
    pub fn half_life(&self, nucid: u32) -> Option<f64> {
        half_life(nucid)
    }

    /// See [`half_life_by_name`].
    pub fn half_life_by_name(&self, name: &str) -> Option<f64> {
        half_life_by_name(name)
    }

    /// See [`decay_constant`].
    pub fn decay_constant(&self, nucid: u32) -> Option<f64> {
        decay_constant(nucid)
    }

    /// See [`decay_constant_by_name`].
    pub fn decay_constant_by_name(&self, name: &str) -> Option<f64> {
        decay_constant_by_name(name)
    }

    /// See [`decay_energy_mev`].
    pub fn decay_energy_mev(&self, nucid: u32) -> Option<f64> {
        decay_energy_mev(nucid)
    }

    /// See [`decay_energy_mev_by_name`].
    pub fn decay_energy_mev_by_name(&self, name: &str) -> Option<f64> {
        decay_energy_mev_by_name(name)
    }

    /// See [`decay_branches`].
    pub fn decay_branches(&self, nucid: u32) -> Option<Vec<DecayBranch>> {
        decay_branches(nucid)
    }

    /// See [`decay_branches_by_name`].
    pub fn decay_branches_by_name(&self, name: &str) -> Option<Vec<DecayBranch>> {
        decay_branches_by_name(name)
    }

    /// See [`branching_fraction`].
    pub fn branching_fraction(&self, parent: u32, progeny: u32) -> Option<f64> {
        branching_fraction(parent, progeny)
    }

    /// See [`branching_fraction_by_name`].
    pub fn branching_fraction_by_name(&self, parent: &str, progeny: &str) -> Option<f64> {
        branching_fraction_by_name(parent, progeny)
    }
}

/// Zero-sized façade over the dose-factor lookups ([`dose_factor`],
/// [`dose_f1`], [`dose_lung_model`]).
///
/// Mirrors [`DecayData`]; the material crate implements its `DoseProvider`
/// trait for this façade so analytics get dose factors with no circular deps.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DoseData;

impl DoseData {
    /// See [`dose_entry`].
    pub fn dose_entry(
        &self,
        nucid: u32,
        pathway: DosePathway,
        source: DoseSource,
    ) -> Option<DoseEntry> {
        dose_entry(nucid, pathway, source)
    }

    /// See [`dose_factor`].
    pub fn dose_factor(&self, nucid: u32, pathway: DosePathway, source: DoseSource) -> Option<f64> {
        dose_factor(nucid, pathway, source)
    }

    /// See [`dose_factor_by_name`].
    pub fn dose_factor_by_name(
        &self,
        name: &str,
        pathway: DosePathway,
        source: DoseSource,
    ) -> Option<f64> {
        dose_factor_by_name(name, pathway, source)
    }

    /// See [`dose_f1`].
    pub fn dose_f1(&self, nucid: u32, source: DoseSource) -> Option<f64> {
        dose_f1(nucid, source)
    }

    /// See [`dose_f1_by_name`].
    pub fn dose_f1_by_name(&self, name: &str, source: DoseSource) -> Option<f64> {
        dose_f1_by_name(name, source)
    }

    /// See [`dose_lung_model`].
    pub fn dose_lung_model(&self, nucid: u32, source: DoseSource) -> Option<char> {
        dose_lung_model(nucid, source)
    }

    /// See [`dose_lung_model_by_name`].
    pub fn dose_lung_model_by_name(&self, name: &str, source: DoseSource) -> Option<char> {
        dose_lung_model_by_name(name, source)
    }
}

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

    const H1: u32 = 10_010_000;
    const O16: u32 = 80_160_000;
    const FE56: u32 = 260_560_000;
    const U235: u32 = 922_350_000;

    #[test]
    fn h1_exact_ame2020_value() {
        assert_eq!(atomic_mass(H1), Some(1.007825031_898));
        assert_eq!(atomic_mass_by_name("H1"), Some(1.007825031_898));
    }

    #[test]
    fn heavy_nuclide_spot_values() {
        assert_eq!(atomic_mass(U235), Some(235.043_928_117));
        assert_eq!(atomic_mass(FE56), Some(55.934_935_537));
        assert_eq!(atomic_mass(O16), Some(15.994_914_619_26));
    }

    #[test]
    fn non_nuclides_and_unknown_ids_return_none() {
        // Free neutron row (Z = 0) is excluded from the vendored table.
        assert_eq!(atomic_mass(10_000), None);
        assert_eq!(atomic_mass(999_999_999), None);
        // Isomers with their own ENDF tape resolve to the isomer mass;
        // isomers without one fall back to the ground-state mass.
        let ba_m1 = NuclideId::from_name("Ba137_m1").unwrap().nucid();
        assert!(atomic_mass(ba_m1).unwrap() > atomic_mass(561_370_000).unwrap());
        assert!(atomic_mass_by_name("U235_m1").unwrap() > atomic_mass(U235).unwrap());
        assert_eq!(
            atomic_mass_by_name("Pm137_m1"),
            atomic_mass_by_name("Pm137")
        );
    }

    #[test]
    fn by_name_agrees_with_nucid_lookup() {
        for name in ["H1", "O16", "Fe56", "U235", "Og294"] {
            let nucid = NuclideId::from_name(name).unwrap().nucid();
            assert_eq!(atomic_mass_by_name(name), atomic_mass(nucid), "{name}");
        }
    }

    #[test]
    fn natural_abundance_spot_values() {
        assert_eq!(natural_abundance(U235), Some(0.007_204));
        assert_eq!(natural_abundance_by_name("U235"), Some(0.007_204));
        assert_eq!(natural_abundance(O16), Some(0.997_620_6));
        assert_eq!(natural_abundance_by_name("H1"), Some(0.999_844_26));
        // The lone naturally occurring isomer.
        assert_eq!(natural_abundance_by_name("Ta180_m1"), Some(0.000_120_1));
    }

    #[test]
    fn natural_abundance_unknown_returns_none() {
        assert_eq!(natural_abundance(999_999_999), None);
        assert_eq!(natural_abundance_by_name("C14"), None);
        assert_eq!(natural_abundance_by_name("Xx999"), None);
    }

    #[test]
    fn abundances_sum_to_one_per_element() {
        let mut totals = [0.0_f64; 119];
        for (nucid, frac) in abundance_table() {
            totals[NuclideId::from_nucid(*nucid).z() as usize] += frac;
        }
        for (z, total) in totals.iter().enumerate() {
            if *total > 0.0 {
                assert!(
                    (total - 1.0).abs() < 1e-6,
                    "Z={z} abundances sum to {total}"
                );
            }
        }
    }

    #[test]
    fn mass_sanity_sweep() {
        let table = mass_table();
        for (nucid, mass) in table {
            let id = NuclideId::from_nucid(*nucid);
            // Ground states plus ENDF-taped isomers (state 1-9); the
            // excitation energy is at most MeV against a GeV-scale mass.
            assert!(id.state() <= 9, "state out of range: {nucid}");
            let (lo, hi) = (0.9 * f64::from(id.a()), 1.2 * f64::from(id.a()));
            assert!(*mass > lo && *mass < hi, "{} mass {mass}", id.to_name());
            assert!(*mass > 0.0);
        }
    }

    #[test]
    fn vendored_row_counts_match_tables() {
        let mass_rows = AME2020_TSV
            .lines()
            .filter(|l| !l.is_empty() && !l.starts_with('#'))
            .count();
        let abundance_rows = NATURAL_ABUNDANCE_TSV
            .lines()
            .filter(|l| !l.is_empty() && !l.starts_with('#'))
            .count();
        assert_eq!(mass_table().len(), mass_rows);
        assert_eq!(mass_rows, 3557 + 738);
        assert_eq!(abundance_table().len(), abundance_rows);
        assert_eq!(abundance_rows, 289);
    }

    #[test]
    fn isomer_masses_follow_ground_plus_excitation() {
        // Ba137_m1: ELIS 661659 eV on a 136.905827207 u ground state.
        let ba = NuclideId::from_name("Ba137").unwrap().nucid();
        let ba_m1 = NuclideId::from_name("Ba137_m1").unwrap().nucid();
        let expected = atomic_mass(ba).unwrap() + 0.661_659 / MEV_PER_U;
        assert!((atomic_mass(ba_m1).unwrap() - expected).abs() < 1e-9);
        // Second isomers resolve too (ENDF m2 tapes, e.g. Cu70_m2).
        let cu_m2 = NuclideId::from_name("Cu70_m2").unwrap().nucid();
        assert!(atomic_mass(cu_m2).unwrap() >= atomic_mass_by_name("Cu70").unwrap());
        // Pm137m has no ENDF/B-VIII.0 isomer tape: absent, no fill-in, so
        // the lookup falls back to the ground-state mass.
        assert_eq!(
            atomic_mass_by_name("Pm137_m1"),
            atomic_mass_by_name("Pm137")
        );
        // Stable Te123 keeps its ground mass; its isomer has its own row.
        assert!(atomic_mass_by_name("Te123_m1").unwrap() > atomic_mass_by_name("Te123").unwrap());
    }

    #[test]
    fn ame_masses_facade_delegates() {
        let provider = AmeMasses;
        assert_eq!(provider.atomic_mass(U235), atomic_mass(U235));
        assert_eq!(provider.atomic_mass_by_name("Fe56"), Some(55.934_935_537));
        assert_eq!(provider.natural_abundance(O16), Some(0.997_620_6));
        assert_eq!(provider.natural_abundance_by_name("Nope1"), None);
    }

    const U238: u32 = 922_380_000;
    const I135: u32 = 531_350_000;
    const CS137: u32 = 551_370_000;

    #[test]
    fn half_life_spot_values() {
        // U-238: 4.468e9 yr × 3.1557e7 s/yr ≈ 1.4100e17 s.
        let t_u238 = half_life(U238).unwrap();
        assert!((t_u238 - 1.409_99e17).abs() / t_u238 < 1e-9);
        // I-135: chain fixture value 2.3652e4 s.
        assert_eq!(half_life(I135), Some(23_652.0));
        // Cs-135: 7.25825e13 s (≈ 2.3 Myr).
        let t_cs135 = half_life_by_name("Cs135").unwrap();
        assert!((t_cs135 - 7.258_25e13).abs() / t_cs135 < 1e-12);
        // Cs-137: 30.08 yr ≈ 9.49e8 s, in the production Julian-year
        // convention (AD-11: 31,557,600 s/yr; the Gregorian divisor it
        // replaces differed by ~6e-4 yr against this 0.01 yr tolerance).
        let t_cs137 = half_life(CS137).unwrap();
        assert!((t_cs137 / 3.155_76e7 - 30.08).abs() < 0.01, "{t_cs137}");
        // Isomers carry their own rows.
        assert_eq!(half_life_by_name("Am242_m1"), Some(4_449_622_000.0));
    }

    #[test]
    fn stable_and_unknown_nuclides_have_no_half_life() {
        // Stable nuclides are absent from the vendored table.
        assert_eq!(half_life(O16), None);
        assert_eq!(half_life_by_name("Fe56"), None);
        assert_eq!(decay_constant(H1), None);
        assert_eq!(half_life(999_999_999), None);
        assert_eq!(half_life_by_name("Xx999"), None);
    }

    #[test]
    fn decay_constant_is_ln2_over_half_life() {
        for nucid in [
            U238,
            I135,
            CS137,
            NuclideId::from_name("Te132").unwrap().nucid(),
        ] {
            let t_half = half_life(nucid).unwrap();
            let lambda = decay_constant(nucid).unwrap();
            let rel = (lambda * t_half - std::f64::consts::LN_2).abs() / std::f64::consts::LN_2;
            assert!(rel < 1e-12, "nucid {nucid}: rel err {rel}");
        }
        let lam = decay_constant_by_name("I135").unwrap();
        assert!((lam - std::f64::consts::LN_2 / 23_652.0).abs() < 1e-18);
    }

    #[test]
    fn shorter_half_life_gives_larger_decay_constant() {
        // Te132 (3.2 d) vs I135 (6.57 h) vs Xe135 (9.14 h) chain ordering.
        let te = NuclideId::from_name("Te132").unwrap().nucid();
        let xe = NuclideId::from_name("Xe135").unwrap().nucid();
        let (t_te, t_i, t_xe) = (
            half_life(te).unwrap(),
            half_life(I135).unwrap(),
            half_life(xe).unwrap(),
        );
        assert!(t_te > t_xe && t_i < t_xe);
        assert!(decay_constant(te).unwrap() < decay_constant(xe).unwrap());
        assert!(decay_constant(xe).unwrap() < decay_constant(I135).unwrap());
    }

    #[test]
    fn half_lives_are_positive_and_finite() {
        for (nucid, t_half) in half_life_table() {
            assert!(*t_half > 0.0 && t_half.is_finite(), "{nucid}: {t_half}");
            let id = NuclideId::from_nucid(*nucid);
            assert!(id.a() >= id.z(), "{}", id.to_name());
        }
    }

    #[test]
    fn vendored_half_life_row_count_matches_table() {
        let rows = HALF_LIFE_TSV
            .lines()
            .filter(|l| !l.is_empty() && !l.starts_with('#'))
            .count();
        assert_eq!(half_life_table().len(), rows);
        assert_eq!(rows, 3561);
    }

    #[test]
    fn neutron_capture_q_value_anchors() {
        // H1(n,γ): textbook 2.224566 MeV.
        let q_h = q_value_neutron_capture(H1).unwrap();
        assert!((q_h - 2.224_566).abs() < 1e-3, "{q_h}");
        // U238(n,γ): ≈ 4.8 MeV.
        let q_u238 = q_value_neutron_capture(U238).unwrap();
        assert!((q_u238 - 4.806_382).abs() < 1e-3, "{q_u238}");
        assert!(q_u238 > 4.79 && q_u238 < 4.81);
        // O16(n,γ): 4.143 MeV.
        let q_o16 = q_value_neutron_capture(O16).unwrap();
        assert!((q_o16 - 4.143_080).abs() < 1e-3, "{q_o16}");
    }

    #[test]
    fn capture_q_value_matches_manual_formula() {
        let expected = (atomic_mass(U238).unwrap() + NEUTRON_MASS_U
            - atomic_mass(922_390_000).unwrap())
            * MEV_PER_U;
        let q = q_value_neutron_capture(U238).unwrap();
        assert!((q - expected).abs() < 1e-9);
        assert_eq!(q_value_neutron_capture_by_name("U238"), Some(q));
        assert_eq!(neutron_mass_u(), NEUTRON_MASS_U);
        assert_eq!(neutron_mass_u(), 1.008_664_915_95);
    }

    #[test]
    fn capture_q_value_missing_or_bad_targets_return_none() {
        // Product nuclide beyond the chart of nuclides (no A+1 mass row).
        let he10 = NuclideId::from_name("He10").unwrap().nucid();
        assert_eq!(atomic_mass(he10 + 10_000), None);
        assert_eq!(q_value_neutron_capture(he10), None);
        // Metastable states and non-nuclides are rejected outright.
        assert_eq!(q_value_neutron_capture(922_350_001), None);
        assert_eq!(q_value_neutron_capture(10_000), None);
        assert_eq!(q_value_neutron_capture_by_name("U235_m1"), None);
        assert_eq!(q_value_neutron_capture_by_name("Nope1"), None);
    }

    #[test]
    fn alpha_q_value_anchors() {
        // Literature: U238 α → 4.2698 MeV, Po210 → 5.4075 MeV,
        // Ra226 → 4.8706 MeV; atomic-mass formula reproduces all three.
        for (name, lit) in [
            ("U238", 4.269_858),
            ("Po210", 5.407_530),
            ("Ra226", 4.870_703),
        ] {
            let q = q_value_alpha_by_name(name).unwrap();
            assert!((q - lit).abs() < 1e-3, "{name}: {q} vs {lit}");
        }
        assert_eq!(q_value_alpha(U238), q_value_alpha_by_name("U238"));
    }

    #[test]
    fn alpha_q_value_rejects_light_and_metastable() {
        // Too light to alpha-decay within the table's Z/A domain.
        assert_eq!(q_value_alpha(H1), None);
        assert_eq!(q_value_alpha_by_name("He4"), None);
        assert_eq!(q_value_alpha(922_350_001), None);
        assert_eq!(q_value_alpha_by_name("Am242_m1"), None);
        // Endothermic "decay" still yields the (negative) Q-value:
        // O16 → C12 + He4 costs ≈ 7.162 MeV.
        let q_o16 = q_value_alpha_by_name("O16").unwrap();
        assert!((q_o16 + 7.162).abs() < 1e-3, "{q_o16}");
    }

    #[test]
    fn decay_data_facade_delegates() {
        let provider = DecayData;
        assert_eq!(provider.half_life(I135), Some(23_652.0));
        assert_eq!(provider.half_life_by_name("I135"), Some(23_652.0));
        assert_eq!(provider.decay_constant(U238), decay_constant(U238));
        assert_eq!(provider.decay_constant_by_name("Fe56"), None);
    }

    #[test]
    fn simple_xs_h1_anchors_within_ten_percent() {
        // Generated values: H free-atom thermal ~20.84 b, ~0.69 b at 14 MeV.
        let (thermal, fast) = simple_xs_by_name("H1").unwrap();
        assert!((thermal - 20.84).abs() / 20.84 < 0.05, "{thermal}");
        assert!((fast - 0.687).abs() / 0.687 < 0.05, "{fast}");
        assert_eq!(simple_xs(H1), Some((thermal, fast)));
    }

    #[test]
    fn simple_xs_absorber_and_actinide_bands() {
        // Strong absorbers dominate at thermal; actinide totals cluster ~6 b
        // at 14 MeV (ENDF/B-VII.1 MF3/MT1).
        let (b10_th, _) = simple_xs_by_name("B10").unwrap();
        assert!(b10_th > 3700.0 && b10_th < 3950.0, "{b10_th}");
        let (u235_th, u235_fast) = simple_xs_by_name("U235").unwrap();
        assert!(u235_th > 680.0 && u235_th < 710.0, "{u235_th}");
        assert!(u235_fast > 5.0 && u235_fast < 7.0, "{u235_fast}");
        let (pu239_th, _) = simple_xs_by_name("Pu239").unwrap();
        assert!(pu239_th > 1000.0 && pu239_th < 1050.0, "{pu239_th}");
        let (o16_th, _) = simple_xs_by_name("O16").unwrap();
        assert!(o16_th > 3.5 && o16_th < 4.0, "{o16_th}");
    }

    #[test]
    fn simple_xs_coverage_gaps_are_documented() {
        // Resonance absorbers without NIST rows, and isomers, are absent.
        for name in ["Cs137", "Co60", "I135", "Xe135", "Am242_m1"] {
            assert_eq!(simple_xs_by_name(name), None, "{name}");
        }
    }

    #[test]
    fn simple_xs_unknown_returns_none() {
        assert_eq!(simple_xs(999_999_999), None);
        assert_eq!(simple_xs_by_name("Og294"), None);
        assert_eq!(simple_xs_by_name("Xx999"), None);
    }

    #[test]
    fn scattering_length_nist_anchors() {
        // NIST NCNR bound lengths (Sears 1992): H1, D, O16.
        let (h_coh, h_inc) = scattering_length_by_name("H1").unwrap();
        assert!((h_coh - -3.7406).abs() < 1e-3, "{h_coh}");
        assert!((h_inc - 25.274).abs() < 1e-3, "{h_inc}");
        let (d_coh, d_inc) = scattering_length_by_name("H2").unwrap();
        assert!((d_coh - 6.671).abs() < 1e-2, "{d_coh}");
        assert!((d_inc - 4.04).abs() < 1e-2, "{d_inc}");
        let (o_coh, o_inc) = scattering_length_by_name("O16").unwrap();
        assert!((o_coh - 5.803).abs() < 1e-2, "{o_coh}");
        assert_eq!(o_inc, 0.0);
    }

    #[test]
    fn scattering_length_unknown_returns_none() {
        assert_eq!(scattering_length(999_999_999), None);
        assert_eq!(scattering_length_by_name("Og294"), None);
        assert_eq!(scattering_length_by_name("Xx999"), None);
    }

    #[test]
    fn decay_energy_anchors_within_tolerance() {
        // ENDF/B-VII.1 MF8/MT457 prompt means: Cs137 excludes the 662 keV
        // daughter gamma (Ba137_m1's row), Co60 ~2.60, H3 ~0.0057 MeV.
        let cs = decay_energy_mev_by_name("Cs137").unwrap();
        assert!((cs - 0.1794).abs() / 0.1794 < 0.05, "{cs}");
        let co = decay_energy_mev_by_name("Co60").unwrap();
        assert!((co - 2.6006).abs() / 2.6006 < 0.05, "{co}");
        let h3 = decay_energy_mev_by_name("H3").unwrap();
        assert!((h3 - 0.00569).abs() / 0.00569 < 0.05, "{h3}");
    }

    #[test]
    fn decay_energy_stable_and_unknown_return_none() {
        assert_eq!(decay_energy_mev(O16), None);
        assert_eq!(decay_energy_mev(FE56), None);
        assert_eq!(decay_energy_mev(999_999_999), None);
        assert_eq!(decay_energy_mev_by_name("Fe56"), None);
        assert_eq!(decay_energy_mev_by_name("Xx999"), None);
    }

    #[test]
    fn decay_energy_isomers_carry_own_rows() {
        // Ba137m prompt 661 keV gamma (×0.9 branching) vs Cs137 prompt only.
        let ba_m1 = decay_energy_mev_by_name("Ba137_m1").unwrap();
        assert!((ba_m1 - 0.6614).abs() / 0.6614 < 0.05, "{ba_m1}");
        assert!(decay_energy_mev_by_name("Ba137").is_none());
        // Second isomers resolve too (ENDF m2 tapes, e.g. Am242_m2).
        let am_m2 = NuclideId::from_name("Am242_m2").unwrap().nucid();
        assert_eq!(
            decay_energy_mev_by_name("Am242_m2"),
            decay_energy_mev(am_m2)
        );
        assert!(decay_energy_mev(am_m2).is_some());
    }

    #[test]
    fn vendored_generated_row_counts_match_tables() {
        for (tsv, table_len, expected) in [
            (SIMPLE_XS_TSV, simple_xs_table().len(), 241),
            (SCATTERING_LENGTHS_TSV, scattering_length_table().len(), 267),
            (DECAY_ENERGY_TSV, decay_energy_table().len(), 3557),
        ] {
            let rows = tsv
                .lines()
                .filter(|l| !l.is_empty() && !l.starts_with('#'))
                .count();
            assert_eq!(table_len, rows);
            assert_eq!(rows, expected);
        }
    }

    #[test]
    fn generated_by_name_agrees_with_nucid_lookup() {
        for name in ["H1", "B10", "O16", "Fe56", "U235", "Pu239"] {
            let nucid = NuclideId::from_name(name).unwrap().nucid();
            assert_eq!(simple_xs_by_name(name), simple_xs(nucid), "{name}");
            assert_eq!(
                scattering_length_by_name(name),
                scattering_length(nucid),
                "{name}"
            );
        }
        for name in ["H3", "Co60", "Cs137"] {
            let nucid = NuclideId::from_name(name).unwrap().nucid();
            assert_eq!(
                decay_energy_mev_by_name(name),
                decay_energy_mev(nucid),
                "{name}"
            );
        }
    }

    #[test]
    fn decay_data_facade_delegates_decay_energy() {
        let provider = DecayData;
        assert_eq!(provider.decay_energy_mev(CS137), decay_energy_mev(CS137));
        let co60 = provider.decay_energy_mev_by_name("Co60").unwrap();
        assert!((co60 - 2.6006).abs() / 2.6006 < 0.05, "{co60}");
        assert_eq!(provider.decay_energy_mev_by_name("Fe56"), None);
    }

    #[test]
    fn decay_branch_k40_two_branches_sum_to_one() {
        // ENDF/B-VIII.0 NDK values, verbatim: beta- 0.8914 to Ca40 and
        // EC/beta+ 0.1086 to Ar40.
        let k40 = NuclideId::from_name("K40").unwrap().nucid();
        let branches = decay_branches(k40).unwrap();
        assert_eq!(branches.len(), 2);
        let ca40 = NuclideId::from_name("Ca40").unwrap().nucid();
        let ar40 = NuclideId::from_name("Ar40").unwrap().nucid();
        assert!(branches.contains(&DecayBranch {
            progeny: ca40,
            branching_fraction: 0.8914,
            mode: DecayBranchMode::BetaMinus,
        }));
        assert!(branches.contains(&DecayBranch {
            progeny: ar40,
            branching_fraction: 0.1086,
            mode: DecayBranchMode::EcBetaPlus,
        }));
        let total: f64 = branches.iter().map(|b| b.branching_fraction).sum();
        assert!((total - 1.0).abs() < 1e-9, "{total}");
        assert_eq!(branching_fraction(k40, ca40), Some(0.8914));
        assert_eq!(branching_fraction_by_name("K40", "Ar40"), Some(0.1086));
        assert_eq!(branching_fraction_by_name("K40", "K40"), None);
    }

    #[test]
    fn decay_branch_spot_modes() {
        use DecayBranchMode as M;
        // Single alpha branch with unit BR.
        let es254 = decay_branches_by_name("Es254").unwrap();
        assert_eq!(es254.len(), 1);
        assert_eq!(es254[0].mode, M::Alpha);
        assert_eq!(es254[0].branching_fraction, 1.0);
        assert_eq!(NuclideId::from_nucid(es254[0].progeny).to_name(), "Bk250");
        // Isomeric transition keeps Z/A.
        let ba = decay_branches_by_name("Ba137_m1").unwrap();
        assert_eq!(ba.len(), 1);
        assert_eq!(ba[0].mode, M::It);
        assert_eq!(NuclideId::from_nucid(ba[0].progeny).to_name(), "Ba137");
        // Delayed-neutron branch collapses to the beta- initial event with
        // the emitted neutron subtracted from the progeny.
        let he8 = decay_branches_by_name("He8").unwrap();
        assert_eq!(he8.len(), 2);
        let names: Vec<String> = he8
            .iter()
            .map(|b| NuclideId::from_nucid(b.progeny).to_name())
            .collect();
        assert!(names.contains(&"Li8".to_string()), "{names:?}");
        assert!(names.contains(&"Li7".to_string()), "{names:?}");
        assert!(he8.iter().all(|b| b.mode == M::BetaMinus));
        // Es254m mixes alpha, beta-, EC, and IT; the SF branch is dropped.
        let es_m1 = decay_branches_by_name("Es254_m1").unwrap();
        assert_eq!(es_m1.len(), 4);
        assert!(es_m1.iter().all(|b| b.mode != M::Sf));
        assert_eq!(branching_fraction_by_name("Es254_m1", "Fm254"), Some(0.98));
    }

    #[test]
    fn decay_branch_stable_and_unknown_have_no_rows() {
        assert_eq!(decay_branches_by_name("Fe56"), None);
        assert_eq!(decay_branches_by_name("O16"), None);
        // Zero-half-life evaluation dummies stay absent (stable-absent rule).
        assert_eq!(decay_branches_by_name("Te123"), None);
        assert_eq!(decay_branches_by_name("Ca46"), None);
        assert_eq!(branching_fraction_by_name("Fe56", "Fe56"), None);
        assert_eq!(decay_branches_by_name("Xx999"), None);
    }

    #[test]
    fn decay_branch_parents_agree_with_half_life_table() {
        // Every branch parent carries a half-life row (same VIII.0 basis);
        // progeny may be stable (absent) — only names must parse.
        for (parent, branches) in decay_branch_table() {
            assert!(
                half_life(*parent).is_some(),
                "parent without half-life: {parent}"
            );
            assert!(!branches.is_empty());
            for b in branches {
                assert!(
                    (0.0..=1.0).contains(&b.branching_fraction),
                    "BF range: {}",
                    b.branching_fraction
                );
                let id = NuclideId::from_nucid(b.progeny);
                assert!(id.z() >= 1 && id.a() >= id.z(), "{}", id.to_name());
            }
        }
    }

    #[test]
    fn decay_branch_row_count_matches_table() {
        let rows = DECAY_BRANCHES_TSV
            .lines()
            .filter(|l| !l.is_empty() && !l.starts_with('#'))
            .count();
        let table_rows: usize = decay_branch_table().values().map(Vec::len).sum();
        assert_eq!(table_rows, rows);
        assert_eq!(rows, 5068);
        assert_eq!(decay_branch_table().len(), 3541);
    }

    #[test]
    fn fission_yield_row_count_matches_table() {
        let rows = FISSION_YIELDS_TSV
            .lines()
            .filter(|l| !l.is_empty() && !l.starts_with('#'))
            .count();
        let table = fission_yield_table();
        let table_rows: usize = table.values().map(Vec::len).sum();
        let set_products: usize = table
            .values()
            .flat_map(|sets| sets.iter())
            .map(|s| s.products.len())
            .sum();
        assert_eq!(set_products, rows);
        assert_eq!(rows, 151_490);
        assert_eq!(table.len(), 80);
        assert_eq!(table_rows, 122);
    }

    #[test]
    fn fission_yield_u235_thermal_spot_values() {
        // Hard values read off the ENDF/B-VIII.0 U-235 tape (England
        // ENDF-349 evaluation), thermal (0.0253 eV) set.
        let u235 = NuclideId::from_name("U235").unwrap().nucid();
        let xe135 = NuclideId::from_name("Xe135").unwrap().nucid();
        let sets = fission_yields(
            u235,
            FissionYieldOrigin::NeutronInduced,
            FissionYieldKind::Independent,
        )
        .unwrap();
        assert_eq!(sets.len(), 3); // 0.0253, 5e5, 1.4e7 eV
        let thermal = &sets[0];
        assert_eq!(thermal.energy_ev, 0.0253);
        let xe = thermal
            .products
            .iter()
            .find(|p| p.progeny == xe135)
            .unwrap();
        assert_eq!(xe.yield_fraction, 0.000_785_125);
        assert_eq!(xe.uncertainty, 4.710_75e-05);
        // The independent set sums to ~2.0: two fragments per fission.
        let total: f64 = thermal.products.iter().map(|p| p.yield_fraction).sum();
        assert!((total - 2.0).abs() < 1e-6, "{total}");
        // Asymmetric split: the A <= 116 light peak carries ~1.0.
        let light: f64 = thermal
            .products
            .iter()
            .filter(|p| NuclideId::from_nucid(p.progeny).a() <= 116)
            .map(|p| p.yield_fraction)
            .sum();
        assert!((light - 1.0).abs() < 1e-3, "{light}");
    }

    #[test]
    fn fission_yield_isomer_and_cumulative_spots() {
        use FissionYieldKind as K;
        use FissionYieldOrigin as O;
        // FPS = 1 maps to the GNDS _m1 suffix (Xe135_m1 thermal row).
        let xe_m1 = fission_yield_by_name("U235", "Xe135_m1");
        assert_eq!(xe_m1, Some(0.001_781_22));
        // Cumulative Xe135 (MT459) is the classic ~6.6% value.
        let cum = fission_yields_by_name("U235", O::NeutronInduced, K::Cumulative).unwrap();
        assert_eq!(cum[0].energy_ev, 0.0253);
        let xe135 = NuclideId::from_name("Xe135").unwrap().nucid();
        let row = cum[0].products.iter().find(|p| p.progeny == xe135).unwrap();
        assert_eq!(row.yield_fraction, 0.065_385);
        assert_eq!(row.uncertainty, 0.000_457_695);
        // Cumulative sets do NOT sum to 2.0 (precursor chains feed in).
        let total: f64 = cum[0].products.iter().map(|p| p.yield_fraction).sum();
        assert!(total > 4.0, "{total}");
    }

    #[test]
    fn fission_yield_parents_origins_and_energies() {
        use FissionYieldKind as K;
        use FissionYieldOrigin as O;
        // Pu-239 thermal (Chadwick-Kawano evaluation): 4 energy sets.
        let pu = fission_yields_by_name("Pu239", O::NeutronInduced, K::Independent).unwrap();
        assert_eq!(pu.len(), 4);
        assert_eq!(pu[0].energy_ev, 0.0253);
        let xe135 = NuclideId::from_name("Xe135").unwrap().nucid();
        let row = pu[0].products.iter().find(|p| p.progeny == xe135).unwrap();
        assert_eq!(row.yield_fraction, 0.003_141_31);
        assert_eq!(row.uncertainty, 0.000_125_652);
        // Cf-252 spontaneous: single E = 0 set.
        let cf = fission_yields_by_name("Cf252", O::Spontaneous, K::Independent).unwrap();
        assert_eq!(cf.len(), 1);
        assert_eq!(cf[0].energy_ev, 0.0);
        let row = cf[0].products.iter().find(|p| p.progeny == xe135).unwrap();
        assert_eq!(row.yield_fraction, 0.001_861_45);
        // U-238 lives in BOTH sublibraries: its neutron-induced default is
        // the 5e5 eV set (there is no thermal nfy evaluation), never the
        // spontaneous E = 0 set.
        let u238 = NuclideId::from_name("U238").unwrap().nucid();
        let default = default_fission_yields(u238).unwrap();
        assert_eq!(default.energy_ev, 500_000.0);
        assert!(fission_yields(u238, O::Spontaneous, K::Independent).is_some());
        // U-238 fast set from the tape (14 MeV; the 5e5 spot pins fast[0]).
        let fast = fission_yields(u238, O::NeutronInduced, K::Independent).unwrap();
        assert_eq!(fast.len(), 2);
        assert_eq!(fast[0].energy_ev, 500_000.0);
        assert_eq!(fast[1].energy_ev, 1.4e7);
        let row = fast[1]
            .products
            .iter()
            .find(|p| p.progeny == xe135)
            .unwrap();
        assert_eq!(row.yield_fraction, 0.001_329_1);
        assert_eq!(row.uncertainty, 1.462_01e-04);
    }

    #[test]
    fn fission_yield_default_and_singular_lookups() {
        let u235 = NuclideId::from_name("U235").unwrap().nucid();
        let xe135 = NuclideId::from_name("Xe135").unwrap().nucid();
        let default = default_fission_yields(u235).unwrap();
        assert_eq!(default.energy_ev, 0.0253);
        assert_eq!(fission_yield(u235, xe135), Some(0.000_785_125));
        assert_eq!(fission_yield_by_name("U235", "Xe135"), Some(0.000_785_125));
        assert_eq!(fission_yield_by_name("U235", "Fe56"), None);
        assert_eq!(default_fission_yields_by_name("Fe56"), None);
        // Parents outside the library (non-fissionable or unevaluated).
        assert_eq!(
            fission_yields_by_name("Fe56", Default::default(), Default::default()),
            None
        );
        assert_eq!(default_fission_yields_by_name("Cm247"), None);
        assert_eq!(
            fission_yields_by_name("Xx999", Default::default(), Default::default()),
            None
        );
    }

    #[test]
    fn fission_yield_origin_kind_tokens() {
        use FissionYieldKind as K;
        use FissionYieldOrigin as O;
        assert_eq!(O::parse("n"), Some(O::NeutronInduced));
        assert_eq!(O::parse("SF"), Some(O::Spontaneous));
        assert_eq!(O::parse("spontaneous"), Some(O::Spontaneous));
        assert_eq!(O::parse("x"), None);
        assert_eq!(O::NeutronInduced.as_str(), "n");
        assert_eq!(O::Spontaneous.as_str(), "sf");
        assert_eq!(K::parse("independent"), Some(K::Independent));
        assert_eq!(K::parse("Cumulative"), Some(K::Cumulative));
        assert_eq!(K::parse("x"), None);
        assert_eq!(K::Independent.as_str(), "independent");
        assert_eq!(K::Cumulative.as_str(), "cumulative");
    }

    #[test]
    fn decay_branch_mode_parsing() {
        use DecayBranchMode as M;
        assert_eq!(M::parse("beta-"), Some(M::BetaMinus));
        assert_eq!(M::parse("ec/beta+"), Some(M::EcBetaPlus));
        assert_eq!(M::parse("EC/BETA+"), Some(M::EcBetaPlus));
        assert_eq!(M::parse("alpha"), Some(M::Alpha));
        assert_eq!(M::parse("IT"), Some(M::It));
        assert_eq!(M::parse("it"), Some(M::It));
        assert_eq!(M::parse("sf"), Some(M::Sf));
        assert_eq!(M::parse("n"), Some(M::Neutron));
        assert_eq!(M::parse("p"), Some(M::Proton));
        assert_eq!(M::parse("nope"), None);
        assert_eq!(M::BetaMinus.as_str(), "beta-");
        assert_eq!(M::EcBetaPlus.as_str(), "ec/beta+");
        assert_eq!(M::It.as_str(), "IT");
    }

    #[test]
    fn decay_data_facade_delegates_branches() {
        let provider = DecayData;
        let k40 = NuclideId::from_name("K40").unwrap().nucid();
        assert_eq!(provider.decay_branches(k40), decay_branches(k40));
        assert_eq!(
            provider.decay_branches_by_name("Es254"),
            decay_branches_by_name("Es254")
        );
        assert_eq!(
            provider.branching_fraction_by_name("K40", "Ca40"),
            Some(0.8914)
        );
        assert_eq!(provider.decay_branches_by_name("Fe56"), None);
    }

    #[test]
    fn dose_factor_row_count_matches_table() {
        let rows = DOSE_FACTORS_TSV
            .lines()
            .filter(|l| !l.is_empty() && !l.starts_with('#'))
            .count();
        assert_eq!(dose_table().len(), rows);
        assert_eq!(rows, 1116);
    }

    #[test]
    fn dose_factor_spot_values() {
        use DosePathway as P;
        use DoseSource as S;
        // Raw table factors from the PyNE CSVs (folded +D parents).
        assert_eq!(
            dose_factor_by_name("Co60", P::Ingest, S::Epa),
            Some(2.69e-05)
        );
        assert_eq!(
            dose_factor_by_name("Cs137", P::Inhale, S::Epa),
            Some(3.19e-05)
        );
        assert_eq!(dose_factor_by_name("H3", P::Air, S::Epa), Some(4.41e-012));
        assert_eq!(dose_factor_by_name("K40", P::Soil, S::Epa), Some(4.33e02));
    }

    #[test]
    fn dose_factor_missing_air_is_minus_one_sentinel() {
        use DosePathway as P;
        use DoseSource as S;
        // Air is EPA-only: GENII/DOE air rows are -1 sentinels (PyNE).
        let h3 = NuclideId::from_name("H3").unwrap().nucid();
        assert_eq!(dose_factor(h3, P::Air, S::Genii), Some(-1.0));
        assert_eq!(dose_factor(h3, P::Air, S::Doe), Some(-1.0));
        // Unknown nuclides have no row at all.
        assert_eq!(dose_factor(999_999_999, P::Ingest, S::Epa), None);
        assert_eq!(dose_factor_by_name("Fe56", P::Ingest, S::Epa), None);
        assert_eq!(dose_factor_by_name("Xx999", P::Ingest, S::Epa), None);
    }

    #[test]
    fn dose_aux_columns() {
        use DoseSource as S;
        // f1 lives on ingest rows; lung model on inhale rows.
        assert_eq!(dose_f1_by_name("Co60", S::Epa), Some(0.3));
        assert_eq!(dose_f1_by_name("H3", S::Epa), Some(1.0));
        assert_eq!(dose_lung_model_by_name("Co60", S::Epa), Some('Y'));
        assert_eq!(dose_lung_model_by_name("H3", S::Epa), Some('V'));
        assert_eq!(dose_lung_model_by_name("C14", S::Epa), Some('O'));
        // Air/soil rows carry neither aux column.
        let h3 = NuclideId::from_name("H3").unwrap().nucid();
        assert_eq!(dose_entry(h3, DosePathway::Air, S::Epa).unwrap().f1, None);
        assert_eq!(
            dose_entry(h3, DosePathway::Air, S::Epa).unwrap().lung_model,
            None
        );
    }

    #[test]
    fn dose_pathway_source_parsing() {
        assert_eq!(DosePathway::parse("air"), Some(DosePathway::Air));
        assert_eq!(DosePathway::parse("ext_air"), Some(DosePathway::Air));
        assert_eq!(DosePathway::parse("ext_soil"), Some(DosePathway::Soil));
        assert_eq!(DosePathway::parse("INGEST"), Some(DosePathway::Ingest));
        assert_eq!(DosePathway::parse("inhale"), Some(DosePathway::Inhale));
        assert_eq!(DosePathway::parse("nope"), None);
        assert_eq!(DoseSource::parse("epa"), Some(DoseSource::Epa));
        assert_eq!(DoseSource::parse("DOE"), Some(DoseSource::Doe));
        assert_eq!(DoseSource::parse("genii"), Some(DoseSource::Genii));
        assert_eq!(DoseSource::from_int(0), Some(DoseSource::Epa));
        assert_eq!(DoseSource::from_int(1), Some(DoseSource::Doe));
        assert_eq!(DoseSource::from_int(2), Some(DoseSource::Genii));
        assert_eq!(DoseSource::from_int(3), None);
        assert_eq!(DoseSource::Epa.to_int(), 0);
    }

    #[test]
    fn dose_data_facade_delegates() {
        use DosePathway as P;
        use DoseSource as S;
        let provider = DoseData;
        let co60 = NuclideId::from_name("Co60").unwrap().nucid();
        assert_eq!(
            provider.dose_factor(co60, P::Ingest, S::Epa),
            dose_factor(co60, P::Ingest, S::Epa)
        );
        assert_eq!(
            provider.dose_factor_by_name("K40", P::Soil, S::Epa),
            Some(4.33e02)
        );
        assert_eq!(provider.dose_f1_by_name("H3", S::Epa), Some(1.0));
        assert_eq!(provider.dose_lung_model_by_name("H3", S::Epa), Some('V'));
        assert_eq!(
            provider.dose_factor_by_name("Fe56", P::Ingest, S::Epa),
            None
        );
    }
}