Skip to main content

nucleide_nuclei/
lib.rs

1#![warn(missing_docs)]
2//! Nuclide identification and naming conventions.
3//!
4//! Canonical representation is the `nucid`: a single
5//! `u32` of the form `(Z*1000 + A) * 10_000 + state`, i.e. the zero-padded
6//! six-digit ZZAAAM block followed by a four-digit tail holding the
7//! metastable state (e.g. U-235 → 922350000, Am-242m → 952420001).
8//! Chosen for compactness, hashing, and direct compatibility with the
9//! integer ids used across legacy codes.
10//!
11//! Scope:
12//! - id ↔ name ("U235", "Am242_m1") conversions
13//! - id ↔ zzaaam (922350) conversions
14//! - element symbol/number tables
15//! - naming dialects (MCNP ZAID, Serpent, FLUKA, NIST, Cinder, ALARA), reaction names
16
17use std::fmt;
18
19pub mod armi;
20pub mod data;
21pub mod dialects;
22pub mod fgr15;
23pub mod particles;
24pub mod rxname;
25
26pub use dialects::DialectError;
27pub use particles::Error as ParticlesError;
28pub use rxname::Error as RxnameError;
29
30/// Element symbols indexed by atomic number (`ELEMENTS[z]`); index 0 is unused.
31pub const ELEMENTS: [&str; 119] = [
32    "", "H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg", "Al", "Si", "P", "S",
33    "Cl", "Ar", "K", "Ca", "Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu", "Zn", "Ga", "Ge",
34    "As", "Se", "Br", "Kr", "Rb", "Sr", "Y", "Zr", "Nb", "Mo", "Tc", "Ru", "Rh", "Pd", "Ag", "Cd",
35    "In", "Sn", "Sb", "Te", "I", "Xe", "Cs", "Ba", "La", "Ce", "Pr", "Nd", "Pm", "Sm", "Eu", "Gd",
36    "Tb", "Dy", "Ho", "Er", "Tm", "Yb", "Lu", "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au", "Hg",
37    "Tl", "Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "Ac", "Th", "Pa", "U", "Np", "Pu", "Am", "Cm",
38    "Bk", "Cf", "Es", "Fm", "Md", "No", "Lr", "Rf", "Db", "Sg", "Bh", "Hs", "Mt", "Ds", "Rg", "Cn",
39    "Nh", "Fl", "Mc", "Lv", "Ts", "Og",
40];
41
42/// Result alias for the `nuclei` crate.
43pub type Result<T> = std::result::Result<T, Error>;
44
45/// Errors from nuclide parsing/validation.
46#[derive(Debug, Clone, PartialEq, Eq)]
47#[non_exhaustive]
48pub enum Error {
49    /// Atomic number outside 1..=118.
50    BadZ(u32),
51    /// Mass number smaller than the atomic number.
52    BadA {
53        /// Atomic number.
54        z: u32,
55        /// Mass number.
56        a: u32,
57    },
58    /// Mass number above the 3-digit AAA limit (> 999).
59    MassNumberTooLarge(u32),
60    /// Metastable state index above the supported range (> 9).
61    BadState(u32),
62    /// Name contained no digits (no mass number).
63    MissingMassNumber(String),
64    /// Mass number or state component failed to parse as an integer.
65    BadNumber(String),
66    /// Element symbol not recognized.
67    UnknownElement(String),
68}
69
70impl fmt::Display for Error {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        match self {
73            Error::BadZ(z) => write!(f, "atomic number {z} out of range 1..=118"),
74            Error::BadA { z, a } => write!(f, "mass number {a} < atomic number {z}"),
75            Error::MassNumberTooLarge(a) => write!(f, "mass number {a} > 999 unsupported"),
76            Error::BadState(s) => write!(f, "metastable state {s} > 9 unsupported"),
77            Error::MissingMassNumber(s) => write!(f, "no mass number in name `{s}`"),
78            Error::BadNumber(s) => write!(f, "invalid numeric component `{s}`"),
79            Error::UnknownElement(s) => write!(f, "unknown element symbol `{s}`"),
80        }
81    }
82}
83
84impl std::error::Error for Error {}
85
86/// A canonical nuclide identifier.
87///
88/// Layout (`nucid = (Z*1000 + A) * 10_000 + state`):
89/// - H-1   → 10010000
90/// - U-235 → 922350000
91/// - Am-242m → 952420001
92#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
93pub struct NuclideId(u32);
94
95impl NuclideId {
96    /// Construct and validate a [`NuclideId`] from components.
97    ///
98    /// Enforces `1 <= Z <= 118`, `Z <= A <= 999`, and `S <= 9`. The
99    /// `A <= 999` bound keeps the packed value within `u32` and preserves
100    /// the 3-digit AAA invariant used by the zzaaam/zzllaaam dialects.
101    pub const fn new(z: u32, a: u32, state: u32) -> Result<Self> {
102        if z == 0 || z > 118 {
103            return Err(Error::BadZ(z));
104        }
105        if a < z {
106            return Err(Error::BadA { z, a });
107        }
108        if a > 999 {
109            return Err(Error::MassNumberTooLarge(a));
110        }
111        if state > 9 {
112            return Err(Error::BadState(state));
113        }
114        Ok(Self((z * 1000 + a) * 10_000 + state))
115    }
116
117    /// Reconstruct from an existing nucid integer without validation.
118    ///
119    /// This is a raw bit-cast: invalid bit patterns yield meaningless
120    /// components from [`z`](Self::z), [`a`](Self::a), and [`state`](Self::state).
121    /// Use [`new`](Self::new) for validated construction.
122    ///
123    /// The id stays usable: [`to_name`](Self::to_name) and
124    /// [`armi::nucid_to_armi_label`] render
125    /// such ids with a diagnostic `Z{z}A{a}[m{s}]` fallback instead of
126    /// panicking. Use [`try_from_nucid`](Self::try_from_nucid) (or
127    /// [`is_valid`](Self::is_valid)) when the integer comes from untrusted
128    /// input.
129    pub const fn from_nucid(nucid: u32) -> Self {
130        Self(nucid)
131    }
132
133    /// Reconstruct from a nucid integer with validation.
134    ///
135    /// Decomposes the integer into `(Z, A, state)` and applies the same
136    /// `1 <= Z <= 118`, `Z <= A <= 999`, `S <= 9` checks as
137    /// [`new`](Self::new) (kept in sync by inspection; the checks are
138    /// inlined because `const fn` cannot match on the `Result`); integers
139    /// with a non-canonical tail (the four low digits above 9, so no
140    /// single-digit state can explain them) fail with [`Error::BadState`].
141    /// Out-of-domain integers fail with the matching [`Error`] instead of
142    /// producing an id whose name rendering falls back to the diagnostic form.
143    pub const fn try_from_nucid(nucid: u32) -> Result<Self> {
144        let tail = nucid % 10_000;
145        if tail > 9 {
146            return Err(Error::BadState(tail));
147        }
148        let z = nucid / 10_000_000;
149        let a = (nucid % 10_000_000) / 10_000;
150        let state = nucid % 10;
151        if z == 0 || z > 118 {
152            return Err(Error::BadZ(z));
153        }
154        if a < z {
155            return Err(Error::BadA { z, a });
156        }
157        if a > 999 {
158            return Err(Error::MassNumberTooLarge(a));
159        }
160        if state > 9 {
161            return Err(Error::BadState(state));
162        }
163        Ok(Self(nucid))
164    }
165
166    /// Whether this id decomposes into validated `(Z, A, state)` components
167    /// (`1 <= Z <= 118`, `Z <= A <= 999`, `S <= 9`, canonical tail).
168    ///
169    /// Raw ids built by [`from_nucid`](Self::from_nucid) may fail this; every
170    /// other constructor guarantees it.
171    pub const fn is_valid(&self) -> bool {
172        if self.0 % 10_000 > 9 {
173            return false;
174        }
175        let z = self.z();
176        let a = self.a();
177        let state = self.state();
178        z != 0 && z <= 118 && a >= z && a <= 999 && state <= 9
179    }
180
181    /// Raw nucid integer (`(Z*1000 + A)*10_000 + state`).
182    pub const fn nucid(&self) -> u32 {
183        self.0
184    }
185
186    /// Atomic number.
187    pub const fn z(&self) -> u32 {
188        self.0 / 10_000_000
189    }
190
191    /// Mass number.
192    pub const fn a(&self) -> u32 {
193        (self.0 % 10_000_000) / 10_000
194    }
195
196    /// Metastable state index (0 = ground).
197    pub const fn state(&self) -> u32 {
198        self.0 % 10
199    }
200
201    /// Six-digit ZZAAAM form (U-235 → 922350, Ba-137m → 561371).
202    pub const fn zzaaam(&self) -> u32 {
203        self.z() * 10_000 + self.a() * 10 + self.state()
204    }
205
206    /// Build from a six-digit ZZAAAM integer.
207    pub fn from_zzaaam(v: u32) -> Result<Self> {
208        let state = v % 10;
209        let rest = v / 10;
210        let a = rest % 1_000;
211        let z = rest / 1_000;
212        Self::new(z, a, state)
213    }
214
215    /// Parse a name such as `"U235"`, `"U-235"`, `"u235"`, `"Am242_m1"`,
216    /// `"Am-242m"`, `"Am242M"`, or `"Ba137m"`.
217    ///
218    /// Dashes are ignored and metastable markers are case-insensitive, so
219    /// this matches PyNE's `name_to_id` normalization for the common forms.
220    pub fn from_name(name: &str) -> Result<Self> {
221        let trimmed = name.trim();
222        let cleaned: String = trimmed.chars().filter(|&c| c != '-').collect();
223        let upper = cleaned.to_ascii_uppercase();
224        let digit_start = upper
225            .find(|c: char| c.is_ascii_digit())
226            .ok_or_else(|| Error::MissingMassNumber(trimmed.to_string()))?;
227        let sym_upper = &upper[..digit_start];
228        let rest = &upper[digit_start..];
229
230        let sym = canonicalize_symbol(sym_upper);
231        let z = element_z(&sym).ok_or_else(|| Error::UnknownElement(sym_upper.to_string()))?;
232
233        // Split mass number from an optional state suffix:
234        // "235" | "242_M1" | "242M" | "137M"
235        let (a_str, state_str) = if let Some((head, tail)) = rest.split_once('_') {
236            // underscore form; tail may start with 'M'
237            let tail = tail.strip_prefix('M').unwrap_or(tail);
238            (head, Some(tail))
239        } else if let Some((head, tail)) = rest.split_once('M') {
240            // bare trailing-M form ("137M"); tail may hold the state index
241            (head, Some(tail))
242        } else {
243            (rest, None)
244        };
245
246        let a: u32 = a_str
247            .parse()
248            .map_err(|_| Error::BadNumber(a_str.to_string()))?;
249        let state = match state_str {
250            None => 0,
251            Some("") => 1,
252            Some(n) => n.parse().map_err(|_| Error::BadNumber(format!("M{n}")))?,
253        };
254
255        Self::new(z, a, state)
256    }
257
258    /// GNDS-style name: `"U235"`, `"Am242_m1"`.
259    ///
260    /// Total over every raw id: validated ids render the canonical name
261    /// (unchanged historical spelling, re-parseable by [`from_name`](Self::from_name));
262    /// raw ids outside the validated `(Z, A, state)` domain render the
263    /// diagnostic fallback `"Z{z}A{a}[m{s}]"`, which `from_name` does not
264    /// parse. The fallback exists so display paths over unchecked integers
265    /// (decay-table progeny, FFI) can never index `ELEMENTS` out of bounds.
266    pub fn to_name(&self) -> String {
267        if self.is_valid() {
268            // `is_valid` pins `1 <= Z <= 118`, so this index is in bounds.
269            let sym = ELEMENTS[self.z() as usize];
270            match self.state() {
271                0 => format!("{}{}", sym, self.a()),
272                s => format!("{}{}_m{}", sym, self.a(), s),
273            }
274        } else {
275            format!("Z{}A{}[m{}]", self.z(), self.a(), self.state())
276        }
277    }
278}
279
280impl fmt::Display for NuclideId {
281    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282        f.write_str(&self.to_name())
283    }
284}
285
286impl std::str::FromStr for NuclideId {
287    type Err = Error;
288    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
289        NuclideId::from_name(s)
290    }
291}
292
293/// Element symbol for atomic number `z`, or `None`.
294pub fn element_symbol(z: u32) -> Option<&'static str> {
295    ELEMENTS
296        .get(z as usize)
297        .and_then(|s| if s.is_empty() { None } else { Some(*s) })
298}
299
300/// Atomic number for an element symbol (case-sensitive), or `None`.
301pub fn element_z(symbol: &str) -> Option<u32> {
302    ELEMENTS.iter().position(|s| *s == symbol).map(|z| z as u32)
303}
304
305/// Convert a free-form element symbol to canonical case for lookup.
306fn canonicalize_symbol(sym: &str) -> String {
307    let mut chars = sym.chars();
308    let mut out = String::with_capacity(sym.len());
309    if let Some(first) = chars.next() {
310        out.extend(first.to_uppercase());
311    }
312    out.push_str(&chars.as_str().to_lowercase());
313    out
314}
315
316#[cfg(test)]
317mod tests {
318    use super::*;
319
320    #[test]
321    fn parse_ground_states() {
322        assert_eq!(NuclideId::from_name("U235").unwrap().nucid(), 922_350_000);
323        assert_eq!(NuclideId::from_name("H1").unwrap().nucid(), 10_010_000);
324        assert_eq!(
325            NuclideId::from_name("Og294").unwrap().nucid(),
326            1_182_940_000
327        );
328    }
329
330    #[test]
331    fn parse_metastables() {
332        let am = NuclideId::from_name("Am242_m1").unwrap();
333        assert_eq!((am.z(), am.a(), am.state()), (95, 242, 1));
334        assert_eq!(am.nucid(), 952_420_001);
335
336        let ba = NuclideId::from_name("Ba137m").unwrap();
337        assert_eq!((ba.z(), ba.a(), ba.state()), (56, 137, 1));
338        assert_eq!(ba.zzaaam(), 561_371);
339    }
340
341    #[test]
342    fn round_trip_display() {
343        for name in ["U235", "H1", "Am242_m1", "Pu239"] {
344            assert_eq!(NuclideId::from_name(name).unwrap().to_name(), name);
345        }
346    }
347
348    #[test]
349    fn zzaaam_round_trip() {
350        let u5 = NuclideId::from_name("U235").unwrap();
351        assert_eq!(u5.zzaaam(), 922_350);
352        assert_eq!(
353            NuclideId::from_zzaaam(922_350).map(|n| n.to_name()),
354            Ok("U235".to_string())
355        );
356    }
357
358    #[test]
359    fn rejects_bad_input() {
360        assert!(matches!(
361            NuclideId::from_name("Xx999"),
362            Err(Error::UnknownElement(_))
363        ));
364        assert!(matches!(
365            NuclideId::from_name("U"),
366            Err(Error::MissingMassNumber(_))
367        ));
368        assert!(matches!(NuclideId::new(0, 1, 0), Err(Error::BadZ(0))));
369        assert!(matches!(NuclideId::new(6, 3, 0), Err(Error::BadA { .. })));
370    }
371
372    #[test]
373    fn elements_table_sanity() {
374        assert_eq!(element_z("U"), Some(92));
375        assert_eq!(element_symbol(92), Some("U"));
376        assert_eq!(element_z("Xx"), None);
377    }
378
379    #[test]
380    fn rejects_mass_number_overflow() {
381        assert!(matches!(
382            NuclideId::new(92, 999_999, 0),
383            Err(Error::MassNumberTooLarge(999_999))
384        ));
385        assert!(matches!(
386            NuclideId::from_name("U999999"),
387            Err(Error::MassNumberTooLarge(999_999))
388        ));
389    }
390
391    #[test]
392    fn parses_pyne_normalized_forms() {
393        assert_eq!(NuclideId::from_name("U-235").unwrap().nucid(), 922_350_000);
394        assert_eq!(NuclideId::from_name("u235").unwrap().nucid(), 922_350_000);
395        assert_eq!(NuclideId::from_name("Am242M").unwrap().nucid(), 952_420_001);
396        assert_eq!(
397            NuclideId::from_name("Am-242M").unwrap().nucid(),
398            952_420_001
399        );
400    }
401
402    #[test]
403    fn try_from_nucid_validates_raw_integers() {
404        // Valid integers pass through untouched.
405        assert_eq!(
406            NuclideId::try_from_nucid(922_350_000).unwrap(),
407            NuclideId::from_nucid(922_350_000)
408        );
409        assert!(NuclideId::try_from_nucid(10_010_000).unwrap().is_valid());
410        assert!(NuclideId::from_nucid(922_350_000).is_valid());
411        // Z out of ELEMENTS range (the `to_name` OOB family).
412        assert!(!NuclideId::from_nucid(0).is_valid());
413        assert!(matches!(NuclideId::try_from_nucid(0), Err(Error::BadZ(0))));
414        assert!(matches!(
415            NuclideId::try_from_nucid(u32::MAX),
416            Err(Error::BadState(7295))
417        ));
418        assert!(matches!(
419            NuclideId::try_from_nucid(1_190_000_000),
420            Err(Error::BadZ(119))
421        ));
422        // A below Z, non-canonical tail (no single-digit state), Z=0 tail.
423        assert!(matches!(
424            NuclideId::try_from_nucid(920_050_000),
425            Err(Error::BadA { z: 92, a: 5 })
426        ));
427        assert!(matches!(
428            NuclideId::try_from_nucid(922_350_010),
429            Err(Error::BadState(10))
430        ));
431        assert!(!NuclideId::from_nucid(920_050_000).is_valid());
432        assert!(!NuclideId::from_nucid(922_350_010).is_valid());
433    }
434
435    #[test]
436    fn to_name_falls_back_for_invalid_raw_ids() {
437        // Formerly `ELEMENTS[z]` out-of-bounds panics; now diagnostics.
438        assert_eq!(NuclideId::from_nucid(0).to_name(), "Z0A0[m0]");
439        assert_eq!(
440            NuclideId::from_nucid(u32::MAX).to_name(),
441            format!(
442                "Z{}A{}[m{}]",
443                NuclideId::from_nucid(u32::MAX).z(),
444                NuclideId::from_nucid(u32::MAX).a(),
445                NuclideId::from_nucid(u32::MAX).state()
446            )
447        );
448        assert_eq!(NuclideId::from_nucid(920_050_000).to_name(), "Z92A5[m0]");
449        assert_eq!(NuclideId::from_nucid(922_350_010).to_name(), "Z92A235[m0]");
450        // The fallback is diagnostic-only: `from_name` rejects it.
451        for raw in [0, u32::MAX, 920_050_000, 1_190_000_000] {
452            let name = NuclideId::from_nucid(raw).to_name();
453            assert!(NuclideId::from_name(&name).is_err(), "{name}");
454            assert_eq!(
455                NuclideId::from_nucid(raw).to_string(),
456                name,
457                "Display follows to_name"
458            );
459        }
460    }
461
462    #[test]
463    fn every_validated_id_round_trips_through_name() {
464        // Canonical construction paths (incl. the checked raw-integer path).
465        let mut ids = vec![
466            NuclideId::new(1, 1, 0).unwrap(),
467            NuclideId::new(92, 235, 0).unwrap(),
468            NuclideId::new(95, 242, 9).unwrap(),
469            NuclideId::new(118, 294, 0).unwrap(),
470            NuclideId::from_name("Am242_m1").unwrap(),
471            NuclideId::from_zzaaam(922_350).unwrap(),
472            NuclideId::try_from_nucid(922_350_000).unwrap(),
473        ];
474        for z in [1, 2, 26, 92, 95, 118] {
475            for a in [z, z + 1, 999] {
476                for s in [0, 1, 9] {
477                    if let Ok(id) = NuclideId::new(z, a.min(999), s) {
478                        ids.push(id);
479                    }
480                }
481            }
482        }
483        for id in ids {
484            assert!(id.is_valid());
485            assert_eq!(NuclideId::from_name(&id.to_name()).unwrap(), id);
486        }
487    }
488
489    #[test]
490    fn error_arms_construct_and_display() {
491        assert!(matches!(
492            NuclideId::new(92, 235, 10),
493            Err(Error::BadState(10))
494        ));
495        assert!(matches!(
496            NuclideId::from_name("U235_mX"),
497            Err(Error::BadNumber(_))
498        ));
499        assert!(NuclideId::from_name("U235_mX")
500            .unwrap_err()
501            .to_string()
502            .contains("MX"));
503        assert!(matches!(
504            NuclideId::from_name("U23X5"),
505            Err(Error::BadNumber(_))
506        ));
507        assert!(!Error::BadState(10).to_string().is_empty());
508        assert!(!Error::BadNumber("MX".to_string()).to_string().is_empty());
509    }
510}