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-insensitive). `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/// Names are lowercase and sorted. Lookup is a binary search, so the table
93/// is plain static data: no `HashMap`, and no hashbrown control bytes for
94/// Valgrind to treat as an interior pointer of a process-lifetime allocation.
95const BASE_UNITS: &[BaseUnit] = &[
96    BaseUnit {
97        name: "a",
98        value: unit(1e-10, Dimension::LENGTH),
99    },
100    BaseUnit {
101        name: "a0",
102        value: unit(5.291_772_109_03e-11, Dimension::LENGTH),
103    },
104    BaseUnit {
105        name: "amu",
106        value: unit(1.660_539_066_60e-27, Dimension::MASS),
107    },
108    BaseUnit {
109        name: "angstrom",
110        value: unit(1e-10, Dimension::LENGTH),
111    },
112    BaseUnit {
113        name: "bohr",
114        value: unit(5.291_772_109_03e-11, Dimension::LENGTH),
115    },
116    BaseUnit {
117        name: "da",
118        value: unit(1.660_539_066_60e-27, Dimension::MASS),
119    },
120    BaseUnit {
121        name: "dalton",
122        value: unit(1.660_539_066_60e-27, Dimension::MASS),
123    },
124    BaseUnit {
125        name: "e",
126        value: unit(1.602_176_634e-19, Dimension::CHARGE),
127    },
128    BaseUnit {
129        name: "electron_charge",
130        value: unit(1.602_176_634e-19, Dimension::CHARGE),
131    },
132    BaseUnit {
133        name: "ev",
134        value: unit(1.602_176_634e-19, ENERGY),
135    },
136    BaseUnit {
137        name: "femtosecond",
138        value: unit(1e-15, Dimension::TIME),
139    },
140    BaseUnit {
141        name: "fs",
142        value: unit(1e-15, Dimension::TIME),
143    },
144    BaseUnit {
145        name: "ha",
146        value: unit(4.359_744_722_207_1e-18, ENERGY),
147    },
148    BaseUnit {
149        name: "hartree",
150        value: unit(4.359_744_722_207_1e-18, ENERGY),
151    },
152    BaseUnit {
153        name: "j",
154        value: unit(1.0, ENERGY),
155    },
156    BaseUnit {
157        name: "joule",
158        value: unit(1.0, ENERGY),
159    },
160    BaseUnit {
161        name: "kcal",
162        value: unit(4184.0, ENERGY),
163    },
164    BaseUnit {
165        name: "kg",
166        value: unit(1.0, Dimension::MASS),
167    },
168    BaseUnit {
169        name: "kilogram",
170        value: unit(1.0, Dimension::MASS),
171    },
172    BaseUnit {
173        name: "kj",
174        value: unit(1000.0, ENERGY),
175    },
176    BaseUnit {
177        name: "m",
178        value: unit(1.0, Dimension::LENGTH),
179    },
180    BaseUnit {
181        name: "meter",
182        value: unit(1.0, Dimension::LENGTH),
183    },
184    BaseUnit {
185        name: "metre",
186        value: unit(1.0, Dimension::LENGTH),
187    },
188    BaseUnit {
189        name: "mev",
190        value: unit(1.602_176_634e-22, ENERGY),
191    },
192    BaseUnit {
193        name: "mol",
194        value: unit(6.022_140_76e23, Dimension::ZERO),
195    },
196    BaseUnit {
197        name: "nanometer",
198        value: unit(1e-9, Dimension::LENGTH),
199    },
200    BaseUnit {
201        name: "nanosecond",
202        value: unit(1e-9, Dimension::TIME),
203    },
204    BaseUnit {
205        name: "nm",
206        value: unit(1e-9, Dimension::LENGTH),
207    },
208    BaseUnit {
209        name: "ns",
210        value: unit(1e-9, Dimension::TIME),
211    },
212    BaseUnit {
213        name: "picosecond",
214        value: unit(1e-12, Dimension::TIME),
215    },
216    BaseUnit {
217        name: "ps",
218        value: unit(1e-12, Dimension::TIME),
219    },
220    BaseUnit {
221        name: "s",
222        value: unit(1.0, Dimension::TIME),
223    },
224    BaseUnit {
225        name: "second",
226        value: unit(1.0, Dimension::TIME),
227    },
228    BaseUnit {
229        name: "u",
230        value: unit(1.660_539_066_60e-27, Dimension::MASS),
231    },
232    BaseUnit {
233        name: "å",
234        value: unit(1e-10, Dimension::LENGTH),
235    },
236];
237
238#[cfg(test)]
239pub(crate) fn cached_unit_table_addr() -> usize {
240    BASE_UNITS.as_ptr() as usize
241}
242
243fn lookup_base(name: &str) -> Option<&'static UnitValue> {
244    BASE_UNITS
245        .binary_search_by(|entry| entry.name.cmp(name))
246        .ok()
247        .map(|index| &BASE_UNITS[index].value)
248}
249
250/// Parse a unit expression into SI factor and dimension.
251pub fn parse_unit_expression(expr: &str) -> Result<(f64, Dimension), ParseError> {
252    let s: String = expr.chars().filter(|c| !c.is_whitespace()).collect();
253    if s.is_empty() {
254        return Err(ParseError::ValidationError("empty unit expression".into()));
255    }
256    // CON-units.16 names are case-insensitive, including `Å`.
257    parse_expr(&s.to_lowercase())
258}
259
260fn parse_expr(s: &str) -> Result<(f64, Dimension), ParseError> {
261    // Split on * and / with left-associative scan; handle ^N on atoms.
262    let mut factor = 1.0_f64;
263    let mut dim = Dimension::ZERO;
264    let mut i = 0;
265    let bytes = s.as_bytes();
266    let mut pending_div = false;
267    while i < bytes.len() {
268        if bytes[i] == b'*' {
269            i += 1;
270            continue;
271        }
272        if bytes[i] == b'/' {
273            pending_div = true;
274            i += 1;
275            continue;
276        }
277        let (atom_f, atom_d, consumed) = parse_atom(&s[i..])?;
278        i += consumed;
279        if pending_div {
280            factor /= atom_f;
281            dim = dim.div(atom_d);
282            pending_div = false;
283        } else {
284            factor *= atom_f;
285            dim = dim.mul(atom_d);
286        }
287    }
288    Ok((factor, dim))
289}
290
291fn parse_atom(s: &str) -> Result<(f64, Dimension, usize), ParseError> {
292    let bytes = s.as_bytes();
293    if bytes.is_empty() {
294        return Err(ParseError::ValidationError(
295            "trailing operator in unit".into(),
296        ));
297    }
298    if bytes[0] == b'(' {
299        let mut depth = 0;
300        for (j, &b) in bytes.iter().enumerate() {
301            if b == b'(' {
302                depth += 1;
303            } else if b == b')' {
304                depth -= 1;
305                if depth == 0 {
306                    let inner = &s[1..j];
307                    let (f, d) = parse_expr(inner)?;
308                    let mut end = j + 1;
309                    let (f2, d2, extra) = apply_power(f, d, &s[end..])?;
310                    end += extra;
311                    return Ok((f2, d2, end));
312                }
313            }
314        }
315        return Err(ParseError::ValidationError("unbalanced '(' in unit".into()));
316    }
317    // identifier [ ^ number ]
318    let mut j = 0;
319    while j < bytes.len()
320        && (bytes[j].is_ascii_alphanumeric() || bytes[j] == b'_' || bytes[j] > 127)
321    {
322        j += 1;
323    }
324    if j == 0 {
325        return Err(ParseError::ValidationError(format!(
326            "expected unit name in '{s}'"
327        )));
328    }
329    let name = &s[..j];
330    let base = lookup_base(name)
331        .ok_or_else(|| ParseError::ValidationError(format!("unknown unit '{name}'")))?;
332    let mut end = j;
333    let (f, d, extra) = apply_power(base.si_factor, base.dim, &s[end..])?;
334    end += extra;
335    Ok((f, d, end))
336}
337
338fn apply_power(f: f64, d: Dimension, rest: &str) -> Result<(f64, Dimension, usize), ParseError> {
339    let bytes = rest.as_bytes();
340    if bytes.first() == Some(&b'^') {
341        let mut k = 1;
342        let neg = bytes.get(1) == Some(&b'-');
343        if neg {
344            k = 2;
345        }
346        let start = k;
347        while k < bytes.len() && (bytes[k].is_ascii_digit() || bytes[k] == b'.') {
348            k += 1;
349        }
350        if k == start {
351            return Err(ParseError::ValidationError(
352                "expected exponent after ^".into(),
353            ));
354        }
355        let mut p: f64 = rest[start..k]
356            .parse()
357            .map_err(|_| ParseError::ValidationError("invalid unit exponent".into()))?;
358        if neg {
359            p = -p;
360        }
361        return Ok((f.powf(p), d.pow(p), k));
362    }
363    Ok((f, d, 0))
364}
365
366/// Multiplicative factor: `value_in_to = factor * value_in_from`.
367///
368/// The names are the ones accepted in a CON `units` object. The table is
369/// built once per process and reused by every reader.
370///
371/// ```
372/// use readcon_core::units::unit_conversion_factor;
373/// let meters = unit_conversion_factor("angstrom", "m").unwrap();
374/// assert!((meters - 1.0e-10).abs() < 1.0e-20);
375/// ```
376pub fn unit_conversion_factor(from_unit: &str, to_unit: &str) -> Result<f64, ParseError> {
377    let (f_from, d_from) = parse_unit_expression(from_unit)?;
378    let (f_to, d_to) = parse_unit_expression(to_unit)?;
379    if !d_from.compatible(d_to) {
380        return Err(ParseError::ValidationError(format!(
381            "incompatible units '{from_unit}' and '{to_unit}'"
382        )));
383    }
384    Ok(f_from / f_to)
385}
386
387/// Time unit that velocities in this frame are stored in (D10).
388///
389/// Versions 1, 2, and 3.0 are the natural unit regardless of a
390/// `units.time` label (CON-units.8, CON-units.9). From minor 1,
391/// `units.time` is authoritative (CON-units.10). `override_unit`
392/// replaces that choice when it is a time expression (CON-units.15).
393pub fn velocity_file_time_unit(
394    spec_version: u32,
395    metadata: &serde_json::Map<String, serde_json::Value>,
396    override_unit: Option<&str>,
397) -> Result<String, ParseError> {
398    if let Some(unit) = override_unit {
399        validate_unit_for_quantity("time", unit)?;
400        return Ok(unit.to_string());
401    }
402    let minor = metadata
403        .get(crate::types::meta::CON_SPEC_MINOR)
404        .and_then(|v| v.as_u64())
405        .unwrap_or(0);
406    if spec_version < 3 || minor == 0 {
407        return Ok(NATURAL_TIME_UNIT.to_string());
408    }
409    let time = metadata
410        .get(crate::types::meta::UNITS)
411        .and_then(|u| u.get("time"))
412        .and_then(|t| t.as_str())
413        .filter(|s| !s.is_empty());
414    match time {
415        Some(unit) => {
416            validate_unit_for_quantity("time", unit)?;
417            Ok(unit.to_string())
418        }
419        None => Err(ParseError::InvalidUnits(
420            "v3.1 velocities require units.time".into(),
421        )),
422    }
423}
424
425/// Multiply a file velocity by this to land in [`NATURAL_TIME_UNIT`].
426///
427/// Velocity scales as 1/time, so the factor is the reciprocal of
428/// [`unit_conversion_factor`] from the file time unit to the natural unit.
429pub fn velocity_scale_to_natural(file_time: &str) -> Result<f64, ParseError> {
430    validate_unit_for_quantity("time", file_time)?;
431    let factor = unit_conversion_factor(file_time, NATURAL_TIME_UNIT)?;
432    if factor == 0.0 || !factor.is_finite() {
433        return Err(ParseError::InvalidUnits(format!(
434            "time unit '{file_time}' has a zero scale"
435        )));
436    }
437    Ok(1.0 / factor)
438}
439
440/// Validate that `unit` has dimensions appropriate for `quantity`
441/// (`length`, `energy`, `mass`, `time`, `velocity`, `force`).
442pub fn validate_unit_for_quantity(quantity: &str, unit: &str) -> Result<(), ParseError> {
443    let (_, dim) = parse_unit_expression(unit)?;
444    let expect = match quantity {
445        "length" => Dimension::LENGTH,
446        "time" => Dimension::TIME,
447        "mass" => Dimension::MASS,
448        "energy" => Dimension::MASS
449            .mul(Dimension::LENGTH.pow(2.0))
450            .div(Dimension::TIME.pow(2.0)),
451        "velocity" => Dimension::LENGTH.div(Dimension::TIME),
452        "force" => Dimension::MASS
453            .mul(Dimension::LENGTH)
454            .div(Dimension::TIME.pow(2.0)),
455        _ => {
456            return Err(ParseError::ValidationError(format!(
457                "unknown quantity '{quantity}'"
458            )));
459        }
460    };
461    if !dim.compatible(expect) {
462        return Err(ParseError::ValidationError(format!(
463            "unit '{unit}' is not valid for quantity '{quantity}'"
464        )));
465    }
466    Ok(())
467}
468
469/// CON v3 requires `units` object with non-empty `length` and `energy` strings.
470pub fn validate_v3_units_metadata(units: &serde_json::Value) -> Result<(), ParseError> {
471    let obj = units
472        .as_object()
473        .ok_or_else(|| ParseError::ValidationError("units must be a JSON object".into()))?;
474    for key in ["length", "energy"] {
475        let Some(v) = obj.get(key) else {
476            return Err(ParseError::ValidationError(format!(
477                "v3 units must include non-empty '{key}'"
478            )));
479        };
480        let Some(s) = v.as_str() else {
481            return Err(ParseError::ValidationError(format!(
482                "units.{key} must be a string"
483            )));
484        };
485        if s.trim().is_empty() {
486            return Err(ParseError::ValidationError(format!(
487                "units.{key} must be non-empty"
488            )));
489        }
490        validate_unit_for_quantity(key, s)?;
491    }
492    // Optional keys if present must be valid for their quantity
493    for (key, qty) in [
494        ("mass", "mass"),
495        ("time", "time"),
496        ("velocity", "velocity"),
497        ("force", "force"),
498    ] {
499        if let Some(v) = obj.get(key) {
500            let s = v.as_str().ok_or_else(|| {
501                ParseError::ValidationError(format!("units.{key} must be a string"))
502            })?;
503            validate_unit_for_quantity(qty, s)?;
504        }
505    }
506    Ok(())
507}
508
509/// Default LODE units object for new v3 frames.
510/// Pinned spelling of the eOn/ASE natural time unit (CON-units.5, D10).
511pub const NATURAL_TIME_UNIT: &str = "(amu*angstrom^2/eV)^0.5";
512
513pub fn default_v3_units_json() -> serde_json::Value {
514    serde_json::json!({
515        "length": "angstrom",
516        "energy": "eV",
517        "mass": "amu"
518    })
519}
520
521fn preferred_atom(alias: &str) -> Option<&'static str> {
522    let lower = alias.trim().to_lowercase();
523    Some(match lower.as_str() {
524        "a" | "å" | "angstrom" | "ångstrom" => "angstrom",
525        "nm" | "nanometer" | "nanometre" => "nm",
526        "m" | "meter" | "metre" => "m",
527        "bohr" | "a0" => "bohr",
528        "fs" | "femtosecond" | "femtoseconds" => "fs",
529        "ps" | "picosecond" | "picoseconds" => "ps",
530        "ns" | "nanosecond" | "nanoseconds" => "ns",
531        "s" | "sec" | "second" | "seconds" => "s",
532        "ev" => "eV",
533        "mev" => "meV",
534        "hartree" | "ha" => "hartree",
535        "j" | "joule" => "J",
536        "kj" => "kJ",
537        "kcal" => "kcal",
538        "amu" | "u" | "dalton" | "da" => "amu",
539        "kg" | "kilogram" => "kg",
540        "mol" => "mol",
541        _ => return None,
542    })
543}
544
545/// Rewrite a unit expression to preferred names (`A` → `angstrom`, `ev` → `eV`).
546/// The expression MUST parse (`unit_conversion_factor` identity).
547pub fn canonicalize_unit_expression(expr: &str) -> Result<String, ParseError> {
548    let trimmed = expr.trim();
549    if trimmed.is_empty() {
550        return Err(ParseError::ValidationError("empty unit".into()));
551    }
552    let _ = unit_conversion_factor(trimmed, trimmed)?;
553    let compact: String = trimmed.chars().filter(|c| !c.is_whitespace()).collect();
554    if compact == NATURAL_TIME_UNIT {
555        return Ok(NATURAL_TIME_UNIT.to_string());
556    }
557    let mut out = String::new();
558    let bytes = compact.as_bytes();
559    let mut i = 0;
560    while i < bytes.len() {
561        let b = bytes[i];
562        if matches!(b, b'*' | b'/' | b'(' | b')' | b'^') {
563            if !out.is_empty() && !out.ends_with(' ') && b != b')' && b != b'^' {
564                out.push(' ');
565            }
566            out.push(b as char);
567            if b != b'(' && b != b'^' {
568                out.push(' ');
569            }
570            i += 1;
571            continue;
572        }
573        if b == b'-' || b.is_ascii_digit() || b == b'.' {
574            out.push(b as char);
575            i += 1;
576            continue;
577        }
578        let start = i;
579        while i < bytes.len() && (bytes[i].is_ascii_alphabetic() || bytes[i] > 127) {
580            i += 1;
581        }
582        if start == i {
583            return Err(ParseError::ValidationError(format!(
584                "bad unit token in '{expr}'"
585            )));
586        }
587        let atom = &compact[start..i];
588        out.push_str(preferred_atom(atom).unwrap_or(atom));
589    }
590    let rendered = out.split_whitespace().collect::<Vec<_>>().join(" ");
591    let rendered_compact: String = rendered.chars().filter(|c| !c.is_whitespace()).collect();
592    if rendered_compact == NATURAL_TIME_UNIT {
593        return Ok(NATURAL_TIME_UNIT.to_string());
594    }
595    Ok(rendered)
596}
597
598/// Rewrite every string member. Does not require v3 `length`+`energy`.
599pub fn canonicalize_units_object(
600    units: &serde_json::Value,
601) -> Result<serde_json::Value, ParseError> {
602    let obj = units
603        .as_object()
604        .ok_or_else(|| ParseError::ValidationError("units must be a JSON object".into()))?;
605    let mut out = serde_json::Map::new();
606    for (k, v) in obj {
607        let s = v
608            .as_str()
609            .ok_or_else(|| ParseError::ValidationError(format!("units.{k} must be a string")))?;
610        out.insert(
611            k.clone(),
612            serde_json::Value::String(canonicalize_unit_expression(s)?),
613        );
614    }
615    Ok(serde_json::Value::Object(out))
616}
617
618/// v3 validate then canonicalize (preferred names on line 2).
619pub fn canonicalize_units_metadata(
620    units: &serde_json::Value,
621) -> Result<serde_json::Value, ParseError> {
622    validate_v3_units_metadata(units)?;
623    canonicalize_units_object(units)
624}
625
626#[cfg(test)]
627mod tests {
628    use super::*;
629
630    #[test]
631    fn base_table_is_shared_across_calls_and_threads() {
632        for pair in BASE_UNITS.windows(2) {
633            assert!(
634                pair[0].name < pair[1].name,
635                "{} is not before {}",
636                pair[0].name,
637                pair[1].name
638            );
639        }
640        let energy = Dimension::MASS
641            .mul(Dimension::LENGTH.pow(2.0))
642            .div(Dimension::TIME.pow(2.0));
643        assert!(
644            parse_unit_expression("eV").unwrap().1.compatible(energy),
645            "energy exponents drifted from M L^2 T^-2"
646        );
647        let first = cached_unit_table_addr();
648        let second = cached_unit_table_addr();
649        assert_eq!(first, second);
650        let factors = std::thread::scope(|scope| {
651            let mut joins = Vec::new();
652            for _ in 0..8 {
653                joins.push(scope.spawn(|| parse_unit_expression("Angstrom").unwrap().0));
654            }
655            joins
656                .into_iter()
657                .map(|join| join.join().unwrap())
658                .collect::<Vec<_>>()
659        });
660        assert!(factors.iter().all(|factor| (*factor - 1e-10).abs() < 1e-22));
661    }
662
663    #[test]
664    fn angstrom_to_nm() {
665        let f = unit_conversion_factor("angstrom", "nm").unwrap();
666        assert!((f - 0.1).abs() < 1e-12);
667    }
668
669    #[test]
670    fn ev_to_mev() {
671        let f = unit_conversion_factor("eV", "meV").unwrap();
672        assert!((f - 1000.0).abs() < 1e-6);
673    }
674
675    #[test]
676    fn dimensional_mismatch() {
677        assert!(unit_conversion_factor("angstrom", "eV").is_err());
678    }
679
680    #[test]
681    fn ev_to_kcal_per_mol_is_metatomic() {
682        let f = unit_conversion_factor("eV", "kcal / mol").unwrap();
683        assert!((f - 23.060_548).abs() < 1e-3, "got {f}");
684        let force = unit_conversion_factor("eV / angstrom", "kJ / mol / angstrom").unwrap();
685        assert!((force - 96.485_332).abs() < 1e-3, "got {force}");
686        let ns = unit_conversion_factor("ns", "ps").unwrap();
687        assert!((ns - 1000.0).abs() < 1e-9, "got {ns}");
688    }
689
690    #[test]
691    fn validate_length_energy() {
692        validate_unit_for_quantity("length", "nm").unwrap();
693        validate_unit_for_quantity("energy", "hartree").unwrap();
694        assert!(validate_unit_for_quantity("energy", "angstrom").is_err());
695    }
696
697    #[test]
698    fn v3_units_require_length_energy() {
699        assert!(validate_v3_units_metadata(&serde_json::json!({"length": "A"})).is_err());
700        validate_v3_units_metadata(&default_v3_units_json()).unwrap();
701    }
702
703    #[test]
704    fn default_v3_units_do_not_invent_time_fs() {
705        let units = default_v3_units_json();
706        assert!(units.get("time").is_none(), "{units}");
707        assert_eq!(units["length"], "angstrom");
708        assert_eq!(units["energy"], "eV");
709        assert_eq!(units["mass"], "amu");
710    }
711
712    #[test]
713    fn canonicalize_aliases() {
714        assert_eq!(canonicalize_unit_expression("A").unwrap(), "angstrom");
715        assert_eq!(canonicalize_unit_expression("ev").unwrap(), "eV");
716        assert_eq!(canonicalize_unit_expression("femtosecond").unwrap(), "fs");
717        assert_eq!(
718            canonicalize_unit_expression("eV/angstrom").unwrap(),
719            "eV / angstrom"
720        );
721        let u = canonicalize_units_metadata(&serde_json::json!({
722            "length": "A",
723            "energy": "ev",
724            "time": "femtosecond"
725        }))
726        .unwrap();
727        assert_eq!(u["length"], "angstrom");
728        assert_eq!(u["energy"], "eV");
729        assert_eq!(u["time"], "fs");
730    }
731
732    #[test]
733    fn natural_time_spelling_is_pinned() {
734        let spaced = "( amu * angstrom ^ 2 / eV ) ^ 0.5";
735        assert_eq!(
736            canonicalize_unit_expression(spaced).unwrap(),
737            NATURAL_TIME_UNIT
738        );
739        assert!(!NATURAL_TIME_UNIT.contains(' '));
740        let factor = unit_conversion_factor(NATURAL_TIME_UNIT, "fs").unwrap();
741        assert!((factor - 10.180_505_710_759_414).abs() < 1e-9, "{factor}");
742        let mixed = "(AMU * angstrom^2 / ev)^0.5";
743        assert_eq!(
744            canonicalize_unit_expression(mixed).unwrap(),
745            NATURAL_TIME_UNIT
746        );
747    }
748}