| 1 |
""" |
| 2 |
pint.facets.context.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 weakref |
| 12 |
from collections import ChainMap, defaultdict |
| 13 |
from collections.abc import Callable, Iterable |
| 14 |
from typing import TYPE_CHECKING, Any, Generic, Protocol |
| 15 |
|
| 16 |
from ..._typing import Magnitude |
| 17 |
from ...facets.plain import MagnitudeT, PlainQuantity, PlainUnit, UnitDefinition |
| 18 |
from ...util import UnitsContainer, to_units_container |
| 19 |
from .definitions import ContextDefinition |
| 20 |
|
| 21 |
if TYPE_CHECKING: |
| 22 |
from ...registry import UnitRegistry |
| 23 |
|
| 24 |
|
| 25 |
class Transformation(Protocol): |
| 26 |
def __call__( |
| 27 |
self, ureg: UnitRegistry, value: PlainQuantity, **kwargs: Any |
| 28 |
) -> PlainQuantity: ... |
| 29 |
|
| 30 |
|
| 31 |
from ..._typing import UnitLike |
| 32 |
|
| 33 |
ToBaseFunc = Callable[[UnitsContainer], UnitsContainer] |
| 34 |
SrcDst = tuple[UnitsContainer, UnitsContainer] |
| 35 |
|
| 36 |
|
| 37 |
class ContextQuantity(Generic[MagnitudeT], PlainQuantity[MagnitudeT]): |
| 38 |
pass |
| 39 |
|
| 40 |
|
| 41 |
class ContextUnit(PlainUnit): |
| 42 |
pass |
| 43 |
|
| 44 |
|
| 45 |
class Context: |
| 46 |
"""A specialized container that defines transformation functions from one |
| 47 |
dimension to another. Each Dimension are specified using a UnitsContainer. |
| 48 |
Simple transformation are given with a function taking a single parameter. |
| 49 |
|
| 50 |
Conversion functions may take optional keyword arguments and the context |
| 51 |
can have default values for these arguments. |
| 52 |
|
| 53 |
Additionally, a context may host redefinitions. |
| 54 |
|
| 55 |
A redefinition must be performed among units that already exist in the registry. It |
| 56 |
cannot change the dimensionality of a unit. The symbol and aliases are automatically |
| 57 |
inherited from the registry. |
| 58 |
|
| 59 |
See ContextDefinition for the definition file syntax. |
| 60 |
|
| 61 |
Parameters |
| 62 |
---------- |
| 63 |
name : str or None, optional |
| 64 |
Name of the context (must be unique within the registry). |
| 65 |
Use None for anonymous Context. (Default value = None). |
| 66 |
aliases : iterable of str |
| 67 |
Other names for the context. |
| 68 |
defaults : None or dict |
| 69 |
Maps variable names to values. |
| 70 |
|
| 71 |
Example |
| 72 |
------- |
| 73 |
|
| 74 |
>>> from pint.util import UnitsContainer |
| 75 |
>>> from pint import Context, UnitRegistry |
| 76 |
>>> ureg = UnitRegistry() |
| 77 |
>>> timedim = UnitsContainer({"[time]": 1}) |
| 78 |
>>> spacedim = UnitsContainer({"[length]": 1}) |
| 79 |
>>> def time_to_len(ureg, time): |
| 80 |
... "Time to length converter" |
| 81 |
... return 3.0 * time |
| 82 |
>>> c = Context() |
| 83 |
>>> c.add_transformation(timedim, spacedim, time_to_len) |
| 84 |
>>> c.transform(timedim, spacedim, ureg, 2) |
| 85 |
6.0 |
| 86 |
>>> def time_to_len_indexed(ureg, time, n=1): |
| 87 |
... "Time to length converter, n is the index of refraction of the material" |
| 88 |
... return 3.0 * time / n |
| 89 |
>>> c = Context(defaults={"n": 3}) |
| 90 |
>>> c.add_transformation(timedim, spacedim, time_to_len_indexed) |
| 91 |
>>> c.transform(timedim, spacedim, ureg, 2) |
| 92 |
2.0 |
| 93 |
>>> c.redefine("pound = 0.5 kg") |
| 94 |
""" |
| 95 |
|
| 96 |
def __init__( |
| 97 |
self, |
| 98 |
name: str | None = None, |
| 99 |
aliases: tuple[str, ...] = tuple(), |
| 100 |
defaults: dict[str, Any] | None = None, |
| 101 |
) -> None: |
| 102 |
self.name: str | None = name |
| 103 |
self.aliases: tuple[str, ...] = aliases |
| 104 |
|
| 105 |
#: Maps (src, dst) -> transformation function |
| 106 |
self.funcs: dict[SrcDst, Transformation] = {} |
| 107 |
|
| 108 |
#: Maps defaults variable names to values |
| 109 |
self.defaults: dict[str, Any] = defaults or {} |
| 110 |
|
| 111 |
# Store Definition objects that are context-specific |
| 112 |
# TODO: narrow type this if possible. |
| 113 |
self.redefinitions: list[Any] = [] |
| 114 |
|
| 115 |
# Flag set to True by the Registry the first time the context is enabled |
| 116 |
self.checked = False |
| 117 |
|
| 118 |
#: Maps (src, dst) -> self |
| 119 |
#: Used as a convenience dictionary to be composed by ContextChain |
| 120 |
self.relation_to_context: weakref.WeakValueDictionary[SrcDst, Context] = ( |
| 121 |
weakref.WeakValueDictionary() |
| 122 |
) |
| 123 |
|
| 124 |
@classmethod |
| 125 |
def from_context(cls, context: Context, **defaults: Any) -> Context: |
| 126 |
"""Creates a new context that shares the funcs dictionary with the |
| 127 |
original context. The default values are copied from the original |
| 128 |
context and updated with the new defaults. |
| 129 |
|
| 130 |
If defaults is empty, return the same context. |
| 131 |
|
| 132 |
Parameters |
| 133 |
---------- |
| 134 |
context : pint.Context |
| 135 |
Original context. |
| 136 |
**defaults |
| 137 |
|
| 138 |
|
| 139 |
Returns |
| 140 |
------- |
| 141 |
pint.Context |
| 142 |
""" |
| 143 |
if defaults: |
| 144 |
newdef = dict(context.defaults, **defaults) |
| 145 |
c = cls(context.name, context.aliases, newdef) |
| 146 |
c.funcs = context.funcs |
| 147 |
c.redefinitions = context.redefinitions |
| 148 |
for edge in context.funcs: |
| 149 |
c.relation_to_context[edge] = c |
| 150 |
return c |
| 151 |
return context |
| 152 |
|
| 153 |
@classmethod |
| 154 |
def from_lines( |
| 155 |
cls, |
| 156 |
lines: Iterable[str], |
| 157 |
to_base_func: ToBaseFunc | None = None, |
| 158 |
non_int_type: type = float, |
| 159 |
) -> Context: |
| 160 |
context_definition = ContextDefinition.from_lines(lines, non_int_type) |
| 161 |
|
| 162 |
if context_definition is None: |
| 163 |
raise ValueError(f"Could not define Context from from {lines}") |
| 164 |
|
| 165 |
return cls.from_definition(context_definition, to_base_func) |
| 166 |
|
| 167 |
@classmethod |
| 168 |
def from_definition( |
| 169 |
cls, cd: ContextDefinition, to_base_func: ToBaseFunc | None = None |
| 170 |
) -> Context: |
| 171 |
ctx = cls(cd.name, cd.aliases, cd.defaults) |
| 172 |
|
| 173 |
for definition in cd.redefinitions: |
| 174 |
ctx._redefine(definition) |
| 175 |
|
| 176 |
for relation in cd.relations: |
| 177 |
try: |
| 178 |
# TODO: check to_base_func. Is it a good API idea? |
| 179 |
if to_base_func: |
| 180 |
src = to_base_func(relation.src) |
| 181 |
dst = to_base_func(relation.dst) |
| 182 |
else: |
| 183 |
src, dst = relation.src, relation.dst |
| 184 |
ctx.add_transformation(src, dst, relation.transformation) |
| 185 |
if relation.bidirectional: |
| 186 |
ctx.add_transformation(dst, src, relation.transformation) |
| 187 |
except Exception as exc: |
| 188 |
raise ValueError( |
| 189 |
f"Could not add Context {cd.name} relation {relation}" |
| 190 |
) from exc |
| 191 |
|
| 192 |
return ctx |
| 193 |
|
| 194 |
def add_transformation( |
| 195 |
self, src: UnitLike, dst: UnitLike, func: Transformation |
| 196 |
) -> None: |
| 197 |
"""Add a transformation function to the context.""" |
| 198 |
|
| 199 |
_key = self.__keytransform__(src, dst) |
| 200 |
self.funcs[_key] = func |
| 201 |
self.relation_to_context[_key] = self |
| 202 |
|
| 203 |
def remove_transformation(self, src: UnitLike, dst: UnitLike) -> None: |
| 204 |
"""Add a transformation function to the context.""" |
| 205 |
|
| 206 |
_key = self.__keytransform__(src, dst) |
| 207 |
del self.funcs[_key] |
| 208 |
del self.relation_to_context[_key] |
| 209 |
|
| 210 |
@staticmethod |
| 211 |
def __keytransform__(src: UnitLike, dst: UnitLike) -> SrcDst: |
| 212 |
return to_units_container(src), to_units_container(dst) |
| 213 |
|
| 214 |
def transform( |
| 215 |
self, |
| 216 |
src: UnitLike, |
| 217 |
dst: UnitLike, |
| 218 |
registry: Any, |
| 219 |
value: Magnitude, |
| 220 |
**ctx_kwargs, |
| 221 |
) -> Magnitude: |
| 222 |
"""Transform a value.""" |
| 223 |
|
| 224 |
_key = self.__keytransform__(src, dst) |
| 225 |
func = self.funcs[_key] |
| 226 |
defaults = self.defaults.copy() |
| 227 |
defaults.update(ctx_kwargs) |
| 228 |
return func(registry, value, **defaults) |
| 229 |
|
| 230 |
def redefine(self, definition: str) -> None: |
| 231 |
"""Override the definition of a unit in the registry. |
| 232 |
|
| 233 |
Parameters |
| 234 |
---------- |
| 235 |
definition : str |
| 236 |
<unit> = <new definition>``, e.g. ``pound = 0.5 kg`` |
| 237 |
""" |
| 238 |
from ...delegates import ParserConfig, txt_defparser |
| 239 |
|
| 240 |
# TODO: kept for backwards compatibility. |
| 241 |
# this is not a good idea as we have no way of known the correct non_int_type |
| 242 |
cfg = ParserConfig(float) |
| 243 |
parser = txt_defparser.DefParser(cfg, None) |
| 244 |
pp = parser.parse_string(definition) |
| 245 |
for definition in parser.iter_parsed_project(pp): |
| 246 |
if isinstance(definition, UnitDefinition): |
| 247 |
self._redefine(definition) |
| 248 |
|
| 249 |
def _redefine(self, definition: UnitDefinition): |
| 250 |
self.redefinitions.append(definition) |
| 251 |
|
| 252 |
def hashable( |
| 253 |
self, |
| 254 |
) -> tuple[ |
| 255 |
str | None, |
| 256 |
tuple[str, ...], |
| 257 |
frozenset[tuple[SrcDst, int]], |
| 258 |
frozenset[tuple[str, Any]], |
| 259 |
tuple[Any, ...], |
| 260 |
]: |
| 261 |
"""Generate a unique hashable and comparable representation of self, which can |
| 262 |
be used as a key in a dict. This class cannot define ``__hash__`` because it is |
| 263 |
mutable, and the Python interpreter does cache the output of ``__hash__``. |
| 264 |
|
| 265 |
Returns |
| 266 |
------- |
| 267 |
tuple |
| 268 |
""" |
| 269 |
return ( |
| 270 |
self.name, |
| 271 |
tuple(self.aliases), |
| 272 |
frozenset((k, id(v)) for k, v in self.funcs.items()), |
| 273 |
frozenset(self.defaults.items()), |
| 274 |
tuple(self.redefinitions), |
| 275 |
) |
| 276 |
|
| 277 |
|
| 278 |
class ContextChain(ChainMap[SrcDst, Context]): |
| 279 |
"""A specialized ChainMap for contexts that simplifies finding rules |
| 280 |
to transform from one dimension to another. |
| 281 |
""" |
| 282 |
|
| 283 |
def __init__(self): |
| 284 |
super().__init__() |
| 285 |
self.contexts: list[Context] = [] |
| 286 |
self.maps.clear() # Remove default empty map |
| 287 |
self._graph: dict[SrcDst, set[UnitsContainer]] | None = None |
| 288 |
|
| 289 |
def insert_contexts(self, *contexts: Context): |
| 290 |
"""Insert one or more contexts in reversed order the chained map. |
| 291 |
(A rule in last context will take precedence) |
| 292 |
|
| 293 |
To facilitate the identification of the context with the matching rule, |
| 294 |
the *relation_to_context* dictionary of the context is used. |
| 295 |
""" |
| 296 |
|
| 297 |
self.contexts = list(reversed(contexts)) + self.contexts |
| 298 |
self.maps = [ctx.relation_to_context for ctx in reversed(contexts)] + self.maps |
| 299 |
self._graph = None |
| 300 |
|
| 301 |
def remove_contexts(self, n: int | None = None): |
| 302 |
"""Remove the last n inserted contexts from the chain. |
| 303 |
|
| 304 |
Parameters |
| 305 |
---------- |
| 306 |
n: int |
| 307 |
(Default value = None) |
| 308 |
""" |
| 309 |
|
| 310 |
del self.contexts[:n] |
| 311 |
del self.maps[:n] |
| 312 |
self._graph = None |
| 313 |
|
| 314 |
@property |
| 315 |
def defaults(self) -> dict[str, Any]: |
| 316 |
for ctx in self.values(): |
| 317 |
return ctx.defaults |
| 318 |
return {} |
| 319 |
|
| 320 |
@property |
| 321 |
def graph(self): |
| 322 |
"""The graph relating""" |
| 323 |
if self._graph is None: |
| 324 |
self._graph = defaultdict(set) |
| 325 |
for fr_, to_ in self: |
| 326 |
self._graph[fr_].add(to_) |
| 327 |
return self._graph |
| 328 |
|
| 329 |
# TODO: type registry |
| 330 |
def transform( |
| 331 |
self, |
| 332 |
src: UnitsContainer, |
| 333 |
dst: UnitsContainer, |
| 334 |
registry: Any, |
| 335 |
value: Magnitude, |
| 336 |
**ctx_kwargs, |
| 337 |
): |
| 338 |
"""Transform the value, finding the rule in the chained context. |
| 339 |
(A rule in last context will take precedence) |
| 340 |
""" |
| 341 |
return self[(src, dst)].transform(src, dst, registry, value, **ctx_kwargs) |
| 342 |
|
| 343 |
def hashable(self) -> tuple[Any, ...]: |
| 344 |
"""Generate a unique hashable and comparable representation of self, which can |
| 345 |
be used as a key in a dict. This class cannot define ``__hash__`` because it is |
| 346 |
mutable, and the Python interpreter does cache the output of ``__hash__``. |
| 347 |
""" |
| 348 |
return tuple(ctx.hashable() for ctx in self.contexts) |