-
Notifications
You must be signed in to change notification settings - Fork 3
feat: add Pint integration for unit conversions #273
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
6a250a0
feat: add Pint integration for unit conversions
nsmith- 9c2b81f
Better test coverage
nsmith- f2c1da7
style: pre-commit fixes
pre-commit-ci[bot] 3e2c6bf
lint
nsmith- 2316a20
style: pre-commit fixes
pre-commit-ci[bot] 097450f
More lint
nsmith- 9023db2
more lint
nsmith- 1104668
Construct explicitly
nsmith- 3814964
Add license statement to pint.py
eduardo-rodrigues a6b1b5c
Add trivial docstring to test_pint.py
eduardo-rodrigues eb6b0c8
style: pre-commit fixes
pre-commit-ci[bot] b84acdc
Apply suggestions from code review
nsmith- c2dbec1
Advertise pint on README
nsmith- File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| # Licensed under a 3-clause BSD style license, see LICENSE. | ||
| """ | ||
| Conversion routines between CLHEP, the HEP System of Units, and Pint units. | ||
|
|
||
| CLHEP adopts the approach where all the quantities are stored in the base unit | ||
| system, effectively dimensionless. Pint offers to store both the magnitude and | ||
| the dimensionality of the unit, which is helpful in deducing and/or validating | ||
| the resulting unit of formulas. This module offers conversion routines between | ||
| Pint's default base unit system and CLHEP. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| try: | ||
| import pint | ||
| except ImportError as exc: | ||
| msg = "Pint is required to use hepunits.pint." | ||
| raise ImportError(msg) from exc | ||
|
|
||
| # TODO: support more unit conversions | ||
| _clhep_base_units = { | ||
| "[length]": "millimeter", | ||
| "[time]": "nanosecond", | ||
| "[mass]": "MeV * millimeter**-2 * nanosecond**2", | ||
| "[current]": "elementary_charge / nanosecond", | ||
| } | ||
|
|
||
|
|
||
| def _unit_from(val: pint.Quantity | pint.Unit) -> pint.Unit: | ||
| """Extract the dimensionality from a Pint Quantity or Unit.""" | ||
| # Grabbing the type is a quick way to be in the correct unit registry | ||
| # see e.g. https://github.com/hgrecco/pint/issues/2207 | ||
| unit = type(val.units) if isinstance(val, pint.Quantity) else type(val) | ||
| out = unit("dimensionless") | ||
| for dim, exponent in val.dimensionality.items(): | ||
| if dim not in _clhep_base_units: | ||
| msg = f"Unsupported dimension {dim} in {val}" | ||
| raise ValueError(msg) | ||
| out *= unit(_clhep_base_units[dim]) ** exponent | ||
|
|
||
| return out | ||
|
|
||
|
|
||
| def to_clhep(val: pint.Quantity | pint.Unit) -> float: | ||
| """ | ||
| Convert a Pint Quantity or Unit to CLHEP base units. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| val : pint.Quantity or pint.Unit | ||
| The value to convert. | ||
|
|
||
| Returns | ||
| ------- | ||
| float | ||
| The value in CLHEP base units (dimensionless). | ||
|
|
||
| Examples | ||
| -------- | ||
| >>> ureg = pint.UnitRegistry() | ||
| >>> g = 9.8 * ureg.meter / ureg.second**2 | ||
| >>> g | ||
| <Quantity(9.8, 'meter / second ** 2')> | ||
| >>> to_clhep(g) | ||
| 9.800000000000001e-15 | ||
| """ | ||
nsmith- marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| clhep_unit = _unit_from(val) | ||
| q = pint.Quantity(1.0, val) if isinstance(val, pint.Unit) else val | ||
| return q.to(clhep_unit).magnitude # type: ignore[no-any-return] | ||
|
|
||
|
|
||
| def from_clhep(val: float, unit: pint.Unit) -> pint.Quantity: | ||
| """ | ||
| Convert a value in CLHEP base units to a Pint Quantity. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| val : float | ||
| The value in CLHEP base units (dimensionless). | ||
| unit : pint.Unit | ||
| The desired output unit. | ||
|
|
||
| Returns | ||
| ------- | ||
| pint.Quantity | ||
| The value in the desired unit. | ||
|
|
||
| Examples | ||
| -------- | ||
| >>> ureg = pint.UnitRegistry() | ||
| >>> from_clhep(hepunits.c_light, ureg.meter / ureg.second) | ||
| <Quantity(299792458.0, 'meter / second')> | ||
| """ | ||
nsmith- marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| clhep_unit = _unit_from(unit) | ||
| return pint.Quantity(val, clhep_unit).to(unit) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| #!/usr/bin/env python | ||
| # Licensed under a 3-clause BSD style license, see LICENSE. | ||
| """ | ||
| Tests for the hepunits.pint module. | ||
| """ | ||
|
|
||
| import pint | ||
| import pytest | ||
| from pytest import approx | ||
|
|
||
| import hepunits | ||
| from hepunits.pint import from_clhep, to_clhep | ||
|
|
||
|
|
||
| def test_pint_constants(): | ||
| ureg = pint.UnitRegistry() | ||
|
|
||
| # These three constants set the relationship between mass, length, time, and charge | ||
| # TODO: check all 7 SI defining constants (hence also supporting more unit conversions) | ||
| pint_c = to_clhep(1 * ureg.speed_of_light) | ||
| assert pint_c == approx(hepunits.c_light, rel=1e-15) | ||
| pint_h = to_clhep(1 * ureg.planck_constant) | ||
| assert pint_h == approx(hepunits.h_Planck, rel=1e-15) | ||
| pint_e = to_clhep(1 * ureg.elementary_charge) | ||
| assert pint_e == approx(1.0, rel=1e-15) | ||
|
|
||
|
|
||
| def test_pint_roundtrip(): | ||
| ureg = pint.UnitRegistry() | ||
|
|
||
| assert to_clhep(3 * ureg.mm) == approx(3.0) | ||
| assert to_clhep(3 * ureg.cm) == approx(30.0) | ||
| assert to_clhep(2 * ureg.ohm) == approx(2.0 * hepunits.ohm) | ||
| assert to_clhep(ureg.coulomb) == approx(hepunits.coulomb) | ||
|
|
||
| assert from_clhep(hepunits.c_light, ureg.meter / ureg.second).m == approx( | ||
| (1.0 * ureg.c).to(ureg.meter / ureg.second).m, rel=1e-15 | ||
| ) | ||
| assert from_clhep(hepunits.tesla, ureg.tesla).m == approx( | ||
| (1 * ureg.tesla).m, rel=1e-15 | ||
| ) | ||
|
|
||
|
|
||
| def test_unsupported_dimension(): | ||
| ureg = pint.UnitRegistry() | ||
| with pytest.raises(ValueError, match="Unsupported dimension"): | ||
| to_clhep(1 * ureg.kelvin) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.