Skip to content

Unified unit parser and converter for lengths - #328

Open
NJMarchese wants to merge 1 commit into
electronmicroscopy:devfrom
NJMarchese:feat/unit-conversion
Open

NJMarchese wants to merge 1 commit into
electronmicroscopy:devfrom
NJMarchese:feat/unit-conversion

Conversation

@NJMarchese

Copy link
Copy Markdown
Collaborator

Unified unit parser and converter in core/utils

Dataset axes store their units as free text, and different file formats spell them differently ("nm", "1/nm", "Å^-1", "A-1", "$\mathrm{nm}^{-1}$", "mrad", ...). Several modules parse these strings with their own small tables. This PR adds one shared module, quantem/core/utils/units.py, and doesn't change any existing code.

What it provides

  • parse_units(units) -> Unit | None reads a unit string into Unit(base, kind, power), for example Unit("Å", "length", -1) for "1/A".
    • Lengths: pm, Å, nm, μm, mm, cm and m.
    • Reciprocal lengths: written as 1/x, x^-1, x**-1, x-1, x⁻¹, or in LaTeX.
    • Angles: μrad, mrad, rad and deg.
    • Spelling: common spellings and any letter case. It returns None for anything it doesn't recognize, such as "pixels".
  • unit_conversion_factor(from_units, to_units, energy=None) -> float gives the factor that converts a value or a sampling between units.
    • It converts within lengths, within reciprocal lengths, within angles, and between angles and reciprocal lengths.
    • Converting between an angle and a reciprocal length goes through the electron wavelength at energy (eV), using k = θ/λ (small-angle approx.).
    • It raises ValueError for an unrecognized unit, for incompatible kinds such as a length and a reciprocal length, or for an angle conversion without energy.
  • LENGTH_UNITS_IN_ANGSTROM and ANGLE_UNITS_IN_RADIANS are the underlying tables.

Tests

tests/utils/test_units.py has 4 tests:

  • the accepted and rejected spellings;
  • conversions within each kind;
  • mrad ↔ 1/Å at 300 kV, checked against electron_wavelength_angstrom and as a round trip;
  • each error.

@arthurmccray

Copy link
Copy Markdown
Collaborator

Would it make sense to also modify show_2d (and core/visualization` functions) to use this? I agree with the implementation but in it's current state nothing would use this PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants