From ae0316173aa0a95ed4ba6b07bc07d66a2e3ac592 Mon Sep 17 00:00:00 2001 From: Robb Traister Date: Thu, 7 May 2026 16:23:03 -0400 Subject: [PATCH] add get_compatible_units function --- gemd/__version__.py | 2 +- gemd/units/__init__.py | 2 ++ gemd/units/impl.py | 17 +++++++++++++++++ tests/units/test_parser.py | 14 ++++++++++++++ 4 files changed, 34 insertions(+), 1 deletion(-) diff --git a/gemd/__version__.py b/gemd/__version__.py index ef6497d..3d67cd6 100644 --- a/gemd/__version__.py +++ b/gemd/__version__.py @@ -1 +1 @@ -__version__ = "2.3.2" +__version__ = "2.4.0" diff --git a/gemd/units/__init__.py b/gemd/units/__init__.py index fc4bd89..425969a 100644 --- a/gemd/units/__init__.py +++ b/gemd/units/__init__.py @@ -3,6 +3,7 @@ parse_units, convert_units, get_base_units, + get_compatible_units, change_definitions_file, UndefinedUnitError, IncompatibleUnitsError, @@ -13,6 +14,7 @@ "parse_units", "convert_units", "get_base_units", + "get_compatible_units", "change_definitions_file", "UndefinedUnitError", "IncompatibleUnitsError", diff --git a/gemd/units/impl.py b/gemd/units/impl.py index 3bcd789..1c608de 100644 --- a/gemd/units/impl.py +++ b/gemd/units/impl.py @@ -385,6 +385,23 @@ def get_base_units(units: Union[str, UnitRegistry.Unit]) -> Tuple[UnitRegistry.U return base_unit, float(ratio), offset +def get_compatible_units(units: Union[str, UnitRegistry.Unit]) -> List[str]: + """Get all compatible units that match the dimensionality of the provided units. + + Parameters + ---------- + units: str, Unit + The representation of the object we wish to compare + + Returns + ------- + List[str] + A list of the compatible units. + + """ + return [f"{u}" for u in _REGISTRY.get_compatible_units(units)] + + def change_definitions_file(filename: str = None): """Change which file is used for units definition. diff --git a/tests/units/test_parser.py b/tests/units/test_parser.py index 031bc24..13db18f 100644 --- a/tests/units/test_parser.py +++ b/tests/units/test_parser.py @@ -13,6 +13,7 @@ change_definitions_file, convert_units, get_base_units, + get_compatible_units, parse_units, ) @@ -191,6 +192,19 @@ def test_get_base_units(): assert get_base_units("g / 25 mm") == (_REGISTRY("kg / m"), 0.04, 0) +def test_get_compatible_units(): + """Test that compatible units make sense.""" + from gemd.units.impl import _REGISTRY + assert "kelvin" in get_compatible_units("degC") + assert "degree_Celsius" in get_compatible_units("degC") + assert "gram" in get_compatible_units("kg") + assert "meter" not in get_compatible_units("kg") + assert "meter" in get_compatible_units("km") + assert "meter" in get_compatible_units(_REGISTRY("km")) + assert "meter" in get_compatible_units("[length]") + assert "gram" not in get_compatible_units("km") + + @contextmanager def _change_units(filename): try: