Skip to main content

readcon_core/
units.rs

1//! Unit expressions and conversion (metatomic-inspired, SI dimensional analysis).
2//!
3//! Supports named base units and simple products/quotients with `*`, `/`, `^`,
4//! and parentheses (case-sensitive). `unit_conversion_factor(from, to)` returns
5//! the multiplier `x_to = factor * x_from` when dimensions match.
6
7use crate::error::ParseError;
8
9/// Physical dimension exponents: L, T, M, Q (charge), Θ (temperature).
10#[derive(Clone, Copy, Debug, PartialEq)]
11pub struct Dimension {
12    pub exponents: [f64; 5],
13}
14
15impl Dimension {
16    pub const ZERO: Self = Self {
17        exponents: [0.0; 5],
18    };
19    pub const LENGTH: Self = Self {
20        exponents: [1.0, 0.0, 0.0, 0.0, 0.0],
21    };
22    pub const TIME: Self = Self {
23        exponents: [0.0, 1.0, 0.0, 0.0, 0.0],
24    };
25    pub const MASS: Self = Self {
26        exponents: [0.0, 0.0, 1.0, 0.0, 0.0],
27    };
28    pub const CHARGE: Self = Self {
29        exponents: [0.0, 0.0, 0.0, 1.0, 0.0],
30    };
31
32    fn mul(self, other: Self) -> Self {
33        let mut e = [0.0; 5];
34        for (slot, (left, right)) in e
35            .iter_mut()
36            .zip(self.exponents.iter().zip(other.exponents.iter()))
37        {
38            *slot = left + right;
39        }
40        Self { exponents: e }
41    }
42
43    fn div(self, other: Self) -> Self {
44        let mut e = [0.0; 5];
45        for (slot, (left, right)) in e
46            .iter_mut()
47            .zip(self.exponents.iter().zip(other.exponents.iter()))
48        {
49            *slot = left - right;
50        }
51        Self { exponents: e }
52    }
53
54    fn pow(self, p: f64) -> Self {
55        let mut e = [0.0; 5];
56        for (slot, exp) in e.iter_mut().zip(self.exponents.iter()) {
57            *slot = exp * p;
58        }
59        Self { exponents: e }
60    }
61
62    fn compatible(self, other: Self) -> bool {
63        self.exponents
64            .iter()
65            .zip(other.exponents.iter())
66            .all(|(a, b)| (a - b).abs() < 1e-9)
67    }
68}
69
70/// Parsed unit: SI scale factor (value in SI = factor * value_in_unit) and dimensions.
71#[derive(Clone, Copy, Debug)]
72struct UnitValue {
73    /// Multiply quantity in this unit by `si_factor` to get SI.
74    si_factor: f64,
75    dim: Dimension,
76}
77
78/// M L^2 T^-2. Same exponents as `MASS * LENGTH^2 / TIME^2`.
79const ENERGY: Dimension = Dimension {
80    exponents: [2.0, -2.0, 1.0, 0.0, 0.0],
81};
82
83struct BaseUnit {
84    name: &'static str,
85    value: UnitValue,
86}
87
88const fn unit(si_factor: f64, dim: Dimension) -> UnitValue {
89    UnitValue { si_factor, dim }
90}
91
92/// CODATA 2018 values. CON-units.18 fixes bohr and hartree to these
93/// published decimal literals rather than values derived from rounded inputs.
94const CODATA2018_BOHR_M: f64 = 5.291_772_109_03e-11;
95const CODATA2018_AMU_KG: f64 = metrology::AMU;
96const CODATA2018_HARTREE_J: f64 = 4.359_744_722_207_1e-18;
97const CODATA2018_ELEMENTARY: f64 = metrology::E_CHARGE;
98const CODATA2018_AVOGADRO: f64 = metrology::N_A;
99/// CON-units.18 writes these decimals. A product of the elementary charge
100/// and a power of ten is a different binary64 value.
101const MEV_J: f64 = 1.602_176_634e-22;
102const MEGA_EV_J: f64 = 1.602_176_634e-13;
103/// Thermochemical kilocalorie, exactly 4184 joule. Not a CODATA value.
104const KCAL_THERMOCHEMICAL_J: f64 = 4184.0;
105
106/// Accepted spellings, sorted for binary search. `MeV` and `meV` are different
107/// names. There is no case fold (CON-units.16).
108const BASE_UNITS: &[BaseUnit] = &[
109    BaseUnit {
110        name: "A",
111        value: unit(1e-10, Dimension::LENGTH),
112    },
113    BaseUnit {
114        name: "AMU",
115        value: unit(CODATA2018_AMU_KG, Dimension::MASS),
116    },
117    BaseUnit {
118        name: "Angstrom",
119        value: unit(1e-10, Dimension::LENGTH),
120    },
121    BaseUnit {
122        name: "Da",
123        value: unit(CODATA2018_AMU_KG, Dimension::MASS),
124    },
125    BaseUnit {
126        name: "Ha",
127        value: unit(CODATA2018_HARTREE_J, ENERGY),
128    },
129    BaseUnit {
130        name: "J",
131        value: unit(1.0, ENERGY),
132    },
133    BaseUnit {
134        name: "MeV",
135        value: unit(MEGA_EV_J, ENERGY),
136    },
137    BaseUnit {
138        name: "a0",
139        value: unit(CODATA2018_BOHR_M, Dimension::LENGTH),
140    },
141    BaseUnit {
142        name: "amu",
143        value: unit(CODATA2018_AMU_KG, Dimension::MASS),
144    },
145    BaseUnit {
146        name: "angstrom",
147        value: unit(1e-10, Dimension::LENGTH),
148    },
149    BaseUnit {
150        name: "bohr",
151        value: unit(CODATA2018_BOHR_M, Dimension::LENGTH),
152    },
153    BaseUnit {
154        name: "dalton",
155        value: unit(CODATA2018_AMU_KG, Dimension::MASS),
156    },
157    BaseUnit {
158        name: "e",
159        value: unit(CODATA2018_ELEMENTARY, Dimension::CHARGE),
160    },
161    BaseUnit {
162        name: "eV",
163        value: unit(CODATA2018_ELEMENTARY, ENERGY),
164    },
165    BaseUnit {
166        name: "electron_charge",
167        value: unit(CODATA2018_ELEMENTARY, Dimension::CHARGE),
168    },
169    BaseUnit {
170        name: "ev",
171        value: unit(CODATA2018_ELEMENTARY, ENERGY),
172    },
173    BaseUnit {
174        name: "femtosecond",
175        value: unit(1e-15, Dimension::TIME),
176    },
177    BaseUnit {
178        name: "fs",
179        value: unit(1e-15, Dimension::TIME),
180    },
181    BaseUnit {
182        name: "hartree",
183        value: unit(CODATA2018_HARTREE_J, ENERGY),
184    },
185    BaseUnit {
186        name: "j",
187        value: unit(1.0, ENERGY),
188    },
189    BaseUnit {
190        name: "joule",
191        value: unit(1.0, ENERGY),
192    },
193    BaseUnit {
194        name: "kJ",
195        value: unit(1000.0, ENERGY),
196    },
197    BaseUnit {
198        name: "kcal",
199        value: unit(KCAL_THERMOCHEMICAL_J, ENERGY),
200    },
201    BaseUnit {
202        name: "kg",
203        value: unit(1.0, Dimension::MASS),
204    },
205    BaseUnit {
206        name: "kilogram",
207        value: unit(1.0, Dimension::MASS),
208    },
209    BaseUnit {
210        name: "kj",
211        value: unit(1000.0, ENERGY),
212    },
213    BaseUnit {
214        name: "m",
215        value: unit(1.0, Dimension::LENGTH),
216    },
217    BaseUnit {
218        name: "meV",
219        value: unit(MEV_J, ENERGY),
220    },
221    BaseUnit {
222        name: "meter",
223        value: unit(1.0, Dimension::LENGTH),
224    },
225    BaseUnit {
226        name: "metre",
227        value: unit(1.0, Dimension::LENGTH),
228    },
229    BaseUnit {
230        name: "mev",
231        value: unit(MEV_J, ENERGY),
232    },
233    BaseUnit {
234        name: "mol",
235        value: unit(CODATA2018_AVOGADRO, Dimension::ZERO),
236    },
237    BaseUnit {
238        name: "nanometer",
239        value: unit(1e-9, Dimension::LENGTH),
240    },
241    BaseUnit {
242        name: "nanosecond",
243        value: unit(1e-9, Dimension::TIME),
244    },
245    BaseUnit {
246        name: "nm",
247        value: unit(1e-9, Dimension::LENGTH),
248    },
249    BaseUnit {
250        name: "ns",
251        value: unit(1e-9, Dimension::TIME),
252    },
253    BaseUnit {
254        name: "picosecond",
255        value: unit(1e-12, Dimension::TIME),
256    },
257    BaseUnit {
258        name: "ps",
259        value: unit(1e-12, Dimension::TIME),
260    },
261    BaseUnit {
262        name: "s",
263        value: unit(1.0, Dimension::TIME),
264    },
265    BaseUnit {
266        name: "second",
267        value: unit(1.0, Dimension::TIME),
268    },
269    BaseUnit {
270        name: "u",
271        value: unit(CODATA2018_AMU_KG, Dimension::MASS),
272    },
273    BaseUnit {
274        name: "Å",
275        value: unit(1e-10, Dimension::LENGTH),
276    },
277    BaseUnit {
278        name: "å",
279        value: unit(1e-10, Dimension::LENGTH),
280    },
281];
282
283#[cfg(test)]
284pub(crate) fn cached_unit_table_addr() -> usize {
285    BASE_UNITS.as_ptr() as usize
286}
287
288fn lookup_base(name: &str) -> Option<&'static UnitValue> {
289    BASE_UNITS
290        .binary_search_by(|entry| entry.name.cmp(name))
291        .ok()
292        .map(|index| &BASE_UNITS[index].value)
293}
294
295/// Parse a unit expression into SI factor and dimension.
296///
297/// ASCII spaces and tabs are removed (CON-units.17). Names are exact
298/// spellings: `MeV` is megaelectronvolt and `meV` is millielectronvolt.
299pub fn parse_unit_expression(expr: &str) -> Result<(f64, Dimension), ParseError> {
300    let s: String = expr.chars().filter(|c| *c != ' ' && *c != '\t').collect();
301    if s.is_empty() {
302        return Err(ParseError::ValidationError("empty unit expression".into()));
303    }
304    parse_expr(&s)
305}
306
307fn parse_expr(s: &str) -> Result<(f64, Dimension), ParseError> {
308    // Split on * and / with left-associative scan; handle ^N on atoms.
309    let mut factor = 1.0_f64;
310    let mut dim = Dimension::ZERO;
311    let mut i = 0;
312    let bytes = s.as_bytes();
313    let mut pending_div = false;
314    while i < bytes.len() {
315        if bytes[i] == b'*' {
316            i += 1;
317            continue;
318        }
319        if bytes[i] == b'/' {
320            pending_div = true;
321            i += 1;
322            continue;
323        }
324        let (atom_f, atom_d, consumed) = parse_atom(&s[i..])?;
325        i += consumed;
326        if pending_div {
327            factor /= atom_f;
328            dim = dim.div(atom_d);
329            pending_div = false;
330        } else {
331            factor *= atom_f;
332            dim = dim.mul(atom_d);
333        }
334    }
335    Ok((factor, dim))
336}
337
338fn parse_atom(s: &str) -> Result<(f64, Dimension, usize), ParseError> {
339    let bytes = s.as_bytes();
340    if bytes.is_empty() {
341        return Err(ParseError::ValidationError(
342            "trailing operator in unit".into(),
343        ));
344    }
345    if bytes[0] == b'(' {
346        let mut depth = 0;
347        for (j, &b) in bytes.iter().enumerate() {
348            if b == b'(' {
349                depth += 1;
350            } else if b == b')' {
351                depth -= 1;
352                if depth == 0 {
353                    let inner = &s[1..j];
354                    let (f, d) = parse_expr(inner)?;
355                    let mut end = j + 1;
356                    let (f2, d2, extra) = apply_power(f, d, &s[end..])?;
357                    end += extra;
358                    return Ok((f2, d2, end));
359                }
360            }
361        }
362        return Err(ParseError::ValidationError("unbalanced '(' in unit".into()));
363    }
364    // identifier [ ^ number ]
365    let mut j = 0;
366    while j < bytes.len()
367        && (bytes[j].is_ascii_alphanumeric() || bytes[j] == b'_' || bytes[j] > 127)
368    {
369        j += 1;
370    }
371    if j == 0 {
372        return Err(ParseError::ValidationError(format!(
373            "expected unit name in '{s}'"
374        )));
375    }
376    let name = &s[..j];
377    let base = lookup_base(name).ok_or_else(|| {
378        ParseError::ValidationError(format!(
379            "unknown unit '{name}'; unit symbols are case-sensitive \
380             (meV is milli, MeV is mega)"
381        ))
382    })?;
383    let mut end = j;
384    let (f, d, extra) = apply_power(base.si_factor, base.dim, &s[end..])?;
385    end += extra;
386    Ok((f, d, end))
387}
388
389fn apply_power(f: f64, d: Dimension, rest: &str) -> Result<(f64, Dimension, usize), ParseError> {
390    let bytes = rest.as_bytes();
391    if bytes.first() == Some(&b'^') {
392        let mut k = 1;
393        let neg = bytes.get(1) == Some(&b'-');
394        if neg {
395            k = 2;
396        }
397        let start = k;
398        while k < bytes.len() && (bytes[k].is_ascii_digit() || bytes[k] == b'.') {
399            k += 1;
400        }
401        if k == start {
402            return Err(ParseError::ValidationError(
403                "expected exponent after ^".into(),
404            ));
405        }
406        let mut p: f64 = rest[start..k]
407            .parse()
408            .map_err(|_| ParseError::ValidationError("invalid unit exponent".into()))?;
409        if neg {
410            p = -p;
411        }
412        return Ok((f.powf(p), d.pow(p), k));
413    }
414    Ok((f, d, 0))
415}
416
417/// Multiplicative factor: `value_in_to = factor * value_in_from`.
418///
419/// The names are the ones accepted in a CON `units` object. The table is
420/// built once per process and reused by every reader.
421///
422/// ```
423/// use readcon_core::units::unit_conversion_factor;
424/// let meters = unit_conversion_factor("angstrom", "m").unwrap();
425/// assert!((meters - 1.0e-10).abs() < 1.0e-20);
426/// ```
427pub fn unit_conversion_factor(from_unit: &str, to_unit: &str) -> Result<f64, ParseError> {
428    unit_conversion_factor_for_version(crate::CON_SPEC_VERSION, from_unit, to_unit)
429}
430
431/// Multiplicative factor from `from_unit` to `to_unit` under a CON major.
432pub fn unit_conversion_factor_for_version(
433    spec_version: u32,
434    from_unit: &str,
435    to_unit: &str,
436) -> Result<f64, ParseError> {
437    let _ = spec_version;
438    let (f_from, d_from) = parse_unit_expression(from_unit)?;
439    let (f_to, d_to) = parse_unit_expression(to_unit)?;
440    if !d_from.compatible(d_to) {
441        return Err(ParseError::ValidationError(format!(
442            "incompatible units '{from_unit}' and '{to_unit}'"
443        )));
444    }
445    Ok(f_from / f_to)
446}
447
448/// Time unit that velocities in this frame are stored in (D10).
449///
450/// Versions 1, 2, and every minor of major 3 are the natural unit
451/// regardless of a `units.time` label (CON-units.8, CON-units.9).
452/// Major 4 and later take `units.time` as authoritative (CON-units.10).
453/// `override_unit` must not replace that assignment (CON-units.15).
454/// A value that differs from the assigned unit is `InvalidUnits`.
455pub fn velocity_file_time_unit(
456    spec_version: u32,
457    metadata: &serde_json::Map<String, serde_json::Value>,
458    override_unit: Option<&str>,
459) -> Result<String, ParseError> {
460    if spec_version < 4 {
461        return Ok(NATURAL_TIME_UNIT.to_string());
462    }
463    let assigned = assigned_velocity_time(metadata)?;
464    if let Some(unit) = override_unit {
465        validate_unit_for_quantity("time", unit)?;
466        let both_natural = is_natural_time_spelling(unit) && is_natural_time_spelling(&assigned);
467        if unit != assigned && !both_natural {
468            return Err(ParseError::InvalidUnits(
469                "a consumer must not replace the time unit the clauses assign".into(),
470            ));
471        }
472    }
473    Ok(assigned)
474}
475
476fn assigned_velocity_time(
477    metadata: &serde_json::Map<String, serde_json::Value>,
478) -> Result<String, ParseError> {
479    let time = metadata
480        .get(crate::types::meta::UNITS)
481        .and_then(|u| u.get("time"))
482        .and_then(|t| t.as_str())
483        .filter(|s| !s.is_empty());
484    match time {
485        Some(unit) => {
486            validate_unit_for_quantity("time", unit)?;
487            Ok(unit.to_string())
488        }
489        None => Err(ParseError::InvalidUnits(
490            "major >= 4 velocities require units.time".into(),
491        )),
492    }
493}
494
495/// Multiply a file velocity by this to land in [`NATURAL_TIME_UNIT`].
496///
497/// Velocity scales as 1/time, so the factor is the reciprocal of
498/// [`unit_conversion_factor`] from the file time unit to the natural unit.
499pub fn velocity_scale_to_natural(file_time: &str) -> Result<f64, ParseError> {
500    validate_unit_for_quantity("time", file_time)?;
501    let factor = unit_conversion_factor(file_time, NATURAL_TIME_UNIT)?;
502    if factor == 0.0 || !factor.is_finite() {
503        return Err(ParseError::InvalidUnits(format!(
504            "time unit '{file_time}' has a zero scale"
505        )));
506    }
507    Ok(1.0 / factor)
508}
509
510/// Validate that `unit` has dimensions appropriate for `quantity`
511/// (`length`, `energy`, `mass`, `time`, `velocity`, `force`).
512pub fn validate_unit_for_quantity(quantity: &str, unit: &str) -> Result<(), ParseError> {
513    let (_, dim) = parse_unit_expression(unit)?;
514    let expect = match quantity {
515        "length" => Dimension::LENGTH,
516        "time" => Dimension::TIME,
517        "mass" => Dimension::MASS,
518        "energy" => Dimension::MASS
519            .mul(Dimension::LENGTH.pow(2.0))
520            .div(Dimension::TIME.pow(2.0)),
521        "velocity" => Dimension::LENGTH.div(Dimension::TIME),
522        "force" => Dimension::MASS
523            .mul(Dimension::LENGTH)
524            .div(Dimension::TIME.pow(2.0)),
525        _ => {
526            return Err(ParseError::ValidationError(format!(
527                "unknown quantity '{quantity}'"
528            )));
529        }
530    };
531    if !dim.compatible(expect) {
532        return Err(ParseError::ValidationError(format!(
533            "unit '{unit}' is not valid for quantity '{quantity}'"
534        )));
535    }
536    Ok(())
537}
538
539/// CON-units.2. A unit string that is present must have the matching
540/// dimension, in every version that carries it (CON-units.7).
541pub fn validate_present_unit_dimensions(units: &serde_json::Value) -> Result<(), ParseError> {
542    let obj = units
543        .as_object()
544        .ok_or_else(|| ParseError::InvalidUnits("units must be a JSON object".into()))?;
545    for (key, quantity) in [
546        ("length", "length"),
547        ("energy", "energy"),
548        ("mass", "mass"),
549        ("time", "time"),
550        ("velocity", "velocity"),
551        ("force", "force"),
552    ] {
553        let Some(value) = obj.get(key) else {
554            continue;
555        };
556        let text = value
557            .as_str()
558            .ok_or_else(|| ParseError::InvalidUnits(format!("units.{key} must be a string")))?;
559        validate_unit_for_quantity(quantity, text)
560            .map_err(|err| ParseError::InvalidUnits(format!("units.{key}: {err}")))?;
561    }
562    Ok(())
563}
564
565/// CON v3 requires `units` object with non-empty `length` and `energy` strings.
566pub fn validate_v3_units_metadata(units: &serde_json::Value) -> Result<(), ParseError> {
567    validate_units_metadata_for_version(3, units)
568}
569
570/// Validate the units object under the spelling rules of its CON major.
571pub fn validate_units_metadata_for_version(
572    spec_version: u32,
573    units: &serde_json::Value,
574) -> Result<(), ParseError> {
575    let _ = spec_version;
576    let obj = units
577        .as_object()
578        .ok_or_else(|| ParseError::ValidationError("units must be a JSON object".into()))?;
579    for key in ["length", "energy"] {
580        let Some(v) = obj.get(key) else {
581            return Err(ParseError::ValidationError(format!(
582                "v3 units must include non-empty '{key}'"
583            )));
584        };
585        let Some(s) = v.as_str() else {
586            return Err(ParseError::ValidationError(format!(
587                "units.{key} must be a string"
588            )));
589        };
590        if s.trim().is_empty() {
591            return Err(ParseError::ValidationError(format!(
592                "units.{key} must be non-empty"
593            )));
594        }
595        validate_unit_for_quantity(key, s)?;
596    }
597    // Optional keys if present must be valid for their quantity
598    for (key, qty) in [
599        ("mass", "mass"),
600        ("time", "time"),
601        ("velocity", "velocity"),
602        ("force", "force"),
603    ] {
604        if let Some(v) = obj.get(key) {
605            let s = v.as_str().ok_or_else(|| {
606                ParseError::ValidationError(format!("units.{key} must be a string"))
607            })?;
608            validate_unit_for_quantity(qty, s)?;
609        }
610    }
611    Ok(())
612}
613
614/// Symbol spelling of the natural time unit (CON-units.5).
615/// The historical alias `(amu*angstrom^2/eV)^0.5` is the same unit.
616pub const NATURAL_TIME_UNIT: &str = "(u*Å^2/eV)^0.5";
617
618/// The eOn and ASE spelling. It mixes a name with symbols and is accepted
619/// as an alias of [`NATURAL_TIME_UNIT`], not as the spelling a new frame uses.
620pub const HISTORICAL_NATURAL_TIME: &str = "(amu*angstrom^2/eV)^0.5";
621
622fn is_natural_time(compact: &str) -> bool {
623    compact == NATURAL_TIME_UNIT || compact == HISTORICAL_NATURAL_TIME
624}
625
626/// Both spellings of CON-units.5, ignoring ASCII spaces and tabs.
627pub fn is_natural_time_spelling(unit: &str) -> bool {
628    let compact: String = unit.chars().filter(|c| !c.is_whitespace()).collect();
629    is_natural_time(&compact)
630}
631
632pub fn default_v3_units_json() -> serde_json::Value {
633    serde_json::json!({
634        "length": "angstrom",
635        "energy": "eV",
636        "mass": "amu"
637    })
638}
639
640fn preferred_atom(alias: &str) -> Option<&'static str> {
641    // Exact spellings. `a`, `ha`, and `da` are not folded onto another unit.
642    Some(match alias {
643        "A" | "Å" | "å" | "angstrom" | "Angstrom" => "angstrom",
644        "nm" | "nanometer" => "nm",
645        "m" | "meter" | "metre" => "m",
646        "bohr" | "a0" => "bohr",
647        "fs" | "femtosecond" => "fs",
648        "ps" | "picosecond" => "ps",
649        "ns" | "nanosecond" => "ns",
650        "s" | "second" => "s",
651        "eV" | "ev" => "eV",
652        "meV" | "mev" => "meV",
653        "MeV" => "MeV",
654        "hartree" | "Ha" => "hartree",
655        "J" | "j" | "joule" => "J",
656        "kJ" | "kj" => "kJ",
657        "kcal" => "kcal",
658        "amu" | "AMU" => "amu",
659        "u" | "Da" | "dalton" => "u",
660        "kg" | "kilogram" => "kg",
661        "mol" => "mol",
662        _ => return None,
663    })
664}
665
666/// Rewrite a unit expression to preferred names (`A` → `angstrom`, `ev` → `eV`).
667/// The expression MUST parse (`unit_conversion_factor` identity).
668pub fn canonicalize_unit_expression(expr: &str) -> Result<String, ParseError> {
669    canonicalize_unit_expression_for_version(crate::CON_SPEC_VERSION, expr)
670}
671
672/// Rewrite a unit expression to preferred names for a CON major.
673pub fn canonicalize_unit_expression_for_version(
674    spec_version: u32,
675    expr: &str,
676) -> Result<String, ParseError> {
677    let trimmed = expr.trim();
678    if trimmed.is_empty() {
679        return Err(ParseError::ValidationError("empty unit".into()));
680    }
681    let _ = unit_conversion_factor_for_version(spec_version, trimmed, trimmed)?;
682    let compact: String = trimmed.chars().filter(|c| !c.is_whitespace()).collect();
683    if is_natural_time(&compact) {
684        return Ok(if spec_version >= 4 {
685            NATURAL_TIME_UNIT
686        } else {
687            HISTORICAL_NATURAL_TIME
688        }
689        .to_string());
690    }
691    let mut out = String::new();
692    let bytes = compact.as_bytes();
693    let mut i = 0;
694    while i < bytes.len() {
695        let b = bytes[i];
696        if matches!(b, b'*' | b'/' | b'(' | b')' | b'^') {
697            if !out.is_empty() && !out.ends_with(' ') && b != b')' && b != b'^' {
698                out.push(' ');
699            }
700            out.push(b as char);
701            if b != b'(' && b != b'^' {
702                out.push(' ');
703            }
704            i += 1;
705            continue;
706        }
707        if b == b'-' || b.is_ascii_digit() || b == b'.' {
708            out.push(b as char);
709            i += 1;
710            continue;
711        }
712        let start = i;
713        while i < bytes.len() && (bytes[i].is_ascii_alphabetic() || bytes[i] > 127) {
714            i += 1;
715        }
716        if start == i {
717            return Err(ParseError::ValidationError(format!(
718                "bad unit token in '{expr}'"
719            )));
720        }
721        let atom = &compact[start..i];
722        out.push_str(preferred_atom(atom).unwrap_or(atom));
723    }
724    let rendered = out.split_whitespace().collect::<Vec<_>>().join(" ");
725    let rendered_compact: String = rendered.chars().filter(|c| !c.is_whitespace()).collect();
726    if is_natural_time(&rendered_compact) {
727        return Ok(if spec_version >= 4 {
728            NATURAL_TIME_UNIT
729        } else {
730            HISTORICAL_NATURAL_TIME
731        }
732        .to_string());
733    }
734    Ok(rendered)
735}
736
737/// CON-units.21. `units.velocity` does not replace the time the version rules assign.
738pub fn enforce_velocity_precedence(
739    spec_version: u32,
740    units: &serde_json::Value,
741) -> Result<(), ParseError> {
742    let Some(obj) = units.as_object() else {
743        return Ok(());
744    };
745    let Some(velocity) = obj.get("velocity").and_then(|value| value.as_str()) else {
746        return Ok(());
747    };
748    validate_unit_for_quantity("velocity", velocity)?;
749    let length = obj
750        .get("length")
751        .and_then(|value| value.as_str())
752        .filter(|text| !text.is_empty())
753        .unwrap_or("angstrom");
754    let time = if spec_version >= 4 {
755        match obj
756            .get("time")
757            .and_then(|value| value.as_str())
758            .filter(|text| !text.is_empty())
759        {
760            Some(unit) => unit.to_string(),
761            None => return Ok(()),
762        }
763    } else {
764        NATURAL_TIME_UNIT.to_string()
765    };
766    let quotient = format!("({length})/({time})");
767    let factor = unit_conversion_factor_for_version(spec_version, velocity, &quotient)?;
768    if (factor - 1.0).abs() > 1e-9 {
769        return Err(ParseError::InvalidUnits(format!(
770            "units.velocity must equal units.length divided by the time unit, not '{velocity}'"
771        )));
772    }
773    Ok(())
774}
775
776/// Rewrite every string member. Does not require v3 `length`+`energy`.
777pub fn canonicalize_units_object(
778    units: &serde_json::Value,
779) -> Result<serde_json::Value, ParseError> {
780    canonicalize_units_object_for_version(crate::CON_SPEC_VERSION, units)
781}
782
783/// Rewrite every string member under the named CON major.
784pub fn canonicalize_units_object_for_version(
785    spec_version: u32,
786    units: &serde_json::Value,
787) -> Result<serde_json::Value, ParseError> {
788    let obj = units
789        .as_object()
790        .ok_or_else(|| ParseError::ValidationError("units must be a JSON object".into()))?;
791    let mut out = serde_json::Map::new();
792    for (k, v) in obj {
793        let s = v
794            .as_str()
795            .ok_or_else(|| ParseError::ValidationError(format!("units.{k} must be a string")))?;
796        out.insert(
797            k.clone(),
798            serde_json::Value::String(canonicalize_unit_expression_for_version(spec_version, s)?),
799        );
800    }
801    Ok(serde_json::Value::Object(out))
802}
803
804/// v3 validate then canonicalize (preferred names on line 2).
805pub fn canonicalize_units_metadata(
806    units: &serde_json::Value,
807) -> Result<serde_json::Value, ParseError> {
808    validate_v3_units_metadata(units)?;
809    canonicalize_units_object_for_version(3, units)
810}
811
812#[cfg(test)]
813mod tests {
814    use super::*;
815
816    /// CON-units.18: bohr and hartree use the specification's exact literals.
817    #[test]
818    fn con_units_18_uses_spec_codata_2018_literals() {
819        let bohr = 5.291_772_109_03e-11_f64;
820        let hartree = 4.359_744_722_207_1e-18_f64;
821        assert_eq!(CODATA2018_BOHR_M.to_bits(), bohr.to_bits());
822        assert_eq!(CODATA2018_HARTREE_J.to_bits(), hartree.to_bits());
823        assert_eq!(
824            parse_unit_expression("bohr").unwrap().0.to_bits(),
825            bohr.to_bits()
826        );
827        assert_eq!(
828            parse_unit_expression("hartree").unwrap().0.to_bits(),
829            hartree.to_bits()
830        );
831    }
832
833    #[test]
834    fn base_table_is_shared_across_calls_and_threads() {
835        for pair in BASE_UNITS.windows(2) {
836            assert!(
837                pair[0].name < pair[1].name,
838                "{} is not before {}",
839                pair[0].name,
840                pair[1].name
841            );
842        }
843        let energy = Dimension::MASS
844            .mul(Dimension::LENGTH.pow(2.0))
845            .div(Dimension::TIME.pow(2.0));
846        assert!(
847            parse_unit_expression("eV").unwrap().1.compatible(energy),
848            "energy exponents drifted from M L^2 T^-2"
849        );
850        let first = cached_unit_table_addr();
851        let second = cached_unit_table_addr();
852        assert_eq!(first, second);
853        let factors = std::thread::scope(|scope| {
854            let mut joins = Vec::new();
855            for _ in 0..8 {
856                joins.push(scope.spawn(|| parse_unit_expression("Angstrom").unwrap().0));
857            }
858            joins
859                .into_iter()
860                .map(|join| join.join().unwrap())
861                .collect::<Vec<_>>()
862        });
863        assert!(factors.iter().all(|factor| (*factor - 1e-10).abs() < 1e-22));
864    }
865
866    #[test]
867    fn angstrom_to_nm() {
868        let f = unit_conversion_factor("angstrom", "nm").unwrap();
869        assert!((f - 0.1).abs() < 1e-12);
870    }
871
872    #[test]
873    fn ev_to_mev() {
874        let f = unit_conversion_factor("eV", "meV").unwrap();
875        assert!((f - 1000.0).abs() < 1e-6);
876    }
877
878    #[test]
879    fn dimensional_mismatch() {
880        assert!(unit_conversion_factor("angstrom", "eV").is_err());
881    }
882
883    #[test]
884    fn ev_to_kcal_per_mol_is_metatomic() {
885        let f = unit_conversion_factor("eV", "kcal / mol").unwrap();
886        assert!((f - 23.060_548).abs() < 1e-3, "got {f}");
887        let force = unit_conversion_factor("eV / angstrom", "kJ / mol / angstrom").unwrap();
888        assert!((force - 96.485_332).abs() < 1e-3, "got {force}");
889        let ns = unit_conversion_factor("ns", "ps").unwrap();
890        assert!((ns - 1000.0).abs() < 1e-9, "got {ns}");
891    }
892
893    #[test]
894    fn validate_length_energy() {
895        validate_unit_for_quantity("length", "nm").unwrap();
896        validate_unit_for_quantity("energy", "hartree").unwrap();
897        assert!(validate_unit_for_quantity("energy", "angstrom").is_err());
898    }
899
900    #[test]
901    fn v3_units_require_length_energy() {
902        assert!(validate_v3_units_metadata(&serde_json::json!({"length": "A"})).is_err());
903        validate_v3_units_metadata(&default_v3_units_json()).unwrap();
904    }
905
906    #[test]
907    fn default_v3_units_do_not_invent_time_fs() {
908        let units = default_v3_units_json();
909        assert!(units.get("time").is_none(), "{units}");
910        assert_eq!(units["length"], "angstrom");
911        assert_eq!(units["energy"], "eV");
912        assert_eq!(units["mass"], "amu");
913    }
914
915    #[test]
916    fn canonicalize_aliases() {
917        assert_eq!(canonicalize_unit_expression("A").unwrap(), "angstrom");
918        assert_eq!(canonicalize_unit_expression("ev").unwrap(), "eV");
919        assert_eq!(canonicalize_unit_expression("femtosecond").unwrap(), "fs");
920        assert_eq!(
921            canonicalize_unit_expression("eV/angstrom").unwrap(),
922            "eV / angstrom"
923        );
924        let u = canonicalize_units_metadata(&serde_json::json!({
925            "length": "A",
926            "energy": "ev",
927            "time": "femtosecond"
928        }))
929        .unwrap();
930        assert_eq!(u["length"], "angstrom");
931        assert_eq!(u["energy"], "eV");
932        assert_eq!(u["time"], "fs");
933    }
934
935    #[test]
936    fn natural_time_spelling_is_pinned() {
937        let spaced = "( amu * angstrom ^ 2 / eV ) ^ 0.5";
938        assert_eq!(
939            canonicalize_unit_expression(spaced).unwrap(),
940            NATURAL_TIME_UNIT
941        );
942        assert!(!NATURAL_TIME_UNIT.contains(' '));
943        let factor = unit_conversion_factor(NATURAL_TIME_UNIT, "fs").unwrap();
944        assert!((factor - 10.180_505_710_759_414).abs() < 1e-9, "{factor}");
945        let mixed = "(AMU * angstrom^2 / ev)^0.5";
946        assert_eq!(
947            canonicalize_unit_expression(mixed).unwrap(),
948            NATURAL_TIME_UNIT
949        );
950    }
951}