| 1 |
""" |
| 2 |
pint.facets.systems.objects |
| 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 |
import numbers |
| 12 |
from collections.abc import Callable, Iterable |
| 13 |
from numbers import Number |
| 14 |
from typing import Any, Generic |
| 15 |
|
| 16 |
from ..._typing import UnitLike |
| 17 |
from ...babel_names import _babel_systems |
| 18 |
from ...compat import babel_parse |
| 19 |
from ...util import ( |
| 20 |
SharedRegistryObject, |
| 21 |
getattr_maybe_raise, |
| 22 |
logger, |
| 23 |
to_units_container, |
| 24 |
) |
| 25 |
from .. import group |
| 26 |
from ..plain import MagnitudeT |
| 27 |
from .definitions import SystemDefinition |
| 28 |
|
| 29 |
GetRootUnits = Callable[[UnitLike, bool], tuple[Number, UnitLike]] |
| 30 |
|
| 31 |
|
| 32 |
class SystemQuantity(Generic[MagnitudeT], group.GroupQuantity[MagnitudeT]): |
| 33 |
pass |
| 34 |
|
| 35 |
|
| 36 |
class SystemUnit(group.GroupUnit): |
| 37 |
pass |
| 38 |
|
| 39 |
|
| 40 |
class System(SharedRegistryObject): |
| 41 |
"""A system is a Group plus a set of plain units. |
| 42 |
|
| 43 |
Members are computed dynamically, that is if a unit is added to a group X |
| 44 |
all groups that include X are affected. |
| 45 |
|
| 46 |
The System belongs to one Registry. |
| 47 |
|
| 48 |
See SystemDefinition for the definition file syntax. |
| 49 |
|
| 50 |
Parameters |
| 51 |
---------- |
| 52 |
name |
| 53 |
Name of the group. |
| 54 |
""" |
| 55 |
|
| 56 |
def __init__(self, name: str): |
| 57 |
#: Name of the system |
| 58 |
#: :type: str |
| 59 |
self.name = name |
| 60 |
|
| 61 |
#: Maps root unit names to a dict indicating the new unit and its exponent. |
| 62 |
self.base_units: dict[str, dict[str, numbers.Number]] = {} |
| 63 |
|
| 64 |
#: Derived unit names. |
| 65 |
self.derived_units: set[str] = set() |
| 66 |
|
| 67 |
#: Names of the _used_groups in used by this system. |
| 68 |
self._used_groups: set[str] = set() |
| 69 |
|
| 70 |
self._computed_members: frozenset[str] | None = None |
| 71 |
|
| 72 |
# Add this system to the system dictionary |
| 73 |
self._REGISTRY._systems[self.name] = self |
| 74 |
|
| 75 |
def __dir__(self): |
| 76 |
return list(self.members) |
| 77 |
|
| 78 |
def __getattr__(self, item: str) -> Any: |
| 79 |
getattr_maybe_raise(self, item) |
| 80 |
u = getattr(self._REGISTRY, self.name + "_" + item, None) |
| 81 |
if u is not None: |
| 82 |
return u |
| 83 |
return getattr(self._REGISTRY, item) |
| 84 |
|
| 85 |
@property |
| 86 |
def members(self): |
| 87 |
d = self._REGISTRY._groups |
| 88 |
if self._computed_members is None: |
| 89 |
tmp: set[str] = set() |
| 90 |
|
| 91 |
for group_name in self._used_groups: |
| 92 |
try: |
| 93 |
tmp |= d[group_name].members |
| 94 |
except KeyError: |
| 95 |
logger.warning( |
| 96 |
"Could not resolve {} in System {}".format( |
| 97 |
group_name, self.name |
| 98 |
) |
| 99 |
) |
| 100 |
|
| 101 |
self._computed_members = frozenset(tmp) |
| 102 |
|
| 103 |
return self._computed_members |
| 104 |
|
| 105 |
def invalidate_members(self): |
| 106 |
"""Invalidate computed members in this Group and all parent nodes.""" |
| 107 |
self._computed_members = None |
| 108 |
|
| 109 |
def add_groups(self, *group_names: str) -> None: |
| 110 |
"""Add groups to group.""" |
| 111 |
self._used_groups |= set(group_names) |
| 112 |
|
| 113 |
self.invalidate_members() |
| 114 |
|
| 115 |
def remove_groups(self, *group_names: str) -> None: |
| 116 |
"""Remove groups from group.""" |
| 117 |
self._used_groups -= set(group_names) |
| 118 |
|
| 119 |
self.invalidate_members() |
| 120 |
|
| 121 |
def format_babel(self, locale: str) -> str: |
| 122 |
"""translate the name of the system.""" |
| 123 |
if locale and self.name in _babel_systems: |
| 124 |
name = _babel_systems[self.name] |
| 125 |
locale = babel_parse(locale) |
| 126 |
return locale.measurement_systems[name] |
| 127 |
return self.name |
| 128 |
|
| 129 |
# TODO: When 3.11 is minimal version, use Self |
| 130 |
|
| 131 |
@classmethod |
| 132 |
def from_lines( |
| 133 |
cls: type[System], |
| 134 |
lines: Iterable[str], |
| 135 |
get_root_func: GetRootUnits, |
| 136 |
non_int_type: type = float, |
| 137 |
) -> System: |
| 138 |
# TODO: we changed something here it used to be |
| 139 |
# system_definition = SystemDefinition.from_lines(lines, get_root_func) |
| 140 |
system_definition = SystemDefinition.from_lines(lines, non_int_type) |
| 141 |
|
| 142 |
if system_definition is None: |
| 143 |
raise ValueError(f"Could not define System from from {lines}") |
| 144 |
|
| 145 |
return cls.from_definition(system_definition, get_root_func) |
| 146 |
|
| 147 |
@classmethod |
| 148 |
def from_definition( |
| 149 |
cls: type[System], |
| 150 |
system_definition: SystemDefinition, |
| 151 |
get_root_func: GetRootUnits | None = None, |
| 152 |
) -> System: |
| 153 |
if get_root_func is None: |
| 154 |
# TODO: kept for backwards compatibility |
| 155 |
get_root_func = cls._REGISTRY.get_root_units |
| 156 |
base_unit_names = {} |
| 157 |
derived_unit_names = [] |
| 158 |
for new_unit, old_unit in system_definition.unit_replacements: |
| 159 |
if old_unit is None: |
| 160 |
old_unit_dict = to_units_container(get_root_func(new_unit)[1]) |
| 161 |
|
| 162 |
if len(old_unit_dict) != 1: |
| 163 |
raise ValueError( |
| 164 |
"The new unit must be a root dimension if not discarded unit is specified." |
| 165 |
) |
| 166 |
|
| 167 |
old_unit, value = dict(old_unit_dict).popitem() |
| 168 |
|
| 169 |
base_unit_names[old_unit] = {new_unit: 1 / value} |
| 170 |
else: |
| 171 |
# The old unit MUST be a root unit, if not raise an error. |
| 172 |
if old_unit != str(get_root_func(old_unit)[1]): |
| 173 |
raise ValueError( |
| 174 |
f"The old unit {old_unit} must be a root unit " |
| 175 |
f"in order to be replaced by new unit {new_unit}" |
| 176 |
) |
| 177 |
|
| 178 |
# Here we find new_unit expanded in terms of root_units |
| 179 |
new_unit_expanded = to_units_container( |
| 180 |
get_root_func(new_unit)[1], cls._REGISTRY |
| 181 |
) |
| 182 |
|
| 183 |
# We require that the old unit is present in the new_unit expanded |
| 184 |
if old_unit not in new_unit_expanded: |
| 185 |
raise ValueError("Old unit must be a component of new unit") |
| 186 |
|
| 187 |
# Here we invert the equation, in other words |
| 188 |
# we write old units in terms new unit and expansion |
| 189 |
new_unit_dict = { |
| 190 |
new_unit: -1 / value |
| 191 |
for new_unit, value in new_unit_expanded.items() |
| 192 |
if new_unit != old_unit |
| 193 |
} |
| 194 |
new_unit_dict[new_unit] = 1 / new_unit_expanded[old_unit] |
| 195 |
|
| 196 |
base_unit_names[old_unit] = new_unit_dict |
| 197 |
|
| 198 |
system = cls(system_definition.name) |
| 199 |
system.add_groups(*system_definition.using_group_names) |
| 200 |
system.base_units.update(**base_unit_names) |
| 201 |
system.derived_units |= set(derived_unit_names) |
| 202 |
|
| 203 |
return system |
| 204 |
|
| 205 |
|
| 206 |
class Lister: |
| 207 |
def __init__(self, d: dict[str, Any]): |
| 208 |
self.d = d |
| 209 |
|
| 210 |
def __dir__(self) -> list[str]: |
| 211 |
return list(self.d.keys()) |
| 212 |
|
| 213 |
def __getattr__(self, item: str) -> Any: |
| 214 |
getattr_maybe_raise(self, item) |
| 215 |
return self.d[item] |