Debian Codegraph @

pint/facets/plain/registry.py

raw
1 """
2 pint.facets.plain.registry
3 ~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 :copyright: 2022 by Pint Authors, see AUTHORS for more details.
6 :license: BSD, see LICENSE for more details.
7
8 The registry contains the following important methods:
9
10 - parse_unit_name: Parse a unit to identify prefix, unit name and suffix
11 by walking the list of prefix and suffix.
12 Result is cached: NO
13 - parse_units: Parse a units expression and returns a UnitContainer with
14 the canonical names.
15 The expression can only contain products, ratios and powers of units;
16 prefixed units and pluralized units.
17 Result is cached: YES
18 - parse_expression: Parse a mathematical expression including units and
19 return a quantity object.
20 Result is cached: NO
21
22 """
23
24 from __future__ import annotations
25
26 import copy
27 import functools
28 import inspect
29 import itertools
30 import pathlib
31 import re
32 from collections import defaultdict
33 from collections.abc import Callable, Generator, Iterable, Iterator
34 from decimal import Decimal
35 from fractions import Fraction
36 from math import isnan
37 from token import NAME, NUMBER
38 from tokenize import TokenInfo
39 from typing import (
40 TYPE_CHECKING,
41 Any,
42 Generic,
43 TypeVar,
44 Union,
45 )
46
47 if TYPE_CHECKING:
48 from ...compat import Locale
49 from ..context import Context
50
51 # from ..._typing import Quantity, Unit
52
53 import platformdirs
54
55 from ... import pint_eval
56 from ..._typing import (
57 Handler,
58 QuantityArgument,
59 QuantityOrUnitLike,
60 Scalar,
61 UnitLike,
62 )
63 from ...compat import Self, TypeAlias, deprecated
64 from ...errors import (
65 DimensionalityError,
66 OffsetUnitCalculusError,
67 RedefinitionError,
68 UndefinedUnitError,
69 )
70 from ...pint_eval import build_eval_tree
71 from ...util import (
72 ParserHelper,
73 _is_dim,
74 create_class_with_registry,
75 getattr_maybe_raise,
76 logger,
77 solve_dependencies,
78 string_preprocessor,
79 to_units_container,
80 )
81 from ...util import UnitsContainer as UnitsContainer
82 from .definitions import (
83 AliasDefinition,
84 CommentDefinition,
85 DefaultsDefinition,
86 DerivedDimensionDefinition,
87 DimensionDefinition,
88 NamedDefinition,
89 PrefixDefinition,
90 UnitDefinition,
91 )
92 from .objects import PlainQuantity, PlainUnit
93
94 T = TypeVar("T")
95
96 _BLOCK_RE = re.compile(r"[ (]")
97
98
99 @functools.lru_cache
100 def pattern_to_regex(pattern: str | re.Pattern[str]) -> re.Pattern[str]:
101 # TODO: This has been changed during typing improvements.
102 # if hasattr(pattern, "finditer"):
103 if not isinstance(pattern, str):
104 pattern = pattern.pattern
105
106 # Replace "{unit_name}" match string with float regex with unit_name as group
107 pattern = re.sub(
108 r"{(\w+)}", r"(?P<\1>[+-]?[0-9]+(?:.[0-9]+)?(?:[Ee][+-]?[0-9]+)?)", pattern
109 )
110
111 return re.compile(pattern)
112
113
114 NON_INT_TYPE = type[Union[float, Decimal, Fraction]]
115 PreprocessorType = Callable[[str], str]
116
117
118 class RegistryCache:
119 """Cache to speed up unit registries"""
120
121 def __init__(self) -> None:
122 #: Maps dimensionality (UnitsContainer) to Units (str)
123 self.dimensional_equivalents: dict[UnitsContainer, frozenset[str]] = {}
124
125 #: Maps dimensionality (UnitsContainer) to Dimensionality (UnitsContainer)
126 # TODO: this description is not right.
127 self.root_units: dict[UnitsContainer, tuple[Scalar, UnitsContainer]] = {}
128
129 #: Maps dimensionality (UnitsContainer) to Units (UnitsContainer)
130 self.dimensionality: dict[UnitsContainer, UnitsContainer] = {}
131
132 #: Cache the unit name associated to user input. ('mV' -> 'millivolt')
133 self.parse_unit: dict[str, UnitsContainer] = {}
134
135 self.conversion_factor: dict[
136 tuple[UnitsContainer, UnitsContainer], Scalar | DimensionalityError
137 ] = {}
138
139 def __eq__(self, other: Any):
140 if not isinstance(other, self.__class__):
141 return False
142 attrs = (
143 "dimensional_equivalents",
144 "root_units",
145 "dimensionality",
146 "parse_unit",
147 "conversion_factor",
148 )
149 return all(getattr(self, attr) == getattr(other, attr) for attr in attrs)
150
151
152 class RegistryMeta(type):
153 """This is just to call after_init at the right time
154 instead of asking the developer to do it when subclassing.
155 """
156
157 def __call__(self, *args: Any, **kwargs: Any):
158 obj = super().__call__(*args, **kwargs)
159 obj._after_init()
160 return obj
161
162
163 # Generic types used to mark types associated to Registries.
164 QuantityT = TypeVar("QuantityT", bound=PlainQuantity)
165 UnitT = TypeVar("UnitT", bound=PlainUnit)
166
167
168 class GenericPlainRegistry(Generic[QuantityT, UnitT], metaclass=RegistryMeta):
169 """Base class for all registries.
170
171 Capabilities:
172
173 - Register units, prefixes, and dimensions, and their relations.
174 - Convert between units.
175 - Find dimensionality of a unit.
176 - Parse units with prefix and/or suffix.
177 - Parse expressions.
178 - Parse a definition file.
179 - Allow extending the definition file parser by registering @ directives.
180
181 Parameters
182 ----------
183 filename : str or None
184 path of the units definition file to load or line iterable object. Empty to load
185 the default definition file. None to leave the UnitRegistry empty.
186 force_ndarray : bool
187 convert any input, scalar or not to a numpy.ndarray.
188 force_ndarray_like : bool
189 convert all inputs other than duck arrays to a numpy.ndarray.
190 on_redefinition : str
191 action to take in case a unit is redefined: 'warn', 'raise', 'ignore'
192 auto_reduce_dimensions :
193 If True, reduce dimensionality on appropriate operations.
194 autoconvert_to_preferred :
195 If True, converts preferred units on appropriate operations.
196 preprocessors :
197 list of callables which are iteratively ran on any input expression or unit
198 string
199 fmt_locale :
200 locale identifier string, used in `format_babel`
201 non_int_type : type
202 numerical type used for non integer values. (Default: float)
203 case_sensitive : bool, optional
204 Control default case sensitivity of unit parsing. (Default: True)
205 cache_folder : str or pathlib.Path or None, optional
206 Specify the folder in which cache files are saved and loaded from.
207 If None, the cache is disabled. (default)
208 separate_format_defaults : bool, optional
209 Separate the default format into magnitude and unit formats as soon as
210 possible. The deprecated default is not to separate. This will change in a
211 future release.
212 """
213
214 Quantity: type[QuantityT]
215 Unit: type[UnitT]
216
217 _diskcache = None
218 _def_parser = None
219
220 def __init__(
221 self,
222 filename="",
223 force_ndarray: bool = False,
224 force_ndarray_like: bool = False,
225 on_redefinition: str = "warn",
226 auto_reduce_dimensions: bool = False,
227 autoconvert_to_preferred: bool = False,
228 preprocessors: list[PreprocessorType] | None = None,
229 fmt_locale: str | None = None,
230 non_int_type: NON_INT_TYPE = float,
231 case_sensitive: bool = True,
232 cache_folder: str | pathlib.Path | None = None,
233 separate_format_defaults: bool | None = None,
234 mpl_formatter: str = "{:P}",
235 ):
236 #: Map a definition class to a adder methods.
237 self._adders: Handler = {}
238 self._register_definition_adders()
239 self._init_dynamic_classes()
240
241 if cache_folder == ":auto:":
242 cache_folder = platformdirs.user_cache_path(appname="pint", appauthor=False)
243
244 from ... import delegates # TODO: change this
245
246 if cache_folder is not None:
247 self._diskcache = delegates.build_disk_cache_class(non_int_type)(
248 cache_folder
249 )
250
251 self._def_parser = delegates.txt_defparser.DefParser(
252 delegates.ParserConfig(non_int_type), diskcache=self._diskcache
253 )
254
255 self.formatter = delegates.Formatter(self)
256 self._filename = filename
257 self.force_ndarray = force_ndarray
258 self.force_ndarray_like = force_ndarray_like
259 self.preprocessors = preprocessors or []
260 # use a default preprocessor to support "%"
261 self.preprocessors.insert(0, lambda string: string.replace("%", " percent "))
262
263 # use a default preprocessor to support permille "‰"
264 self.preprocessors.insert(0, lambda string: string.replace("‰", " permille "))
265
266 # use a default preprocessor to support multiplication sign "×"
267 self.preprocessors.insert(0, lambda string: string.replace("×", "*"))
268
269 #: mode used to fill in the format defaults
270 self.separate_format_defaults = separate_format_defaults
271
272 #: Action to take in case a unit is redefined. 'warn', 'raise', 'ignore'
273 self._on_redefinition = on_redefinition
274
275 #: Determines if dimensionality should be reduced on appropriate operations.
276 self.auto_reduce_dimensions = auto_reduce_dimensions
277
278 #: Determines if units will be converted to preffered on appropriate operations.
279 self.autoconvert_to_preferred = autoconvert_to_preferred
280
281 #: Default locale identifier string, used when calling format_babel without explicit locale.
282 self.formatter.set_locale(fmt_locale)
283
284 #: sets the formatter used when plotting with matplotlib
285 self.mpl_formatter = mpl_formatter
286
287 #: Numerical type used for non integer values.
288 self._non_int_type = non_int_type
289
290 #: Default unit case sensitivity
291 self.case_sensitive = case_sensitive
292
293 #: Map between name (string) and value (string) of defaults stored in the
294 #: definitions file.
295 self._defaults: dict[str, str] = {}
296
297 #: Map dimension name (string) to its definition (DimensionDefinition).
298 self._dimensions: dict[
299 str, DimensionDefinition | DerivedDimensionDefinition
300 ] = {}
301
302 #: Map unit name (string) to its definition (UnitDefinition).
303 #: Might contain prefixed units.
304 self._units: dict[str, UnitDefinition] = {}
305
306 #: List base unit names
307 self._base_units: list[str] = []
308
309 #: Map unit name in lower case (string) to a set of unit names with the right
310 #: case.
311 #: Does not contain prefixed units.
312 #: e.g: 'hz' - > set('Hz', )
313 self._units_casei: dict[str, set[str]] = defaultdict(set)
314
315 #: Map prefix name (string) to its definition (PrefixDefinition).
316 self._prefixes: dict[str, PrefixDefinition] = {"": PrefixDefinition("", 1)}
317
318 #: Map suffix name (string) to canonical , and unit alias to canonical unit name
319 self._suffixes: dict[str, str] = {"": "", "s": ""}
320
321 #: Map contexts to RegistryCache
322 self._cache = RegistryCache()
323
324 self._initialized = False
325
326 def _init_dynamic_classes(self) -> None:
327 """Generate subclasses on the fly and attach them to self"""
328
329 self.Unit = create_class_with_registry(self, self.Unit)
330 self.Quantity = create_class_with_registry(self, self.Quantity)
331
332 def _after_init(self) -> None:
333 """This should be called after all __init__"""
334
335 if self._filename == "":
336 path = pathlib.Path(__file__).parent.parent.parent / "default_en.txt"
337 loaded_files = self.load_definitions(path, True)
338 elif self._filename is not None:
339 loaded_files = self.load_definitions(self._filename)
340 else:
341 loaded_files = None
342
343 self._build_cache(loaded_files)
344 self._initialized = True
345
346 def _register_adder(
347 self,
348 definition_class: type[T],
349 adder_func: Callable[
350 [
351 T,
352 ],
353 None,
354 ],
355 ) -> None:
356 """Register a block definition."""
357 self._adders[definition_class] = adder_func
358
359 def _register_definition_adders(self) -> None:
360 self._register_adder(AliasDefinition, self._add_alias)
361 self._register_adder(DefaultsDefinition, self._add_defaults)
362 self._register_adder(CommentDefinition, lambda o: o)
363 self._register_adder(PrefixDefinition, self._add_prefix)
364 self._register_adder(UnitDefinition, self._add_unit)
365 self._register_adder(DimensionDefinition, self._add_dimension)
366 self._register_adder(DerivedDimensionDefinition, self._add_derived_dimension)
367
368 def __deepcopy__(self: Self, memo) -> type[Self]:
369 new = object.__new__(type(self))
370 new.__dict__ = copy.deepcopy(self.__dict__, memo)
371 new._init_dynamic_classes()
372 return new
373
374 def __getattr__(self, item: str) -> UnitT:
375 getattr_maybe_raise(self, item)
376
377 # self.Unit will call parse_units
378 return self.Unit(item)
379
380 @deprecated(
381 "Calling the getitem method from a UnitRegistry will be removed in future versions of pint.\n"
382 "use `parse_expression` method or use the registry as a callable."
383 )
384 def __getitem__(self, item: str) -> UnitT:
385 return self.parse_expression(item)
386
387 def __contains__(self, item: str) -> bool:
388 """Support checking prefixed units with the `in` operator"""
389 try:
390 self.__getattr__(item)
391 return True
392 except UndefinedUnitError:
393 return False
394
395 def __dir__(self) -> list[str]:
396 #: Calling dir(registry) gives all units, methods, and attributes.
397 #: Also used for autocompletion in IPython.
398 return list(self._units.keys()) + list(object.__dir__(self))
399
400 def __iter__(self) -> Iterator[str]:
401 """Allows for listing all units in registry with `list(ureg)`.
402
403 Returns
404 -------
405 Iterator over names of all units in registry, ordered alphabetically.
406 """
407 return iter(sorted(self._units.keys()))
408
409 @property
410 @deprecated(
411 "This function will be removed in future versions of pint.\n"
412 "Use ureg.formatter.fmt_locale"
413 )
414 def fmt_locale(self) -> Locale | None:
415 return self.formatter.locale
416
417 @fmt_locale.setter
418 @deprecated(
419 "This function will be removed in future versions of pint.\n"
420 "Use ureg.formatter.set_locale"
421 )
422 def fmt_locale(self, loc: str | None):
423 self.formatter.set_locale(loc)
424
425 @deprecated(
426 "This function will be removed in future versions of pint.\n"
427 "Use ureg.formatter.set_locale"
428 )
429 def set_fmt_locale(self, loc: str | None) -> None:
430 """Change the locale used by default by `format_babel`.
431
432 Parameters
433 ----------
434 loc : str or None
435 None` (do not translate), 'sys' (detect the system locale) or a locale id string.
436 """
437
438 self.formatter.set_locale(loc)
439
440 @property
441 @deprecated(
442 "This function will be removed in future versions of pint.\n"
443 "Use ureg.formatter.default_format"
444 )
445 def default_format(self) -> str:
446 """Default formatting string for quantities."""
447 return self.formatter.default_format
448
449 @default_format.setter
450 @deprecated(
451 "This function will be removed in future versions of pint.\n"
452 "Use ureg.formatter.default_format"
453 )
454 def default_format(self, value: str) -> None:
455 self.formatter.default_format = value
456
457 @property
458 def cache_folder(self) -> pathlib.Path | None:
459 if self._diskcache:
460 return self._diskcache.cache_folder
461 return None
462
463 @property
464 def non_int_type(self):
465 return self._non_int_type
466
467 def define(self, definition: str | type) -> None:
468 """Add unit to the registry.
469
470 Parameters
471 ----------
472 definition : str or Definition
473 a dimension, unit or prefix definition.
474 """
475
476 if isinstance(definition, str):
477 parsed_project = self._def_parser.parse_string(definition)
478
479 for definition in self._def_parser.iter_parsed_project(parsed_project):
480 self._helper_dispatch_adder(definition)
481 else:
482 self._helper_dispatch_adder(definition)
483
484 ############
485 # Adders
486 # - we first provide some helpers that deal with repetitive task.
487 # - then we define specific adder for each definition class. :-D
488 ############
489
490 def _helper_dispatch_adder(self, definition: Any) -> None:
491 """Helper function to add a single definition,
492 choosing the appropiate method by class.
493 """
494 for cls in inspect.getmro(definition.__class__):
495 if cls in self._adders:
496 adder_func = self._adders[cls]
497 break
498 else:
499 raise TypeError(
500 f"No loader function defined for {definition.__class__.__name__}"
501 )
502
503 adder_func(definition)
504
505 def _helper_adder(
506 self,
507 definition: NamedDefinition,
508 target_dict: dict[str, Any],
509 casei_target_dict: dict[str, Any] | None,
510 ) -> None:
511 """Helper function to store a definition in the internal dictionaries.
512 It stores the definition under its name, symbol and aliases.
513 """
514 self._helper_single_adder(
515 definition.name, definition, target_dict, casei_target_dict
516 )
517
518 # TODO: Not sure why but using hasattr does not work here.
519 if getattr(definition, "has_symbol", ""):
520 self._helper_single_adder(
521 definition.symbol, definition, target_dict, casei_target_dict
522 )
523
524 for alias in getattr(definition, "aliases", ()):
525 if " " in alias:
526 logger.warn("Alias cannot contain a space: " + alias)
527
528 self._helper_single_adder(alias, definition, target_dict, casei_target_dict)
529
530 def _helper_single_adder(
531 self,
532 key: str,
533 value: NamedDefinition,
534 target_dict: dict[str, Any],
535 casei_target_dict: dict[str, Any] | None,
536 ) -> None:
537 """Helper function to store a definition in the internal dictionaries.
538
539 It warns or raise error on redefinition.
540 """
541 if key in target_dict:
542 if self._on_redefinition == "raise":
543 raise RedefinitionError(key, type(value))
544 elif self._on_redefinition == "warn":
545 logger.warning(f"Redefining '{key}' ({type(value)})")
546
547 target_dict[key] = value
548 if casei_target_dict is not None:
549 casei_target_dict[key.lower()].add(key)
550
551 def _add_defaults(self, defaults_definition: DefaultsDefinition) -> None:
552 for k, v in defaults_definition.items():
553 self._defaults[k] = v
554
555 def _add_alias(self, definition: AliasDefinition) -> None:
556 unit_dict = self._units
557 unit = unit_dict[definition.name]
558 while not isinstance(unit, UnitDefinition):
559 unit = unit_dict[unit.name]
560 for alias in definition.aliases:
561 self._helper_single_adder(alias, unit, self._units, self._units_casei)
562
563 def _add_dimension(self, definition: DimensionDefinition) -> None:
564 self._helper_adder(definition, self._dimensions, None)
565
566 def _add_derived_dimension(self, definition: DerivedDimensionDefinition) -> None:
567 for dim_name in definition.reference.keys():
568 if dim_name not in self._dimensions:
569 self._add_dimension(DimensionDefinition(dim_name))
570 self._helper_adder(definition, self._dimensions, None)
571
572 def _add_prefix(self, definition: PrefixDefinition) -> None:
573 self._helper_adder(definition, self._prefixes, None)
574
575 def _add_unit(self, definition: UnitDefinition) -> None:
576 if definition.is_base:
577 self._base_units.append(definition.name)
578 for dim_name in definition.reference.keys():
579 if dim_name not in self._dimensions:
580 self._add_dimension(DimensionDefinition(dim_name))
581
582 self._helper_adder(definition, self._units, self._units_casei)
583
584 def load_definitions(
585 self, file: Iterable[str] | str | pathlib.Path, is_resource: bool = False
586 ):
587 """Add units and prefixes defined in a definition text file.
588
589 Parameters
590 ----------
591 file :
592 can be a filename or a line iterable.
593 is_resource :
594 used to indicate that the file is a resource file
595 and therefore should be loaded from the package. (Default value = False)
596 """
597
598 if isinstance(file, (list, tuple)):
599 # TODO: this hack was to keep it backwards compatible.
600 parsed_project = self._def_parser.parse_string("\n".join(file))
601 else:
602 parsed_project = self._def_parser.parse_file(file)
603
604 for definition in self._def_parser.iter_parsed_project(parsed_project):
605 self._helper_dispatch_adder(definition)
606
607 return parsed_project
608
609 def _build_cache(self, loaded_files=None) -> None:
610 """Build a cache of dimensionality and plain units."""
611
612 diskcache = self._diskcache
613 if loaded_files and diskcache:
614 cache, cache_basename = diskcache.load(loaded_files, "build_cache")
615 if cache is None:
616 self._build_cache()
617 diskcache.save(self._cache, loaded_files, "build_cache")
618 return
619
620 self._cache = RegistryCache()
621
622 deps: dict[str, set[str]] = {
623 name: set(definition.reference.keys()) if definition.reference else set()
624 for name, definition in self._units.items()
625 }
626
627 for unit_names in solve_dependencies(deps):
628 for unit_name in unit_names:
629 if "[" in unit_name:
630 continue
631 parsed_names = self.parse_unit_name(unit_name)
632 if parsed_names:
633 prefix, base_name, _ = parsed_names[0]
634 else:
635 prefix, base_name = "", unit_name
636
637 try:
638 uc = ParserHelper.from_word(base_name, self.non_int_type)
639
640 bu = self._get_root_units(uc)
641 di = self._get_dimensionality(uc)
642
643 self._cache.root_units[uc] = bu
644 self._cache.dimensionality[uc] = di
645
646 if not prefix:
647 dimeq_set = self._cache.dimensional_equivalents.setdefault(
648 di, set()
649 )
650 dimeq_set.add(self._units[base_name].name)
651
652 except Exception as exc:
653 logger.warning(f"Could not resolve {unit_name}: {exc!r}")
654 return self._cache
655
656 def get_name(self, name_or_alias: str, case_sensitive: bool | None = None) -> str:
657 """Return the canonical name of a unit."""
658
659 if name_or_alias == "dimensionless":
660 return ""
661
662 try:
663 return self._units[name_or_alias].name
664 except KeyError:
665 pass
666
667 candidates = self.parse_unit_name(name_or_alias, case_sensitive)
668 if not candidates:
669 raise UndefinedUnitError(name_or_alias)
670
671 prefix, unit_name, _ = candidates[0]
672 if len(candidates) > 1:
673 logger.warning(
674 f"Parsing {name_or_alias} yield multiple results. Options are: {candidates!r}"
675 )
676
677 if prefix:
678 if not self._units[unit_name].is_multiplicative:
679 raise OffsetUnitCalculusError(
680 "Prefixing a unit requires multiplying the unit."
681 )
682
683 name = prefix + unit_name
684 symbol = self.get_symbol(name, case_sensitive)
685 prefix_def = self._prefixes[prefix]
686 self._units[name] = UnitDefinition(
687 name,
688 symbol,
689 tuple(),
690 prefix_def.converter,
691 self.UnitsContainer({unit_name: 1}),
692 )
693 return prefix + unit_name
694
695 return unit_name
696
697 def get_symbol(self, name_or_alias: str, case_sensitive: bool | None = None) -> str:
698 """Return the preferred alias for a unit."""
699 candidates = self.parse_unit_name(name_or_alias, case_sensitive)
700 if not candidates:
701 raise UndefinedUnitError(name_or_alias)
702
703 prefix, unit_name, _ = candidates[0]
704 if len(candidates) > 1:
705 logger.warning(
706 f"Parsing {name_or_alias} yield multiple results. Options are: {candidates!r}"
707 )
708
709 return self._prefixes[prefix].symbol + self._units[unit_name].symbol
710
711 def _get_symbol(self, name: str) -> str:
712 return self._units[name].symbol
713
714 def get_dimensionality(self, input_units: UnitLike) -> UnitsContainer:
715 """Convert unit or dict of units or dimensions to a dict of plain dimensions
716 dimensions
717 """
718
719 # TODO: This should be to_units_container(input_units, self)
720 # but this tries to reparse and fail for dimensions.
721 input_units = to_units_container(input_units)
722
723 return self._get_dimensionality(input_units)
724
725 def _get_dimensionality(self, input_units: UnitsContainer | None) -> UnitsContainer:
726 """Convert a UnitsContainer to plain dimensions."""
727 if not input_units:
728 return self.UnitsContainer()
729
730 cache = self._cache.dimensionality
731
732 try:
733 return cache[input_units]
734 except KeyError:
735 pass
736
737 accumulator: dict[str, int] = defaultdict(int)
738 self._get_dimensionality_recurse(input_units, 1, accumulator)
739
740 if "[]" in accumulator:
741 del accumulator["[]"]
742
743 dims = self.UnitsContainer({k: v for k, v in accumulator.items() if v != 0})
744
745 cache[input_units] = dims
746
747 return dims
748
749 def _get_dimensionality_recurse(
750 self, ref: UnitsContainer, exp: Scalar, accumulator: dict[str, int]
751 ) -> None:
752 for key in ref:
753 exp2 = exp * ref[key]
754 if _is_dim(key):
755 try:
756 reg = self._dimensions[key]
757 except KeyError:
758 raise ValueError(
759 f"{key} is not defined as dimension in the pint UnitRegistry"
760 )
761 if isinstance(reg, DerivedDimensionDefinition):
762 self._get_dimensionality_recurse(reg.reference, exp2, accumulator)
763 else:
764 # DimensionDefinition.
765 accumulator[key] += exp2
766
767 else:
768 reg = self._units[self.get_name(key)]
769 if reg.reference is not None:
770 self._get_dimensionality_recurse(reg.reference, exp2, accumulator)
771
772 def _get_dimensionality_ratio(
773 self, unit1: UnitLike, unit2: UnitLike
774 ) -> Scalar | None:
775 """Get the exponential ratio between two units, i.e. solve unit2 = unit1**x for x.
776
777 Parameters
778 ----------
779 unit1 : UnitsContainer compatible (str, Unit, UnitsContainer, dict)
780 first unit
781 unit2 : UnitsContainer compatible (str, Unit, UnitsContainer, dict)
782 second unit
783
784 Returns
785 -------
786 number or None
787 exponential proportionality or None if the units cannot be converted
788
789 """
790 # shortcut in case of equal units
791 if unit1 == unit2:
792 return 1
793
794 dim1, dim2 = (self.get_dimensionality(unit) for unit in (unit1, unit2))
795 if dim1 == dim2:
796 return 1
797 elif not dim1 or not dim2 or dim1.keys() != dim2.keys(): # not comparable
798 return None
799
800 ratios = (dim2[key] / val for key, val in dim1.items())
801 first = next(ratios)
802 if all(r == first for r in ratios): # all are same, we're good
803 return first
804 return None
805
806 def get_root_units(
807 self, input_units: UnitLike, check_nonmult: bool = True
808 ) -> tuple[Scalar, UnitT]:
809 """Convert unit or dict of units to the root units.
810
811 If any unit is non multiplicative and check_converter is True,
812 then None is returned as the multiplicative factor.
813
814 Parameters
815 ----------
816 input_units : UnitsContainer or str
817 units
818 check_nonmult : bool
819 if True, None will be returned as the
820 multiplicative factor if a non-multiplicative
821 units is found in the final Units. (Default value = True)
822
823 Returns
824 -------
825 Number, pint.Unit
826 multiplicative factor, plain units
827
828 """
829 input_units = to_units_container(input_units, self)
830
831 f, units = self._get_root_units(input_units, check_nonmult)
832
833 return f, self.Unit(units)
834
835 def _get_conversion_factor(
836 self, src: UnitsContainer, dst: UnitsContainer
837 ) -> Scalar | DimensionalityError:
838 """Get conversion factor in non-multiplicative units.
839
840 Parameters
841 ----------
842 src
843 Source units
844 dst
845 Target units
846
847 Returns
848 -------
849 Conversion factor or DimensionalityError
850 """
851 cache = self._cache.conversion_factor
852 try:
853 return cache[(src, dst)]
854 except KeyError:
855 pass
856
857 src_dim = self._get_dimensionality(src)
858 dst_dim = self._get_dimensionality(dst)
859
860 # If the source and destination dimensionality are different,
861 # then the conversion cannot be performed.
862 if src_dim != dst_dim:
863 return DimensionalityError(src, dst, src_dim, dst_dim)
864
865 # Here src and dst have only multiplicative units left. Thus we can
866 # convert with a factor.
867 factor, _ = self._get_root_units(src / dst)
868
869 cache[(src, dst)] = factor
870 return factor
871
872 def _get_root_units(
873 self, input_units: UnitsContainer, check_nonmult: bool = True
874 ) -> tuple[Scalar, UnitsContainer]:
875 """Convert unit or dict of units to the root units.
876
877 If any unit is non multiplicative and check_converter is True,
878 then None is returned as the multiplicative factor.
879
880 Parameters
881 ----------
882 input_units : UnitsContainer or dict
883 units
884 check_nonmult : bool
885 if True, None will be returned as the
886 multiplicative factor if a non-multiplicative
887 units is found in the final Units. (Default value = True)
888
889 Returns
890 -------
891 number, Unit
892 multiplicative factor, plain units
893
894 """
895 if not input_units:
896 return 1, self.UnitsContainer()
897
898 cache = self._cache.root_units
899 try:
900 return cache[input_units]
901 except KeyError:
902 pass
903
904 accumulators: dict[str | None, int] = defaultdict(int)
905 fraction: dict[str, dict[Decimal | float, Decimal | int]] = dict(
906 numerator=dict(), denominator=dict()
907 )
908 self._get_root_units_recurse(input_units, 1, accumulators, fraction)
909
910 # Identify if terms appear in both numerator and denominator
911 def terms_are_unique(fraction):
912 for n_factor, n_exp in fraction["numerator"].items():
913 if n_factor in fraction["denominator"]:
914 return False
915 return True
916
917 # Cancel out terms where factor matches
918 while not terms_are_unique(fraction):
919 for n_factor, n_exponent in fraction["numerator"].items():
920 if n_factor in fraction["denominator"]:
921 if n_exponent >= fraction["denominator"][n_factor]:
922 fraction["numerator"][n_factor] -= fraction["denominator"][
923 n_factor
924 ]
925 del fraction["denominator"][n_factor]
926 continue
927 for d_factor, d_exponent in fraction["denominator"].items():
928 if d_factor in fraction["numerator"]:
929 if d_exponent >= fraction["numerator"][d_factor]:
930 fraction["denominator"][d_factor] -= fraction["numerator"][
931 d_factor
932 ]
933 del fraction["numerator"][d_factor]
934 continue
935
936 factor = 1
937 for n_factor, n_exponent in fraction["numerator"].copy().items():
938 if n_exponent == 0:
939 del fraction["numerator"][n_factor]
940 elif isinstance(n_factor, tuple):
941 # Uncancelled NaN factor: result is NaN
942 factor = float("nan")
943 else:
944 factor *= n_factor**n_exponent
945 for d_factor, d_exponent in fraction["denominator"].copy().items():
946 if d_exponent == 0:
947 del fraction["denominator"][d_factor]
948 elif isinstance(d_factor, tuple):
949 # Uncancelled NaN factor: result is NaN
950 factor = float("nan")
951 else:
952 factor *= d_factor**-d_exponent
953
954 units = self.UnitsContainer(
955 {k: v for k, v in accumulators.items() if k is not None and v != 0}
956 )
957
958 # Check if any of the final units is non multiplicative and return None instead.
959 if check_nonmult:
960 if any(not self._units[unit].converter.is_multiplicative for unit in units):
961 factor = None
962
963 cache[input_units] = factor, units
964 return factor, units
965
966 def get_base_units(
967 self,
968 input_units: UnitsContainer | str,
969 check_nonmult: bool = True,
970 system=None,
971 ) -> tuple[Scalar, UnitT]:
972 """Convert unit or dict of units to the plain units.
973
974 If any unit is non multiplicative and check_converter is True,
975 then None is returned as the multiplicative factor.
976
977 Parameters
978 ----------
979 input_units : UnitsContainer or str
980 units
981 check_nonmult : bool
982 If True, None will be returned as the multiplicative factor if
983 non-multiplicative units are found in the final Units.
984 (Default value = True)
985 system :
986 (Default value = None)
987
988 Returns
989 -------
990 Number, pint.Unit
991 multiplicative factor, plain units
992
993 """
994
995 return self.get_root_units(input_units, check_nonmult)
996
997 # TODO: accumulators breaks typing list[int, dict[str, int]]
998 # So we have changed the behavior here
999 def _get_root_units_recurse(
1000 self,
1001 ref: UnitsContainer,
1002 exp: Scalar,
1003 accumulators: dict[str | None, int],
1004 fraction: dict[str, dict[Decimal | float, Decimal | int]],
1005 ) -> None:
1006 """
1007
1008 accumulators None keeps the scalar prefactor not associated with a specific unit.
1009
1010 """
1011 for key in ref:
1012 exp2 = exp * ref[key]
1013 key = self.get_name(key)
1014 reg = self._units[key]
1015 if reg.is_base:
1016 accumulators[key] += exp2
1017 else:
1018 # Build numerator and denominator.
1019 # For NaN scales, use a unit-specific key so that NaN factors
1020 # from different units don't incorrectly cancel each other,
1021 # while NaN factors from the same unit (e.g. truckload appearing
1022 # via kilotruckload) can still cancel correctly.
1023 scale_key = (
1024 (key, "nan") if isnan(reg.converter.scale) else reg.converter.scale
1025 )
1026 if exp2 < 0:
1027 fraction["denominator"][scale_key] = (
1028 fraction["denominator"].get(scale_key, 0) - exp2
1029 )
1030 else:
1031 fraction["numerator"][scale_key] = (
1032 fraction["numerator"].get(scale_key, 0) + exp2
1033 )
1034 if reg.reference is not None:
1035 self._get_root_units_recurse(
1036 reg.reference, exp2, accumulators, fraction
1037 )
1038
1039 def get_compatible_units(self, input_units: QuantityOrUnitLike) -> frozenset[UnitT]:
1040 """ """
1041 input_units = to_units_container(input_units)
1042
1043 equiv = self._get_compatible_units(input_units)
1044
1045 return frozenset(self.Unit(eq) for eq in equiv)
1046
1047 def _get_compatible_units(
1048 self, input_units: UnitsContainer, *args, **kwargs
1049 ) -> frozenset[str]:
1050 """ """
1051 if not input_units:
1052 return frozenset()
1053
1054 src_dim = self._get_dimensionality(input_units)
1055 return self._cache.dimensional_equivalents.setdefault(src_dim, frozenset())
1056
1057 # TODO: remove context from here
1058 def is_compatible_with(
1059 self, obj1: Any, obj2: Any, *contexts: str | Context, **ctx_kwargs
1060 ) -> bool:
1061 """check if the other object is compatible
1062
1063 Parameters
1064 ----------
1065 obj1, obj2
1066 The objects to check against each other. Treated as
1067 dimensionless if not a Quantity, Unit or str.
1068 *contexts : str or pint.Context
1069 Contexts to use in the transformation.
1070 **ctx_kwargs :
1071 Values for the Context/s
1072
1073 Returns
1074 -------
1075 bool
1076 """
1077 if isinstance(obj1, (self.Quantity, self.Unit)):
1078 return obj1.is_compatible_with(obj2, *contexts, **ctx_kwargs)
1079
1080 if isinstance(obj1, str):
1081 return self.parse_expression(obj1).is_compatible_with(
1082 obj2, *contexts, **ctx_kwargs
1083 )
1084
1085 return not isinstance(obj2, (self.Quantity, self.Unit))
1086
1087 def convert(
1088 self,
1089 value: T,
1090 src: QuantityOrUnitLike,
1091 dst: QuantityOrUnitLike,
1092 inplace: bool = False,
1093 **ctx_kwargs,
1094 ) -> T:
1095 """Convert value from some source to destination units.
1096
1097 Parameters
1098 ----------
1099 value :
1100 value
1101 src : pint.Quantity or str
1102 source units.
1103 dst : pint.Quantity or str
1104 destination units.
1105 inplace :
1106 (Default value = False)
1107
1108 Returns
1109 -------
1110 type
1111 converted value
1112
1113 """
1114 src = to_units_container(src, self)
1115
1116 dst = to_units_container(dst, self)
1117
1118 if src == dst:
1119 return value
1120
1121 return self._convert(value, src, dst, inplace, **ctx_kwargs)
1122
1123 def _convert(
1124 self,
1125 value: T,
1126 src: UnitsContainer,
1127 dst: UnitsContainer,
1128 inplace: bool = False,
1129 check_dimensionality: bool = True,
1130 ) -> T:
1131 """Convert value from some source to destination units.
1132
1133 Parameters
1134 ----------
1135 value :
1136 value
1137 src : UnitsContainer
1138 source units.
1139 dst : UnitsContainer
1140 destination units.
1141 inplace :
1142 (Default value = False)
1143 check_dimensionality :
1144 (Default value = True)
1145
1146 Returns
1147 -------
1148 type
1149 converted value
1150
1151 """
1152
1153 factor = self._get_conversion_factor(src, dst)
1154
1155 if isinstance(factor, DimensionalityError):
1156 raise factor
1157
1158 # factor is type float and if our magnitude is type Decimal then
1159 # must first convert to Decimal before we can '*' the values
1160 if isinstance(value, Decimal):
1161 factor = Decimal(str(factor))
1162 elif isinstance(value, Fraction):
1163 factor = Fraction(str(factor))
1164
1165 if inplace:
1166 value *= factor
1167 else:
1168 value = value * factor
1169
1170 return value
1171
1172 def parse_unit_name(
1173 self, unit_name: str, case_sensitive: bool | None = None
1174 ) -> tuple[tuple[str, str, str], ...]:
1175 """Parse a unit to identify prefix, unit name and suffix
1176 by walking the list of prefix and suffix.
1177 In case of equivalent combinations (e.g. ('kilo', 'gram', '') and
1178 ('', 'kilogram', ''), prefer those with prefix.
1179
1180 Parameters
1181 ----------
1182 unit_name :
1183
1184 case_sensitive : bool or None
1185 Control if unit lookup is case sensitive. Defaults to None, which uses the
1186 registry's case_sensitive setting
1187
1188 Returns
1189 -------
1190 tuple of tuples (str, str, str)
1191 all non-equivalent combinations of (prefix, unit name, suffix)
1192 """
1193
1194 case_sensitive = (
1195 self.case_sensitive if case_sensitive is None else case_sensitive
1196 )
1197 return self._dedup_candidates(
1198 self._yield_unit_triplets(unit_name, case_sensitive)
1199 )
1200
1201 def _yield_unit_triplets(
1202 self, unit_name: str, case_sensitive: bool
1203 ) -> Generator[tuple[str, str, str]]:
1204 """Helper of parse_unit_name."""
1205
1206 stw = unit_name.startswith
1207 edw = unit_name.endswith
1208 for suffix, prefix in itertools.product(self._suffixes, self._prefixes):
1209 if stw(prefix) and edw(suffix):
1210 name = unit_name[len(prefix) :]
1211 if suffix:
1212 name = name[: -len(suffix)]
1213 if len(name) == 1:
1214 continue
1215 if case_sensitive:
1216 if name in self._units:
1217 yield (
1218 self._prefixes[prefix].name,
1219 self._units[name].name,
1220 self._suffixes[suffix],
1221 )
1222 else:
1223 for real_name in self._units_casei.get(name.lower(), ()):
1224 yield (
1225 self._prefixes[prefix].name,
1226 self._units[real_name].name,
1227 self._suffixes[suffix],
1228 )
1229
1230 # TODO: keep this for backward compatibility
1231 _parse_unit_name = _yield_unit_triplets
1232
1233 @staticmethod
1234 def _dedup_candidates(
1235 candidates: Iterable[tuple[str, str, str]],
1236 ) -> tuple[tuple[str, str, str], ...]:
1237 """Helper of parse_unit_name.
1238
1239 Given an iterable of unit triplets (prefix, name, suffix), remove those with
1240 different names but equal value, preferring those with a prefix.
1241
1242 e.g. ('kilo', 'gram', '') and ('', 'kilogram', '')
1243 """
1244 candidates = dict.fromkeys(candidates) # ordered set
1245 for cp, cu, cs in list(candidates):
1246 assert isinstance(cp, str)
1247 assert isinstance(cu, str)
1248 if cs != "":
1249 raise NotImplementedError("non-empty suffix")
1250 if cp:
1251 candidates.pop(("", cp + cu, ""), None)
1252 return tuple(candidates)
1253
1254 def parse_units(
1255 self,
1256 input_string: str,
1257 as_delta: bool | None = None,
1258 case_sensitive: bool | None = None,
1259 ) -> UnitT:
1260 """Parse a units expression and returns a UnitContainer with
1261 the canonical names.
1262
1263 The expression can only contain products, ratios and powers of units.
1264
1265 Parameters
1266 ----------
1267 input_string : str
1268 as_delta : bool or None
1269 if the expression has multiple units, the parser will
1270 interpret non multiplicative units as their `delta_` counterparts. (Default value = None)
1271 case_sensitive : bool or None
1272 Control if unit parsing is case sensitive. Defaults to None, which uses the
1273 registry's setting.
1274
1275 Returns
1276 -------
1277 pint.Unit
1278
1279 """
1280
1281 return self.Unit(
1282 self.parse_units_as_container(input_string, as_delta, case_sensitive)
1283 )
1284
1285 def parse_units_as_container(
1286 self,
1287 input_string: str,
1288 as_delta: bool | None = None,
1289 case_sensitive: bool | None = None,
1290 ) -> UnitsContainer:
1291 as_delta = (
1292 as_delta if as_delta is not None else True
1293 ) # TODO This only exists in nonmultiplicative
1294 case_sensitive = (
1295 case_sensitive if case_sensitive is not None else self.case_sensitive
1296 )
1297 return self._parse_units_as_container(input_string, as_delta, case_sensitive)
1298
1299 def _parse_units_as_container(
1300 self,
1301 input_string: str,
1302 as_delta: bool = True,
1303 case_sensitive: bool = True,
1304 ) -> UnitsContainer:
1305 """Parse a units expression and returns a UnitContainer with
1306 the canonical names.
1307 """
1308
1309 cache = self._cache.parse_unit
1310 # Issue #1097: it is possible, when a unit was defined while a different context
1311 # was active, that the unit is in self._cache.parse_unit but not in self._units.
1312 # If this is the case, force self._units to be repopulated.
1313 if as_delta and input_string in cache and input_string in self._units:
1314 return cache[input_string]
1315
1316 for p in self.preprocessors:
1317 input_string = p(input_string)
1318
1319 if not input_string:
1320 return self.UnitsContainer()
1321
1322 # Sanitize input_string with whitespaces.
1323 input_string = input_string.strip()
1324
1325 units = ParserHelper.from_string(input_string, self.non_int_type)
1326 if units.scale != 1:
1327 raise ValueError("Unit expression cannot have a scaling factor.")
1328
1329 ret = self.UnitsContainer({})
1330 many = len(units) > 1
1331 for name in units:
1332 cname = self.get_name(name, case_sensitive=case_sensitive)
1333 value = units[name]
1334 if not cname:
1335 continue
1336 if as_delta and (many or (not many and value != 1)):
1337 definition = self._units[cname]
1338 if not definition.is_multiplicative:
1339 cname = "delta_" + cname
1340 ret = ret.add(cname, value)
1341
1342 if as_delta:
1343 cache[input_string] = ret
1344
1345 return ret
1346
1347 def _eval_token(
1348 self,
1349 token: TokenInfo,
1350 case_sensitive: bool | None = None,
1351 **values: QuantityArgument,
1352 ):
1353 """Evaluate a single token using the following rules:
1354
1355 1. numerical values as strings are replaced by their numeric counterparts
1356 - integers are parsed as integers
1357 - other numeric values are parses of non_int_type
1358 2. strings in (inf, infinity, nan, dimensionless) with their numerical value.
1359 3. strings in values.keys() are replaced by Quantity(values[key])
1360 4. in other cases, the values are parsed as units and replaced by their canonical name.
1361
1362 Parameters
1363 ----------
1364 token
1365 Token to evaluate.
1366 case_sensitive, optional
1367 If true, a case sensitive matching of the unit name will be done in the registry.
1368 If false, a case INsensitive matching of the unit name will be done in the registry.
1369 (Default value = None, which uses registry setting)
1370 **values
1371 Other string that will be parsed using the Quantity constructor on their corresponding value.
1372 """
1373 token_type = token[0]
1374 token_text = token[1]
1375 if token_type == NAME:
1376 if token_text == "dimensionless":
1377 return self.Quantity(1)
1378 elif token_text.lower() in ("inf", "infinity"):
1379 return self.non_int_type("inf")
1380 elif token_text.lower() == "nan":
1381 return self.non_int_type("nan")
1382 elif token_text in values:
1383 return self.Quantity(values[token_text])
1384 else:
1385 return self.Quantity(
1386 1,
1387 self.UnitsContainer(
1388 {self.get_name(token_text, case_sensitive=case_sensitive): 1}
1389 ),
1390 )
1391 elif token_type == NUMBER:
1392 return ParserHelper.eval_token(token, non_int_type=self.non_int_type)
1393 else:
1394 raise Exception("unknown token type")
1395
1396 def parse_pattern(
1397 self,
1398 input_string: str,
1399 pattern: str,
1400 case_sensitive: bool | None = None,
1401 many: bool = False,
1402 ) -> list[str] | str | None:
1403 """Parse a string with a given regex pattern and returns result.
1404
1405 Parameters
1406 ----------
1407 input_string
1408
1409 pattern_string:
1410 The regex parse string
1411 case_sensitive, optional
1412 If true, a case sensitive matching of the unit name will be done in the registry.
1413 If false, a case INsensitive matching of the unit name will be done in the registry.
1414 (Default value = None, which uses registry setting)
1415 many, optional
1416 Match many results
1417 (Default value = False)
1418 """
1419
1420 if not input_string:
1421 return [] if many else None
1422
1423 # Parse string
1424 regex = pattern_to_regex(pattern)
1425 matched = re.finditer(regex, input_string)
1426
1427 # Extract result(s)
1428 results = []
1429 for match in matched:
1430 # Extract units from result
1431 match = match.groupdict()
1432
1433 # Parse units
1434 units = [
1435 float(value) * self.parse_expression(unit, case_sensitive)
1436 for unit, value in match.items()
1437 ]
1438
1439 # Add to results
1440 results.append(units)
1441
1442 # Return first match only
1443 if not many:
1444 return results[0]
1445
1446 return results
1447
1448 def parse_expression(
1449 self: Self,
1450 input_string: str,
1451 case_sensitive: bool | None = None,
1452 **values: QuantityArgument,
1453 ) -> QuantityT:
1454 """Parse a mathematical expression including units and return a quantity object.
1455
1456 Numerical constants can be specified as keyword arguments and will take precedence
1457 over the names defined in the registry.
1458
1459 Parameters
1460 ----------
1461 input_string
1462
1463 case_sensitive, optional
1464 If true, a case sensitive matching of the unit name will be done in the registry.
1465 If false, a case INsensitive matching of the unit name will be done in the registry.
1466 (Default value = None, which uses registry setting)
1467 **values
1468 Other string that will be parsed using the Quantity constructor on their corresponding value.
1469 """
1470 if not input_string:
1471 return self.Quantity(1)
1472
1473 for p in self.preprocessors:
1474 input_string = p(input_string)
1475 input_string = string_preprocessor(input_string)
1476 gen = pint_eval.tokenizer(input_string)
1477
1478 def _define_op(s: str):
1479 return self._eval_token(s, case_sensitive=case_sensitive, **values)
1480
1481 result = build_eval_tree(gen).evaluate(_define_op)
1482
1483 if not isinstance(result, self.Quantity):
1484 return self.Quantity(result)
1485 return result
1486
1487 # We put this last to avoid overriding UnitsContainer
1488 # and I do not want to rename it.
1489 # TODO: Maybe in the future we need to change it to a more meaningful
1490 # non-colliding name.
1491 def UnitsContainer(self, *args: Any, **kwargs: Any) -> UnitsContainer:
1492 return UnitsContainer(*args, non_int_type=self.non_int_type, **kwargs)
1493
1494 __call__ = parse_expression
1495
1496
1497 class PlainRegistry(GenericPlainRegistry[PlainQuantity, PlainUnit]):
1498 Quantity: TypeAlias = PlainQuantity
1499 Unit: TypeAlias = PlainUnit