| 1 |
""" |
| 2 |
pint.facets.systems.registry |
| 3 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 4 |
|
| 5 |
:copyright: 2022 by Pint Authors, see AUTHORS for more details. |
| 6 |
:license: BSD, see LICENSE for more details. |
| 7 |
""" |
| 8 |
|
| 9 |
from __future__ import annotations |
| 10 |
|
| 11 |
from numbers import Number |
| 12 |
from typing import TYPE_CHECKING, Generic |
| 13 |
|
| 14 |
from ... import errors |
| 15 |
from ...compat import TypeAlias |
| 16 |
from ..plain import QuantityT, UnitT |
| 17 |
|
| 18 |
if TYPE_CHECKING: |
| 19 |
from ..._typing import Quantity, Unit |
| 20 |
|
| 21 |
from ..._typing import UnitLike |
| 22 |
from ...util import UnitsContainer as UnitsContainerT |
| 23 |
from ...util import ( |
| 24 |
create_class_with_registry, |
| 25 |
to_units_container, |
| 26 |
) |
| 27 |
from ..group import GenericGroupRegistry |
| 28 |
from . import objects |
| 29 |
from .definitions import SystemDefinition |
| 30 |
|
| 31 |
|
| 32 |
class GenericSystemRegistry( |
| 33 |
Generic[QuantityT, UnitT], GenericGroupRegistry[QuantityT, UnitT] |
| 34 |
): |
| 35 |
"""Handle of Systems. |
| 36 |
|
| 37 |
Conversion between units with different dimensions according |
| 38 |
to previously established relations (contexts). |
| 39 |
(e.g. in the spectroscopy, conversion between frequency and energy is possible) |
| 40 |
|
| 41 |
Capabilities: |
| 42 |
|
| 43 |
- Register systems. |
| 44 |
- List systems |
| 45 |
- Get or get the default system. |
| 46 |
- Parse @group directive. |
| 47 |
""" |
| 48 |
|
| 49 |
# TODO: Change this to System: System to specify class |
| 50 |
# and use introspection to get system class as a way |
| 51 |
# to enjoy typing goodies |
| 52 |
System: type[objects.System] |
| 53 |
|
| 54 |
def __init__(self, system: str | None = None, **kwargs): |
| 55 |
super().__init__(**kwargs) |
| 56 |
|
| 57 |
#: Map system name to system. |
| 58 |
self._systems: dict[str, objects.System] = {} |
| 59 |
|
| 60 |
#: Maps dimensionality (UnitsContainer) to Dimensionality (UnitsContainer) |
| 61 |
self._base_units_cache: dict[UnitsContainerT, UnitsContainerT] = {} |
| 62 |
|
| 63 |
self._default_system_name: str | None = system |
| 64 |
|
| 65 |
def _init_dynamic_classes(self) -> None: |
| 66 |
"""Generate subclasses on the fly and attach them to self""" |
| 67 |
super()._init_dynamic_classes() |
| 68 |
self.System = create_class_with_registry(self, objects.System) |
| 69 |
|
| 70 |
def _after_init(self) -> None: |
| 71 |
"""Invoked at the end of ``__init__``. |
| 72 |
|
| 73 |
- Create default group and add all orphan units to it |
| 74 |
- Set default system |
| 75 |
""" |
| 76 |
super()._after_init() |
| 77 |
|
| 78 |
#: System name to be used by default. |
| 79 |
self._default_system_name = self._default_system_name or self._defaults.get( |
| 80 |
"system", None |
| 81 |
) |
| 82 |
|
| 83 |
def _register_definition_adders(self) -> None: |
| 84 |
super()._register_definition_adders() |
| 85 |
self._register_adder(SystemDefinition, self._add_system) |
| 86 |
|
| 87 |
def _add_system(self, sd: SystemDefinition) -> None: |
| 88 |
if sd.name in self._systems: |
| 89 |
raise ValueError(f"System {sd.name} already present in registry") |
| 90 |
|
| 91 |
try: |
| 92 |
# As a System is a SharedRegistryObject |
| 93 |
# it adds itself to the registry. |
| 94 |
self.System.from_definition(sd) |
| 95 |
except KeyError as e: |
| 96 |
# TODO: fix this error message |
| 97 |
raise errors.DefinitionError(f"unknown dimension {e} in context") |
| 98 |
|
| 99 |
@property |
| 100 |
def sys(self): |
| 101 |
return objects.Lister(self._systems) |
| 102 |
|
| 103 |
@property |
| 104 |
def default_system(self) -> str | None: |
| 105 |
return self._default_system_name |
| 106 |
|
| 107 |
@default_system.setter |
| 108 |
def default_system(self, name: str) -> None: |
| 109 |
if name: |
| 110 |
if name not in self._systems: |
| 111 |
raise ValueError("Unknown system %s" % name) |
| 112 |
|
| 113 |
self._base_units_cache = {} |
| 114 |
|
| 115 |
self._default_system_name = name |
| 116 |
|
| 117 |
def get_system(self, name: str, create_if_needed: bool = True) -> objects.System: |
| 118 |
"""Return a Group. |
| 119 |
|
| 120 |
Parameters |
| 121 |
---------- |
| 122 |
name : str |
| 123 |
Name of the group to be. |
| 124 |
create_if_needed : bool |
| 125 |
If True, create a group if not found. If False, raise an Exception. |
| 126 |
(Default value = True) |
| 127 |
|
| 128 |
Returns |
| 129 |
------- |
| 130 |
type |
| 131 |
System |
| 132 |
|
| 133 |
""" |
| 134 |
if name in self._systems: |
| 135 |
return self._systems[name] |
| 136 |
|
| 137 |
if not create_if_needed: |
| 138 |
raise ValueError("Unknown system %s" % name) |
| 139 |
|
| 140 |
return self.System(name) |
| 141 |
|
| 142 |
def get_base_units( |
| 143 |
self, |
| 144 |
input_units: UnitLike | Quantity, |
| 145 |
check_nonmult: bool = True, |
| 146 |
system: str | objects.System | None = None, |
| 147 |
) -> tuple[Number, Unit]: |
| 148 |
"""Convert unit or dict of units to the plain units. |
| 149 |
|
| 150 |
If any unit is non multiplicative and check_converter is True, |
| 151 |
then None is returned as the multiplicative factor. |
| 152 |
|
| 153 |
Unlike PlainRegistry, in this registry root_units might be different |
| 154 |
from base_units |
| 155 |
|
| 156 |
Parameters |
| 157 |
---------- |
| 158 |
input_units : UnitsContainer or str |
| 159 |
units |
| 160 |
check_nonmult : bool |
| 161 |
if True, None will be returned as the |
| 162 |
multiplicative factor if a non-multiplicative |
| 163 |
units is found in the final Units. (Default value = True) |
| 164 |
system : |
| 165 |
(Default value = None) |
| 166 |
|
| 167 |
Returns |
| 168 |
------- |
| 169 |
type |
| 170 |
multiplicative factor, plain units |
| 171 |
|
| 172 |
""" |
| 173 |
|
| 174 |
input_units = to_units_container(input_units) |
| 175 |
|
| 176 |
f, units = self._get_base_units(input_units, check_nonmult, system) |
| 177 |
|
| 178 |
return f, self.Unit(units) |
| 179 |
|
| 180 |
def _get_base_units( |
| 181 |
self, |
| 182 |
input_units: UnitsContainerT, |
| 183 |
check_nonmult: bool = True, |
| 184 |
system: str | objects.System | None = None, |
| 185 |
): |
| 186 |
if system is None: |
| 187 |
system = self._default_system_name |
| 188 |
|
| 189 |
# The cache is only done for check_nonmult=True and the current system. |
| 190 |
if ( |
| 191 |
check_nonmult |
| 192 |
and system == self._default_system_name |
| 193 |
and input_units in self._base_units_cache |
| 194 |
): |
| 195 |
return self._base_units_cache[input_units] |
| 196 |
|
| 197 |
factor, units = self.get_root_units(input_units, check_nonmult) |
| 198 |
|
| 199 |
if not system: |
| 200 |
return factor, units |
| 201 |
|
| 202 |
# This will not be necessary after integration with the registry |
| 203 |
# as it has a UnitsContainer intermediate |
| 204 |
units = to_units_container(units, self) |
| 205 |
|
| 206 |
destination_units = self.UnitsContainer() |
| 207 |
|
| 208 |
bu = self.get_system(system, False).base_units |
| 209 |
|
| 210 |
for unit, value in units.items(): |
| 211 |
if unit in bu: |
| 212 |
new_unit = bu[unit] |
| 213 |
new_unit = to_units_container(new_unit, self) |
| 214 |
destination_units *= new_unit**value |
| 215 |
else: |
| 216 |
destination_units *= self.UnitsContainer({unit: value}) |
| 217 |
|
| 218 |
base_factor = self.convert(factor, units, destination_units) |
| 219 |
|
| 220 |
if check_nonmult: |
| 221 |
self._base_units_cache[input_units] = base_factor, destination_units |
| 222 |
|
| 223 |
return base_factor, destination_units |
| 224 |
|
| 225 |
def get_compatible_units( |
| 226 |
self, input_units: UnitsContainerT, group_or_system: str | None = None |
| 227 |
) -> frozenset[Unit]: |
| 228 |
""" """ |
| 229 |
|
| 230 |
group_or_system = group_or_system or self._default_system_name |
| 231 |
|
| 232 |
if group_or_system is None: |
| 233 |
return super().get_compatible_units(input_units) |
| 234 |
|
| 235 |
input_units = to_units_container(input_units) |
| 236 |
|
| 237 |
equiv = self._get_compatible_units(input_units, group_or_system) |
| 238 |
|
| 239 |
return frozenset(self.Unit(eq) for eq in equiv) |
| 240 |
|
| 241 |
def _get_compatible_units( |
| 242 |
self, input_units: UnitsContainerT, group_or_system: str | None = None |
| 243 |
) -> frozenset[Unit]: |
| 244 |
if group_or_system and group_or_system in self._systems: |
| 245 |
members = self._systems[group_or_system].members |
| 246 |
# group_or_system has been handled by System |
| 247 |
return frozenset(members & super()._get_compatible_units(input_units)) |
| 248 |
|
| 249 |
try: |
| 250 |
# This will be handled by groups |
| 251 |
return super()._get_compatible_units(input_units, group_or_system) |
| 252 |
except ValueError as ex: |
| 253 |
# It might be also a system |
| 254 |
if "Unknown Group" in str(ex): |
| 255 |
raise ValueError( |
| 256 |
"Unknown Group o System with name '%s'" % group_or_system |
| 257 |
) from ex |
| 258 |
raise ex |
| 259 |
|
| 260 |
|
| 261 |
class SystemRegistry(GenericSystemRegistry[objects.SystemQuantity, objects.SystemUnit]): |
| 262 |
Quantity: TypeAlias = objects.SystemQuantity |
| 263 |
Unit: TypeAlias = objects.SystemUnit |