| 1 |
""" |
| 2 |
pint.facets.context.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 |
import functools |
| 12 |
from collections import ChainMap |
| 13 |
from collections.abc import Callable, Generator |
| 14 |
from contextlib import contextmanager |
| 15 |
from typing import Any, Generic |
| 16 |
|
| 17 |
from ..._typing import F, Magnitude |
| 18 |
from ...compat import TypeAlias |
| 19 |
from ...errors import UndefinedUnitError |
| 20 |
from ...util import UnitsContainer, find_connected_nodes, find_shortest_path, logger |
| 21 |
from ..plain import GenericPlainRegistry, QuantityT, UnitDefinition, UnitT |
| 22 |
from . import objects |
| 23 |
from .definitions import ContextDefinition |
| 24 |
|
| 25 |
# TODO: Put back annotation when possible |
| 26 |
# registry_cache: "RegistryCache" |
| 27 |
|
| 28 |
|
| 29 |
class ContextCacheOverlay: |
| 30 |
"""Layer on top of the plain UnitRegistry cache, specific to a combination of |
| 31 |
active contexts which contain unit redefinitions. |
| 32 |
""" |
| 33 |
|
| 34 |
def __init__(self, registry_cache) -> None: |
| 35 |
self.dimensional_equivalents = registry_cache.dimensional_equivalents |
| 36 |
self.root_units = {} |
| 37 |
self.dimensionality = registry_cache.dimensionality |
| 38 |
self.parse_unit = registry_cache.parse_unit |
| 39 |
self.conversion_factor = {} |
| 40 |
|
| 41 |
|
| 42 |
class GenericContextRegistry( |
| 43 |
Generic[QuantityT, UnitT], GenericPlainRegistry[QuantityT, UnitT] |
| 44 |
): |
| 45 |
"""Handle of Contexts. |
| 46 |
|
| 47 |
Conversion between units with different dimensions according |
| 48 |
to previously established relations (contexts). |
| 49 |
(e.g. in the spectroscopy, conversion between frequency and energy is possible) |
| 50 |
|
| 51 |
Capabilities: |
| 52 |
|
| 53 |
- Register contexts. |
| 54 |
- Enable and disable contexts. |
| 55 |
- Parse @context directive. |
| 56 |
""" |
| 57 |
|
| 58 |
Context: type[objects.Context] = objects.Context |
| 59 |
|
| 60 |
def __init__(self, **kwargs: Any) -> None: |
| 61 |
# Map context name (string) or abbreviation to context. |
| 62 |
self._contexts: dict[str, objects.Context] = {} |
| 63 |
# Stores active contexts. |
| 64 |
self._active_ctx = objects.ContextChain() |
| 65 |
# Map context chain to cache |
| 66 |
self._caches = {} |
| 67 |
# Map context chain to units override |
| 68 |
self._context_units = {} |
| 69 |
|
| 70 |
super().__init__(**kwargs) |
| 71 |
|
| 72 |
# Allow contexts to add override layers to the units |
| 73 |
self._units: ChainMap[str, UnitDefinition] = ChainMap(self._units) |
| 74 |
|
| 75 |
def _register_definition_adders(self) -> None: |
| 76 |
super()._register_definition_adders() |
| 77 |
self._register_adder(ContextDefinition, self.add_context) |
| 78 |
|
| 79 |
def add_context(self, context: objects.Context | ContextDefinition) -> None: |
| 80 |
"""Add a context object to the registry. |
| 81 |
|
| 82 |
The context will be accessible by its name and aliases. |
| 83 |
|
| 84 |
Notice that this method will NOT enable the context; |
| 85 |
see :meth:`enable_contexts`. |
| 86 |
""" |
| 87 |
if isinstance(context, ContextDefinition): |
| 88 |
context = objects.Context.from_definition(context, self.get_dimensionality) |
| 89 |
|
| 90 |
if not context.name: |
| 91 |
raise ValueError("Can't add unnamed context to registry") |
| 92 |
if context.name in self._contexts: |
| 93 |
logger.warning( |
| 94 |
"The name %s was already registered for another context.", context.name |
| 95 |
) |
| 96 |
self._contexts[context.name] = context |
| 97 |
for alias in context.aliases: |
| 98 |
if alias in self._contexts: |
| 99 |
logger.warning( |
| 100 |
"The name %s was already registered for another context", |
| 101 |
context.name, |
| 102 |
) |
| 103 |
self._contexts[alias] = context |
| 104 |
|
| 105 |
def remove_context(self, name_or_alias: str) -> objects.Context: |
| 106 |
"""Remove a context from the registry and return it. |
| 107 |
|
| 108 |
Notice that this methods will not disable the context; |
| 109 |
see :meth:`disable_contexts`. |
| 110 |
""" |
| 111 |
context = self._contexts[name_or_alias] |
| 112 |
|
| 113 |
del self._contexts[context.name] |
| 114 |
for alias in context.aliases: |
| 115 |
del self._contexts[alias] |
| 116 |
|
| 117 |
return context |
| 118 |
|
| 119 |
def _build_cache(self, loaded_files=None) -> None: |
| 120 |
super()._build_cache(loaded_files) |
| 121 |
self._caches[()] = self._cache |
| 122 |
|
| 123 |
def _switch_context_cache_and_units(self) -> None: |
| 124 |
"""If any of the active contexts redefine units, create variant self._cache |
| 125 |
and self._units specific to the combination of active contexts. |
| 126 |
The next time this method is invoked with the same combination of contexts, |
| 127 |
reuse the same variant self._cache and self._units as in the previous time. |
| 128 |
""" |
| 129 |
del self._units.maps[:-1] |
| 130 |
units_overlay = any(ctx.redefinitions for ctx in self._active_ctx.contexts) |
| 131 |
if not units_overlay: |
| 132 |
# Use the default _cache and _units |
| 133 |
self._cache = self._caches[()] |
| 134 |
return |
| 135 |
|
| 136 |
key = self._active_ctx.hashable() |
| 137 |
try: |
| 138 |
self._cache = self._caches[key] |
| 139 |
self._units.maps.insert(0, self._context_units[key]) |
| 140 |
except KeyError: |
| 141 |
pass |
| 142 |
|
| 143 |
# First time using this specific combination of contexts and it contains |
| 144 |
# unit redefinitions |
| 145 |
base_cache = self._caches[()] |
| 146 |
self._caches[key] = self._cache = ContextCacheOverlay(base_cache) |
| 147 |
|
| 148 |
self._context_units[key] = units_overlay = {} |
| 149 |
self._units.maps.insert(0, units_overlay) |
| 150 |
|
| 151 |
on_redefinition_backup = self._on_redefinition |
| 152 |
self._on_redefinition = "ignore" |
| 153 |
try: |
| 154 |
for ctx in reversed(self._active_ctx.contexts): |
| 155 |
for definition in ctx.redefinitions: |
| 156 |
self._redefine(definition) |
| 157 |
finally: |
| 158 |
self._on_redefinition = on_redefinition_backup |
| 159 |
|
| 160 |
def _redefine(self, definition: UnitDefinition) -> None: |
| 161 |
"""Redefine a unit from a context""" |
| 162 |
# Find original definition in the UnitRegistry |
| 163 |
candidates = self.parse_unit_name(definition.name) |
| 164 |
if not candidates: |
| 165 |
raise UndefinedUnitError(definition.name) |
| 166 |
candidates_no_prefix = [c for c in candidates if not c[0]] |
| 167 |
if not candidates_no_prefix: |
| 168 |
raise ValueError(f"Can't redefine a unit with a prefix: {definition.name}") |
| 169 |
assert len(candidates_no_prefix) == 1 |
| 170 |
_, name, _ = candidates_no_prefix[0] |
| 171 |
try: |
| 172 |
basedef = self._units[name] |
| 173 |
except KeyError: |
| 174 |
raise UndefinedUnitError(name) |
| 175 |
|
| 176 |
# Rebuild definition as a variant of the plain |
| 177 |
if basedef.is_base: |
| 178 |
raise ValueError("Can't redefine a plain unit to a derived one") |
| 179 |
|
| 180 |
dims_old = self._get_dimensionality(basedef.reference) |
| 181 |
dims_new = self._get_dimensionality(definition.reference) |
| 182 |
if dims_old != dims_new: |
| 183 |
raise ValueError( |
| 184 |
f"Can't change dimensionality of {basedef.name} " |
| 185 |
f"from {dims_old} to {dims_new} in a context" |
| 186 |
) |
| 187 |
|
| 188 |
# Do not modify in place the original definition, as (1) the context may |
| 189 |
# be shared by other registries, and (2) it would alter the cache key |
| 190 |
definition = UnitDefinition( |
| 191 |
name=basedef.name, |
| 192 |
defined_symbol=basedef.symbol, |
| 193 |
aliases=basedef.aliases, |
| 194 |
reference=definition.reference, |
| 195 |
converter=definition.converter, |
| 196 |
) |
| 197 |
|
| 198 |
# Write into the context-specific self._units.maps[0] and self._cache.root_units |
| 199 |
self.define(definition) |
| 200 |
|
| 201 |
def enable_contexts( |
| 202 |
self, *names_or_contexts: str | objects.Context, **kwargs: Any |
| 203 |
) -> None: |
| 204 |
"""Enable contexts provided by name or by object. |
| 205 |
|
| 206 |
Parameters |
| 207 |
---------- |
| 208 |
*names_or_contexts : |
| 209 |
one or more contexts or context names/aliases |
| 210 |
**kwargs : |
| 211 |
keyword arguments for the context(s) |
| 212 |
|
| 213 |
Examples |
| 214 |
-------- |
| 215 |
See :meth:`context` |
| 216 |
""" |
| 217 |
|
| 218 |
# If present, copy the defaults from the containing contexts |
| 219 |
if self._active_ctx.defaults: |
| 220 |
kwargs = dict(self._active_ctx.defaults, **kwargs) |
| 221 |
|
| 222 |
# For each name, we first find the corresponding context |
| 223 |
ctxs = [ |
| 224 |
self._contexts[name] if isinstance(name, str) else name |
| 225 |
for name in names_or_contexts |
| 226 |
] |
| 227 |
|
| 228 |
# Check if the contexts have been checked first, if not we make sure |
| 229 |
# that dimensions are expressed in terms of plain dimensions. |
| 230 |
for ctx in ctxs: |
| 231 |
if ctx.checked: |
| 232 |
continue |
| 233 |
funcs_copy = dict(ctx.funcs) |
| 234 |
for (src, dst), func in funcs_copy.items(): |
| 235 |
src_ = self._get_dimensionality(src) |
| 236 |
dst_ = self._get_dimensionality(dst) |
| 237 |
if src != src_ or dst != dst_: |
| 238 |
ctx.remove_transformation(src, dst) |
| 239 |
ctx.add_transformation(src_, dst_, func) |
| 240 |
ctx.checked = True |
| 241 |
|
| 242 |
# and create a new one with the new defaults. |
| 243 |
contexts = tuple(objects.Context.from_context(ctx, **kwargs) for ctx in ctxs) |
| 244 |
|
| 245 |
# Finally we add them to the active context. |
| 246 |
self._active_ctx.insert_contexts(*contexts) |
| 247 |
self._switch_context_cache_and_units() |
| 248 |
|
| 249 |
def disable_contexts(self, n: int | None = None) -> None: |
| 250 |
"""Disable the last n enabled contexts. |
| 251 |
|
| 252 |
Parameters |
| 253 |
---------- |
| 254 |
n : int |
| 255 |
Number of contexts to disable. Default: disable all contexts. |
| 256 |
""" |
| 257 |
self._active_ctx.remove_contexts(n) |
| 258 |
self._switch_context_cache_and_units() |
| 259 |
|
| 260 |
@contextmanager |
| 261 |
def context( |
| 262 |
self: GenericContextRegistry[QuantityT, UnitT], *names: str, **kwargs: Any |
| 263 |
) -> Generator[GenericContextRegistry[QuantityT, UnitT]]: |
| 264 |
"""Used as a context manager, this function enables to activate a context |
| 265 |
which is removed after usage. |
| 266 |
|
| 267 |
Parameters |
| 268 |
---------- |
| 269 |
*names : name(s) of the context(s). |
| 270 |
**kwargs : keyword arguments for the contexts. |
| 271 |
|
| 272 |
Examples |
| 273 |
-------- |
| 274 |
Context can be called by their name: |
| 275 |
|
| 276 |
>>> import pint.facets.context.objects |
| 277 |
>>> import pint |
| 278 |
>>> ureg = pint.UnitRegistry() |
| 279 |
>>> ureg.add_context(pint.facets.context.objects.Context("one")) |
| 280 |
>>> ureg.add_context(pint.facets.context.objects.Context("two")) |
| 281 |
>>> with ureg.context("one"): |
| 282 |
... pass |
| 283 |
|
| 284 |
If a context has an argument, you can specify its value as a keyword argument: |
| 285 |
|
| 286 |
>>> with ureg.context("one", n=1): |
| 287 |
... pass |
| 288 |
|
| 289 |
Multiple contexts can be entered in single call: |
| 290 |
|
| 291 |
>>> with ureg.context("one", "two", n=1): |
| 292 |
... pass |
| 293 |
|
| 294 |
Or nested allowing you to give different values to the same keyword argument: |
| 295 |
|
| 296 |
>>> with ureg.context("one", n=1): |
| 297 |
... with ureg.context("two", n=2): |
| 298 |
... pass |
| 299 |
|
| 300 |
A nested context inherits the defaults from the containing context: |
| 301 |
|
| 302 |
>>> with ureg.context("one", n=1): |
| 303 |
... # Here n takes the value of the outer context |
| 304 |
... with ureg.context("two"): |
| 305 |
... pass |
| 306 |
""" |
| 307 |
# Enable the contexts. |
| 308 |
self.enable_contexts(*names, **kwargs) |
| 309 |
|
| 310 |
try: |
| 311 |
# After adding the context and rebuilding the graph, the registry |
| 312 |
# is ready to use. |
| 313 |
yield self |
| 314 |
finally: |
| 315 |
# Upon leaving the with statement, |
| 316 |
# the added contexts are removed from the active one. |
| 317 |
self.disable_contexts(len(names)) |
| 318 |
|
| 319 |
def with_context(self, name: str, **kwargs: Any) -> Callable[[F], F]: |
| 320 |
"""Decorator to wrap a function call in a Pint context. |
| 321 |
|
| 322 |
Use it to ensure that a certain context is active when |
| 323 |
calling a function. |
| 324 |
|
| 325 |
Parameters |
| 326 |
---------- |
| 327 |
name : |
| 328 |
name of the context. |
| 329 |
**kwargs : |
| 330 |
keyword arguments for the context |
| 331 |
|
| 332 |
|
| 333 |
Returns |
| 334 |
------- |
| 335 |
callable: the wrapped function. |
| 336 |
|
| 337 |
Examples |
| 338 |
-------- |
| 339 |
>>> @ureg.with_context("sp") |
| 340 |
... def my_cool_fun(wavelength): |
| 341 |
... print( |
| 342 |
... "This wavelength is equivalent to: %s", wavelength.to("terahertz") |
| 343 |
... ) |
| 344 |
""" |
| 345 |
|
| 346 |
def decorator(func): |
| 347 |
assigned = tuple( |
| 348 |
attr for attr in functools.WRAPPER_ASSIGNMENTS if hasattr(func, attr) |
| 349 |
) |
| 350 |
updated = tuple( |
| 351 |
attr for attr in functools.WRAPPER_UPDATES if hasattr(func, attr) |
| 352 |
) |
| 353 |
|
| 354 |
@functools.wraps(func, assigned=assigned, updated=updated) |
| 355 |
def wrapper(*values, **wrapper_kwargs): |
| 356 |
with self.context(name, **kwargs): |
| 357 |
return func(*values, **wrapper_kwargs) |
| 358 |
|
| 359 |
return wrapper |
| 360 |
|
| 361 |
return decorator |
| 362 |
|
| 363 |
def _convert( |
| 364 |
self, |
| 365 |
value: Magnitude, |
| 366 |
src: UnitsContainer, |
| 367 |
dst: UnitsContainer, |
| 368 |
inplace: bool = False, |
| 369 |
**ctx_kwargs, |
| 370 |
) -> Magnitude: |
| 371 |
"""Convert value from some source to destination units. |
| 372 |
|
| 373 |
In addition to what is done by the PlainRegistry, |
| 374 |
converts between units with different dimensions by following |
| 375 |
transformation rules defined in the context. |
| 376 |
|
| 377 |
Parameters |
| 378 |
---------- |
| 379 |
value : |
| 380 |
value |
| 381 |
src : UnitsContainer |
| 382 |
source units. |
| 383 |
dst : UnitsContainer |
| 384 |
destination units. |
| 385 |
inplace : |
| 386 |
(Default value = False) |
| 387 |
**ctx_kwargs : |
| 388 |
keyword arguments for the context |
| 389 |
|
| 390 |
Returns |
| 391 |
------- |
| 392 |
callable |
| 393 |
converted value |
| 394 |
""" |
| 395 |
# If there is an active context, we look for a path connecting source and |
| 396 |
# destination dimensionality. If it exists, we transform the source value |
| 397 |
# by applying sequentially each transformation of the path. |
| 398 |
if self._active_ctx: |
| 399 |
src_dim = self._get_dimensionality(src) |
| 400 |
dst_dim = self._get_dimensionality(dst) |
| 401 |
|
| 402 |
path = find_shortest_path(self._active_ctx.graph, src_dim, dst_dim) |
| 403 |
if path: |
| 404 |
src = self.Quantity(value, src) |
| 405 |
for a, b in zip(path[:-1], path[1:]): |
| 406 |
src = self._active_ctx.transform(a, b, self, src, **ctx_kwargs) |
| 407 |
|
| 408 |
value, src = src._magnitude, src._units |
| 409 |
|
| 410 |
return super()._convert(value, src, dst, inplace, **ctx_kwargs) |
| 411 |
|
| 412 |
def _get_compatible_units( |
| 413 |
self, input_units: UnitsContainer, group_or_system: str | None = None |
| 414 |
): |
| 415 |
src_dim = self._get_dimensionality(input_units) |
| 416 |
|
| 417 |
ret = super()._get_compatible_units(input_units, group_or_system) |
| 418 |
|
| 419 |
if self._active_ctx: |
| 420 |
ret = ret.copy() # Do not alter self._cache |
| 421 |
nodes = find_connected_nodes(self._active_ctx.graph, src_dim) |
| 422 |
if nodes: |
| 423 |
for node in nodes: |
| 424 |
ret |= self._cache.dimensional_equivalents[node] |
| 425 |
|
| 426 |
return ret |
| 427 |
|
| 428 |
|
| 429 |
class ContextRegistry( |
| 430 |
GenericContextRegistry[objects.ContextQuantity, objects.ContextUnit] |
| 431 |
): |
| 432 |
Quantity: TypeAlias = objects.ContextQuantity |
| 433 |
Unit: TypeAlias = objects.ContextUnit |