Debian Codegraph @

pint/facets/nonmultiplicative/objects.py

raw
1 """
2 pint.facets.nonmultiplicative.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 from typing import Generic
12
13 from ..plain import MagnitudeT, PlainQuantity, PlainUnit
14
15
16 class NonMultiplicativeQuantity(Generic[MagnitudeT], PlainQuantity[MagnitudeT]):
17 @property
18 def _is_multiplicative(self) -> bool:
19 """Check if the PlainQuantity object has only multiplicative units."""
20 return not self._get_non_multiplicative_units()
21
22 def _get_non_multiplicative_units(self) -> list[str]:
23 """Return a list of the of non-multiplicative units of the PlainQuantity object."""
24 return [
25 unit
26 for unit in self._units
27 if not self._get_unit_definition(unit).is_multiplicative
28 ]
29
30 @property
31 def _is_logarithmic(self) -> bool:
32 """Check if the PlainQuantity object has logarithmic units."""
33 if (
34 len(self._units) == 1
35 and self._get_unit_definition(next(iter(self._units))).is_logarithmic
36 ):
37 return True
38 return False
39
40 def _get_delta_units(self) -> list[str]:
41 """Return list of delta units ot the PlainQuantity object."""
42 return [u for u in self._units if u.startswith("delta_")]
43
44 def _has_compatible_delta(self, unit: str) -> bool:
45 """ "Check if PlainQuantity object has a delta_unit that is compatible with unit"""
46 deltas = self._get_delta_units()
47 if "delta_" + unit in deltas:
48 return True
49 # Look for delta units with same dimension as the offset unit
50 offset_unit_dim = self._get_unit_definition(unit).reference
51 return any(
52 self._get_unit_definition(d).reference == offset_unit_dim for d in deltas
53 )
54
55 def _ok_for_muldiv(self, no_offset_units: int | None = None) -> bool:
56 """Checks if PlainQuantity object can be multiplied or divided"""
57
58 is_ok = True
59 if no_offset_units is None:
60 no_offset_units = len(self._get_non_multiplicative_units())
61 if no_offset_units > 1:
62 is_ok = False
63 if no_offset_units == 1:
64 if len(self._units) > 1:
65 is_ok = False
66 if (
67 len(self._units) == 1
68 and not self._REGISTRY.autoconvert_offset_to_baseunit
69 ):
70 is_ok = False
71 if next(iter(self._units.values())) != 1:
72 is_ok = False
73 return is_ok
74
75
76 class NonMultiplicativeUnit(PlainUnit):
77 pass