| 1 |
""" |
| 2 |
pint.facets.plain.quantity |
| 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 copy |
| 12 |
import datetime |
| 13 |
import locale |
| 14 |
import numbers |
| 15 |
import operator |
| 16 |
from collections.abc import Callable, Iterable, Iterator, Sequence |
| 17 |
from typing import ( |
| 18 |
TYPE_CHECKING, |
| 19 |
Any, |
| 20 |
Generic, |
| 21 |
TypeVar, |
| 22 |
overload, |
| 23 |
) |
| 24 |
|
| 25 |
from ..._typing import Magnitude, QuantityOrUnitLike, Scalar, UnitLike |
| 26 |
from ...compat import ( |
| 27 |
HAS_NUMPY, |
| 28 |
Self, |
| 29 |
_to_magnitude, |
| 30 |
deprecated, |
| 31 |
eq, |
| 32 |
is_duck_array_type, |
| 33 |
is_upcast_type, |
| 34 |
np, |
| 35 |
zero_or_nan, |
| 36 |
) |
| 37 |
from ...errors import DimensionalityError, OffsetUnitCalculusError, PintTypeError |
| 38 |
from ...util import ( |
| 39 |
PrettyIPython, |
| 40 |
SharedRegistryObject, |
| 41 |
UnitsContainer, |
| 42 |
logger, |
| 43 |
to_units_container, |
| 44 |
) |
| 45 |
from . import qto |
| 46 |
from .definitions import UnitDefinition |
| 47 |
|
| 48 |
if TYPE_CHECKING: |
| 49 |
from ..context import Context |
| 50 |
from .unit import PlainUnit as Unit |
| 51 |
from .unit import UnitsContainer as UnitsContainerT |
| 52 |
|
| 53 |
if HAS_NUMPY: |
| 54 |
import numpy as np # noqa |
| 55 |
|
| 56 |
try: |
| 57 |
import uncertainties.unumpy as unp |
| 58 |
from uncertainties import UFloat, ufloat |
| 59 |
|
| 60 |
HAS_UNCERTAINTIES = True |
| 61 |
except ImportError: |
| 62 |
unp = np |
| 63 |
ufloat = Ufloat = None |
| 64 |
HAS_UNCERTAINTIES = False |
| 65 |
|
| 66 |
|
| 67 |
MagnitudeT = TypeVar("MagnitudeT", bound=Magnitude) |
| 68 |
ScalarT = TypeVar("ScalarT", bound=Scalar) |
| 69 |
|
| 70 |
T = TypeVar("T", bound=Magnitude) |
| 71 |
|
| 72 |
|
| 73 |
def ireduce_dimensions(f): |
| 74 |
def wrapped(self, *args, **kwargs): |
| 75 |
result = f(self, *args, **kwargs) |
| 76 |
try: |
| 77 |
if result._REGISTRY.autoconvert_to_preferred: |
| 78 |
result.ito_preferred() |
| 79 |
except AttributeError: |
| 80 |
pass |
| 81 |
|
| 82 |
try: |
| 83 |
if result._REGISTRY.auto_reduce_dimensions: |
| 84 |
result.ito_reduced_units() |
| 85 |
except AttributeError: |
| 86 |
pass |
| 87 |
return result |
| 88 |
|
| 89 |
return wrapped |
| 90 |
|
| 91 |
|
| 92 |
def check_implemented(f): |
| 93 |
def wrapped(self, *args, **kwargs): |
| 94 |
other = args[0] |
| 95 |
if is_upcast_type(type(other)): |
| 96 |
return NotImplemented |
| 97 |
# pandas often gets to arrays of quantities [ Q_(1,"m"), Q_(2,"m")] |
| 98 |
# and expects PlainQuantity * array[PlainQuantity] should return NotImplemented |
| 99 |
elif isinstance(other, list) and other and isinstance(other[0], type(self)): |
| 100 |
return NotImplemented |
| 101 |
return f(self, *args, **kwargs) |
| 102 |
|
| 103 |
return wrapped |
| 104 |
|
| 105 |
|
| 106 |
def method_wraps(numpy_func): |
| 107 |
if isinstance(numpy_func, str): |
| 108 |
numpy_func = getattr(np, numpy_func, None) |
| 109 |
|
| 110 |
def wrapper(func): |
| 111 |
func.__wrapped__ = numpy_func |
| 112 |
|
| 113 |
return func |
| 114 |
|
| 115 |
return wrapper |
| 116 |
|
| 117 |
|
| 118 |
# TODO: remove all nonmultiplicative remnants |
| 119 |
|
| 120 |
|
| 121 |
class PlainQuantity(Generic[MagnitudeT], PrettyIPython, SharedRegistryObject): |
| 122 |
"""Implements a class to describe a physical quantity: |
| 123 |
the product of a numerical value and a unit of measurement. |
| 124 |
|
| 125 |
Parameters |
| 126 |
---------- |
| 127 |
value : str, pint.PlainQuantity or any numeric type |
| 128 |
Value of the physical quantity to be created. |
| 129 |
units : UnitsContainer, str or pint.PlainQuantity |
| 130 |
Units of the physical quantity to be created. |
| 131 |
|
| 132 |
Returns |
| 133 |
------- |
| 134 |
|
| 135 |
""" |
| 136 |
|
| 137 |
_magnitude: MagnitudeT |
| 138 |
|
| 139 |
@property |
| 140 |
def ndim(self) -> int: |
| 141 |
if isinstance(self.magnitude, numbers.Number): |
| 142 |
return 0 |
| 143 |
if str(type(self.magnitude)) == "NAType": |
| 144 |
return 0 |
| 145 |
return self.magnitude.ndim |
| 146 |
|
| 147 |
@property |
| 148 |
def force_ndarray(self) -> bool: |
| 149 |
return self._REGISTRY.force_ndarray |
| 150 |
|
| 151 |
@property |
| 152 |
def force_ndarray_like(self) -> bool: |
| 153 |
return self._REGISTRY.force_ndarray_like |
| 154 |
|
| 155 |
def __reduce__(self) -> tuple[type, Magnitude, UnitsContainer]: |
| 156 |
"""Allow pickling quantities. Since UnitRegistries are not pickled, upon |
| 157 |
unpickling the new object is always attached to the application registry. |
| 158 |
""" |
| 159 |
from pint import _unpickle_quantity |
| 160 |
|
| 161 |
# Note: type(self) would be a mistake as subclasses built by |
| 162 |
# dinamically can't be pickled |
| 163 |
# TODO: Check if this is still the case. |
| 164 |
return _unpickle_quantity, (PlainQuantity, self.magnitude, self._units) |
| 165 |
|
| 166 |
@overload |
| 167 |
def __new__( |
| 168 |
cls, value: MagnitudeT, units: UnitLike | None = None |
| 169 |
) -> PlainQuantity[MagnitudeT]: ... |
| 170 |
|
| 171 |
@overload |
| 172 |
def __new__( |
| 173 |
cls, value: str, units: UnitLike | None = None |
| 174 |
) -> PlainQuantity[Any]: ... |
| 175 |
|
| 176 |
@overload |
| 177 |
def __new__( # type: ignore[misc] |
| 178 |
cls, value: Sequence[ScalarT], units: UnitLike | None = None |
| 179 |
) -> PlainQuantity[Any]: ... |
| 180 |
|
| 181 |
@overload |
| 182 |
def __new__( |
| 183 |
cls, value: PlainQuantity[Any], units: UnitLike | None = None |
| 184 |
) -> PlainQuantity[Any]: ... |
| 185 |
|
| 186 |
def __new__(cls, value, units=None): |
| 187 |
if is_upcast_type(type(value)): |
| 188 |
raise TypeError(f"PlainQuantity cannot wrap upcast type {type(value)}") |
| 189 |
|
| 190 |
if units is None and isinstance(value, str) and value == "": |
| 191 |
raise ValueError( |
| 192 |
"Expression to parse as PlainQuantity cannot be an empty string." |
| 193 |
) |
| 194 |
|
| 195 |
if units is None and isinstance(value, str): |
| 196 |
ureg = SharedRegistryObject.__new__(cls)._REGISTRY |
| 197 |
inst = ureg.parse_expression(value) |
| 198 |
return cls.__new__(cls, inst) |
| 199 |
|
| 200 |
if units is None and isinstance(value, cls): |
| 201 |
return copy.copy(value) |
| 202 |
|
| 203 |
inst = SharedRegistryObject().__new__(cls) |
| 204 |
if units is None: |
| 205 |
units = inst.UnitsContainer() |
| 206 |
else: |
| 207 |
if isinstance(units, (UnitsContainer, UnitDefinition)): |
| 208 |
units = units |
| 209 |
elif isinstance(units, str): |
| 210 |
units = inst._REGISTRY.parse_units(units)._units |
| 211 |
elif isinstance(units, SharedRegistryObject): |
| 212 |
if isinstance(units, PlainQuantity) and units.magnitude != 1: |
| 213 |
units = copy.copy(units)._units |
| 214 |
logger.warning( |
| 215 |
"Creating new PlainQuantity using a non unity PlainQuantity as units." |
| 216 |
) |
| 217 |
else: |
| 218 |
units = units._units |
| 219 |
else: |
| 220 |
raise TypeError( |
| 221 |
"units must be of type str, PlainQuantity or " |
| 222 |
"UnitsContainer; not {}.".format(type(units)) |
| 223 |
) |
| 224 |
if isinstance(value, cls): |
| 225 |
magnitude = value.to(units)._magnitude |
| 226 |
else: |
| 227 |
magnitude = _to_magnitude( |
| 228 |
value, inst.force_ndarray, inst.force_ndarray_like |
| 229 |
) |
| 230 |
inst._magnitude = magnitude |
| 231 |
inst._units = units |
| 232 |
|
| 233 |
return inst |
| 234 |
|
| 235 |
def __iter__(self: PlainQuantity[MagnitudeT]) -> Iterator[Any]: |
| 236 |
# Make sure that, if self.magnitude is not iterable, we raise TypeError as soon |
| 237 |
# as one calls iter(self) without waiting for the first element to be drawn from |
| 238 |
# the iterator |
| 239 |
it_magnitude = iter(self.magnitude) |
| 240 |
|
| 241 |
def it_outer(): |
| 242 |
for element in it_magnitude: |
| 243 |
yield self.__class__(element, self._units) |
| 244 |
|
| 245 |
return it_outer() |
| 246 |
|
| 247 |
def __copy__(self) -> PlainQuantity[MagnitudeT]: |
| 248 |
ret = self.__class__(copy.copy(self._magnitude), self._units) |
| 249 |
return ret |
| 250 |
|
| 251 |
def __deepcopy__(self, memo) -> PlainQuantity[MagnitudeT]: |
| 252 |
ret = self.__class__( |
| 253 |
copy.deepcopy(self._magnitude, memo), copy.deepcopy(self._units, memo) |
| 254 |
) |
| 255 |
return ret |
| 256 |
|
| 257 |
@deprecated( |
| 258 |
"This function will be removed in future versions of pint.\n" |
| 259 |
"Use ureg.formatter.format_quantity_babel" |
| 260 |
) |
| 261 |
def format_babel(self, spec: str = "", **kwspec: Any) -> str: |
| 262 |
return self._REGISTRY.formatter.format_quantity_babel(self, spec, **kwspec) |
| 263 |
|
| 264 |
def __format__(self, spec: str) -> str: |
| 265 |
return self._REGISTRY.formatter.format_quantity(self, spec) |
| 266 |
|
| 267 |
def __str__(self) -> str: |
| 268 |
return self._REGISTRY.formatter.format_quantity(self) |
| 269 |
|
| 270 |
def __bytes__(self) -> bytes: |
| 271 |
return str(self).encode(locale.getpreferredencoding()) |
| 272 |
|
| 273 |
def __repr__(self) -> str: |
| 274 |
if HAS_UNCERTAINTIES: |
| 275 |
if isinstance(self._magnitude, UFloat): |
| 276 |
return f"<Quantity({self._magnitude:.6}, '{self._units}')>" |
| 277 |
else: |
| 278 |
return f"<Quantity({self._magnitude}, '{self._units}')>" |
| 279 |
elif isinstance(self._magnitude, float): |
| 280 |
return f"<Quantity({self._magnitude:.9}, '{self._units}')>" |
| 281 |
|
| 282 |
return f"<Quantity({self._magnitude}, '{self._units}')>" |
| 283 |
|
| 284 |
def __hash__(self) -> int: |
| 285 |
self_base = self.to_base_units() |
| 286 |
if self_base.dimensionless: |
| 287 |
return hash(self_base.magnitude) |
| 288 |
|
| 289 |
return hash((self_base.__class__, self_base.magnitude, self_base.units)) |
| 290 |
|
| 291 |
@property |
| 292 |
def magnitude(self) -> MagnitudeT: |
| 293 |
"""PlainQuantity's magnitude. Long form for `m`""" |
| 294 |
return self._magnitude |
| 295 |
|
| 296 |
@property |
| 297 |
def m(self) -> MagnitudeT: |
| 298 |
"""PlainQuantity's magnitude. Short form for `magnitude`""" |
| 299 |
return self._magnitude |
| 300 |
|
| 301 |
def m_as(self, units) -> MagnitudeT: |
| 302 |
"""PlainQuantity's magnitude expressed in particular units. |
| 303 |
|
| 304 |
Parameters |
| 305 |
---------- |
| 306 |
units : pint.PlainQuantity, str or dict |
| 307 |
destination units |
| 308 |
|
| 309 |
Returns |
| 310 |
------- |
| 311 |
|
| 312 |
""" |
| 313 |
return self.to(units).magnitude |
| 314 |
|
| 315 |
@property |
| 316 |
def units(self) -> Unit: |
| 317 |
"""PlainQuantity's units. Long form for `u`""" |
| 318 |
return self._REGISTRY.Unit(self._units) |
| 319 |
|
| 320 |
@property |
| 321 |
def u(self) -> Unit: |
| 322 |
"""PlainQuantity's units. Short form for `units`""" |
| 323 |
return self._REGISTRY.Unit(self._units) |
| 324 |
|
| 325 |
@property |
| 326 |
def unitless(self) -> bool: |
| 327 |
""" """ |
| 328 |
return not bool(self.to_root_units()._units) |
| 329 |
|
| 330 |
def unit_items(self) -> Iterable[tuple[str, Scalar]]: |
| 331 |
"""A view of the unit items.""" |
| 332 |
return self._units.unit_items() |
| 333 |
|
| 334 |
@property |
| 335 |
def dimensionless(self) -> bool: |
| 336 |
""" """ |
| 337 |
tmp = self.to_root_units() |
| 338 |
|
| 339 |
return not bool(tmp.dimensionality) |
| 340 |
|
| 341 |
_dimensionality: UnitsContainerT | None = None |
| 342 |
|
| 343 |
@property |
| 344 |
def dimensionality(self) -> UnitsContainerT: |
| 345 |
""" |
| 346 |
Returns |
| 347 |
------- |
| 348 |
dict |
| 349 |
Dimensionality of the PlainQuantity, e.g. ``{length: 1, time: -1}`` |
| 350 |
""" |
| 351 |
if self._dimensionality is None: |
| 352 |
self._dimensionality = self._REGISTRY._get_dimensionality(self._units) |
| 353 |
|
| 354 |
return self._dimensionality |
| 355 |
|
| 356 |
def check(self, dimension: UnitLike) -> bool: |
| 357 |
"""Return true if the quantity's dimension matches passed dimension.""" |
| 358 |
return self.dimensionality == self._REGISTRY.get_dimensionality(dimension) |
| 359 |
|
| 360 |
@classmethod |
| 361 |
def from_list( |
| 362 |
cls, quant_list: list[PlainQuantity[MagnitudeT]], units=None |
| 363 |
) -> PlainQuantity[MagnitudeT]: |
| 364 |
"""Transforms a list of Quantities into an numpy.array quantity. |
| 365 |
If no units are specified, the unit of the first element will be used. |
| 366 |
Same as from_sequence. |
| 367 |
|
| 368 |
If units is not specified and list is empty, the unit cannot be determined |
| 369 |
and a ValueError is raised. |
| 370 |
|
| 371 |
Parameters |
| 372 |
---------- |
| 373 |
quant_list : list of pint.PlainQuantity |
| 374 |
list of pint.PlainQuantity |
| 375 |
units : UnitsContainer, str or pint.PlainQuantity |
| 376 |
units of the physical quantity to be created (Default value = None) |
| 377 |
|
| 378 |
Returns |
| 379 |
------- |
| 380 |
pint.PlainQuantity |
| 381 |
""" |
| 382 |
return cls.from_sequence(quant_list, units=units) |
| 383 |
|
| 384 |
@classmethod |
| 385 |
def from_sequence( |
| 386 |
cls, seq: Sequence[PlainQuantity[MagnitudeT]], units=None |
| 387 |
) -> PlainQuantity[MagnitudeT]: |
| 388 |
"""Transforms a sequence of Quantities into an numpy.array quantity. |
| 389 |
If no units are specified, the unit of the first element will be used. |
| 390 |
|
| 391 |
If units is not specified and sequence is empty, the unit cannot be determined |
| 392 |
and a ValueError is raised. |
| 393 |
|
| 394 |
Parameters |
| 395 |
---------- |
| 396 |
seq : sequence of pint.PlainQuantity |
| 397 |
sequence of pint.PlainQuantity |
| 398 |
units : UnitsContainer, str or pint.PlainQuantity |
| 399 |
units of the physical quantity to be created (Default value = None) |
| 400 |
|
| 401 |
Returns |
| 402 |
------- |
| 403 |
pint.PlainQuantity |
| 404 |
""" |
| 405 |
|
| 406 |
len_seq = len(seq) |
| 407 |
if units is None: |
| 408 |
if len_seq: |
| 409 |
units = seq[0].u |
| 410 |
else: |
| 411 |
raise ValueError("Cannot determine units from empty sequence!") |
| 412 |
|
| 413 |
a = np.empty(len_seq) |
| 414 |
|
| 415 |
for i, seq_i in enumerate(seq): |
| 416 |
a[i] = seq_i.m_as(units) |
| 417 |
# raises DimensionalityError if incompatible units are used in the sequence |
| 418 |
|
| 419 |
return cls(a, units) |
| 420 |
|
| 421 |
@classmethod |
| 422 |
def from_tuple(cls, tup): |
| 423 |
for units_tup in tup[1]: |
| 424 |
cls._REGISTRY.get_name(units_tup[0]) |
| 425 |
return cls(tup[0], cls._REGISTRY.UnitsContainer(tup[1])) |
| 426 |
|
| 427 |
def to_tuple(self) -> tuple[MagnitudeT, tuple[tuple[str, ...]]]: |
| 428 |
return self.m, tuple(self._units.items()) |
| 429 |
|
| 430 |
def compatible_units(self, *contexts): |
| 431 |
if contexts: |
| 432 |
with self._REGISTRY.context(*contexts): |
| 433 |
return self._REGISTRY.get_compatible_units(self._units) |
| 434 |
|
| 435 |
return self._REGISTRY.get_compatible_units(self._units) |
| 436 |
|
| 437 |
def is_compatible_with( |
| 438 |
self, other: Any, *contexts: str | Context, **ctx_kwargs: Any |
| 439 |
) -> bool: |
| 440 |
"""check if the other object is compatible |
| 441 |
|
| 442 |
Parameters |
| 443 |
---------- |
| 444 |
other |
| 445 |
The object to check. Treated as dimensionless if not a |
| 446 |
PlainQuantity, Unit or str. |
| 447 |
*contexts : str or pint.Context |
| 448 |
Contexts to use in the transformation. |
| 449 |
**ctx_kwargs : |
| 450 |
Values for the Context/s |
| 451 |
|
| 452 |
Returns |
| 453 |
------- |
| 454 |
bool |
| 455 |
""" |
| 456 |
from .unit import PlainUnit |
| 457 |
|
| 458 |
if contexts or self._REGISTRY._active_ctx: |
| 459 |
try: |
| 460 |
self.to(other, *contexts, **ctx_kwargs) |
| 461 |
return True |
| 462 |
except DimensionalityError: |
| 463 |
return False |
| 464 |
|
| 465 |
if isinstance(other, (PlainQuantity, PlainUnit)): |
| 466 |
return self.dimensionality == other.dimensionality |
| 467 |
|
| 468 |
if isinstance(other, str): |
| 469 |
return ( |
| 470 |
self.dimensionality == self._REGISTRY.parse_units(other).dimensionality |
| 471 |
) |
| 472 |
|
| 473 |
return self.dimensionless |
| 474 |
|
| 475 |
def _convert_magnitude_not_inplace(self, other, *contexts, **ctx_kwargs): |
| 476 |
if contexts: |
| 477 |
with self._REGISTRY.context(*contexts, **ctx_kwargs): |
| 478 |
return self._REGISTRY.convert(self._magnitude, self._units, other) |
| 479 |
|
| 480 |
return self._REGISTRY.convert(self._magnitude, self._units, other, **ctx_kwargs) |
| 481 |
|
| 482 |
def _convert_magnitude(self, other, *contexts, **ctx_kwargs): |
| 483 |
if contexts: |
| 484 |
with self._REGISTRY.context(*contexts, **ctx_kwargs): |
| 485 |
return self._REGISTRY.convert(self._magnitude, self._units, other) |
| 486 |
|
| 487 |
return self._REGISTRY.convert( |
| 488 |
self._magnitude, |
| 489 |
self._units, |
| 490 |
other, |
| 491 |
inplace=is_duck_array_type(type(self._magnitude)), |
| 492 |
**ctx_kwargs, |
| 493 |
) |
| 494 |
|
| 495 |
def ito( |
| 496 |
self, other: QuantityOrUnitLike | None = None, *contexts, **ctx_kwargs |
| 497 |
) -> None: |
| 498 |
"""Inplace rescale to different units. |
| 499 |
|
| 500 |
Parameters |
| 501 |
---------- |
| 502 |
other : pint.PlainQuantity, str or dict |
| 503 |
Destination units. (Default value = None) |
| 504 |
*contexts : str or pint.Context |
| 505 |
Contexts to use in the transformation. |
| 506 |
**ctx_kwargs : |
| 507 |
Values for the Context/s |
| 508 |
""" |
| 509 |
|
| 510 |
other = to_units_container(other, self._REGISTRY) |
| 511 |
|
| 512 |
self._magnitude = self._convert_magnitude(other, *contexts, **ctx_kwargs) |
| 513 |
self._units = other |
| 514 |
|
| 515 |
return None |
| 516 |
|
| 517 |
def to( |
| 518 |
self, other: QuantityOrUnitLike | None = None, *contexts, **ctx_kwargs |
| 519 |
) -> Self: |
| 520 |
"""Return PlainQuantity rescaled to different units. |
| 521 |
|
| 522 |
Parameters |
| 523 |
---------- |
| 524 |
other : pint.PlainQuantity, str or dict |
| 525 |
destination units. (Default value = None) |
| 526 |
*contexts : str or pint.Context |
| 527 |
Contexts to use in the transformation. |
| 528 |
**ctx_kwargs : |
| 529 |
Values for the Context/s |
| 530 |
|
| 531 |
Returns |
| 532 |
------- |
| 533 |
pint.PlainQuantity |
| 534 |
""" |
| 535 |
other = to_units_container(other, self._REGISTRY) |
| 536 |
|
| 537 |
magnitude = self._convert_magnitude_not_inplace(other, *contexts, **ctx_kwargs) |
| 538 |
|
| 539 |
return self.__class__(magnitude, other) |
| 540 |
|
| 541 |
def ito_root_units(self) -> None: |
| 542 |
"""Return PlainQuantity rescaled to root units.""" |
| 543 |
|
| 544 |
_, other = self._REGISTRY._get_root_units(self._units) |
| 545 |
|
| 546 |
self._magnitude = self._convert_magnitude(other) |
| 547 |
self._units = other |
| 548 |
|
| 549 |
return None |
| 550 |
|
| 551 |
def to_root_units(self) -> PlainQuantity[MagnitudeT]: |
| 552 |
"""Return PlainQuantity rescaled to root units.""" |
| 553 |
|
| 554 |
_, other = self._REGISTRY._get_root_units(self._units) |
| 555 |
|
| 556 |
magnitude = self._convert_magnitude_not_inplace(other) |
| 557 |
|
| 558 |
return self.__class__(magnitude, other) |
| 559 |
|
| 560 |
def ito_base_units(self) -> None: |
| 561 |
"""Return PlainQuantity rescaled to plain units.""" |
| 562 |
|
| 563 |
_, other = self._REGISTRY._get_base_units(self._units) |
| 564 |
|
| 565 |
self._magnitude = self._convert_magnitude(other) |
| 566 |
self._units = other |
| 567 |
|
| 568 |
return None |
| 569 |
|
| 570 |
def to_base_units(self) -> PlainQuantity[MagnitudeT]: |
| 571 |
"""Return PlainQuantity rescaled to plain units.""" |
| 572 |
|
| 573 |
_, other = self._REGISTRY._get_base_units(self._units) |
| 574 |
|
| 575 |
magnitude = self._convert_magnitude_not_inplace(other) |
| 576 |
|
| 577 |
return self.__class__(magnitude, other) |
| 578 |
|
| 579 |
# Functions not essential to a Quantity but it is |
| 580 |
# convenient that they live in PlainQuantity. |
| 581 |
# They are implemented elsewhere to keep Quantity class clean. |
| 582 |
to_compact = qto.to_compact |
| 583 |
to_preferred = qto.to_preferred |
| 584 |
ito_preferred = qto.ito_preferred |
| 585 |
to_reduced_units = qto.to_reduced_units |
| 586 |
ito_reduced_units = qto.ito_reduced_units |
| 587 |
to_unprefixed = qto.to_unprefixed |
| 588 |
ito_unprefixed = qto.ito_unprefixed |
| 589 |
|
| 590 |
# Mathematical operations |
| 591 |
def __int__(self) -> int: |
| 592 |
if self.dimensionless: |
| 593 |
return int(self._convert_magnitude_not_inplace(UnitsContainer())) |
| 594 |
raise DimensionalityError(self._units, "dimensionless") |
| 595 |
|
| 596 |
def __float__(self) -> float: |
| 597 |
if self.dimensionless: |
| 598 |
return float(self._convert_magnitude_not_inplace(UnitsContainer())) |
| 599 |
raise DimensionalityError(self._units, "dimensionless") |
| 600 |
|
| 601 |
def __complex__(self) -> complex: |
| 602 |
if self.dimensionless: |
| 603 |
return complex(self._convert_magnitude_not_inplace(UnitsContainer())) |
| 604 |
raise DimensionalityError(self._units, "dimensionless") |
| 605 |
|
| 606 |
@check_implemented |
| 607 |
def _iadd_sub(self, other, op): |
| 608 |
"""Perform addition or subtraction operation in-place and return the result. |
| 609 |
|
| 610 |
Parameters |
| 611 |
---------- |
| 612 |
other : pint.PlainQuantity or any type accepted by :func:`_to_magnitude` |
| 613 |
object to be added to / subtracted from self |
| 614 |
op : function |
| 615 |
operator function (e.g. operator.add, operator.isub) |
| 616 |
|
| 617 |
""" |
| 618 |
if not self._check(other): |
| 619 |
# other not from same Registry or not a PlainQuantity |
| 620 |
try: |
| 621 |
other_magnitude = _to_magnitude( |
| 622 |
other, self.force_ndarray, self.force_ndarray_like |
| 623 |
) |
| 624 |
except PintTypeError: |
| 625 |
raise |
| 626 |
except TypeError: |
| 627 |
return NotImplemented |
| 628 |
if zero_or_nan(other, True): |
| 629 |
# If the other value is 0 (but not PlainQuantity 0) |
| 630 |
# do the operation without checking units. |
| 631 |
# We do the calculation instead of just returning the same |
| 632 |
# value to enforce any shape checking and type casting due to |
| 633 |
# the operation. |
| 634 |
self._magnitude = op(self._magnitude, other_magnitude) |
| 635 |
elif self.dimensionless: |
| 636 |
self.ito(self.UnitsContainer()) |
| 637 |
self._magnitude = op(self._magnitude, other_magnitude) |
| 638 |
else: |
| 639 |
raise DimensionalityError(self._units, "dimensionless") |
| 640 |
return self |
| 641 |
|
| 642 |
if not self.dimensionality == other.dimensionality: |
| 643 |
raise DimensionalityError( |
| 644 |
self._units, other._units, self.dimensionality, other.dimensionality |
| 645 |
) |
| 646 |
|
| 647 |
# Next we define some variables to make if-clauses more readable. |
| 648 |
self_non_mul_units = self._get_non_multiplicative_units() |
| 649 |
is_self_multiplicative = len(self_non_mul_units) == 0 |
| 650 |
if len(self_non_mul_units) == 1: |
| 651 |
self_non_mul_unit = self_non_mul_units[0] |
| 652 |
other_non_mul_units = other._get_non_multiplicative_units() |
| 653 |
is_other_multiplicative = len(other_non_mul_units) == 0 |
| 654 |
if len(other_non_mul_units) == 1: |
| 655 |
other_non_mul_unit = other_non_mul_units[0] |
| 656 |
|
| 657 |
# Presence of non-multiplicative units gives rise to several cases. |
| 658 |
if is_self_multiplicative and is_other_multiplicative: |
| 659 |
if self._units == other._units: |
| 660 |
self._magnitude = op(self._magnitude, other._magnitude) |
| 661 |
# If only self has a delta unit, other determines unit of result. |
| 662 |
elif self._get_delta_units() and not other._get_delta_units(): |
| 663 |
self._magnitude = op( |
| 664 |
self._convert_magnitude(other._units), other._magnitude |
| 665 |
) |
| 666 |
self._units = other._units |
| 667 |
else: |
| 668 |
self._magnitude = op(self._magnitude, other.to(self._units)._magnitude) |
| 669 |
|
| 670 |
elif ( |
| 671 |
op == operator.isub |
| 672 |
and len(self_non_mul_units) == 1 |
| 673 |
and self._units[self_non_mul_unit] == 1 |
| 674 |
and not other._has_compatible_delta(self_non_mul_unit) |
| 675 |
): |
| 676 |
if self._units == other._units: |
| 677 |
self._magnitude = op(self._magnitude, other._magnitude) |
| 678 |
else: |
| 679 |
self._magnitude = op(self._magnitude, other.to(self._units)._magnitude) |
| 680 |
self._units = self._units.rename( |
| 681 |
self_non_mul_unit, "delta_" + self_non_mul_unit |
| 682 |
) |
| 683 |
|
| 684 |
elif ( |
| 685 |
op == operator.isub |
| 686 |
and len(other_non_mul_units) == 1 |
| 687 |
and other._units[other_non_mul_unit] == 1 |
| 688 |
and not self._has_compatible_delta(other_non_mul_unit) |
| 689 |
): |
| 690 |
# we convert to self directly since it is multiplicative |
| 691 |
self._magnitude = op(self._magnitude, other.to(self._units)._magnitude) |
| 692 |
|
| 693 |
elif ( |
| 694 |
len(self_non_mul_units) == 1 |
| 695 |
# order of the dimension of offset unit == 1 ? |
| 696 |
and self._units[self_non_mul_unit] == 1 |
| 697 |
and other._has_compatible_delta(self_non_mul_unit) |
| 698 |
): |
| 699 |
# Replace offset unit in self by the corresponding delta unit. |
| 700 |
# This is done to prevent a shift by offset in the to()-call. |
| 701 |
tu = self._units.rename(self_non_mul_unit, "delta_" + self_non_mul_unit) |
| 702 |
self._magnitude = op(self._magnitude, other.to(tu)._magnitude) |
| 703 |
elif ( |
| 704 |
len(other_non_mul_units) == 1 |
| 705 |
# order of the dimension of offset unit == 1 ? |
| 706 |
and other._units[other_non_mul_unit] == 1 |
| 707 |
and self._has_compatible_delta(other_non_mul_unit) |
| 708 |
): |
| 709 |
# Replace offset unit in other by the corresponding delta unit. |
| 710 |
# This is done to prevent a shift by offset in the to()-call. |
| 711 |
tu = other._units.rename(other_non_mul_unit, "delta_" + other_non_mul_unit) |
| 712 |
self._magnitude = op(self._convert_magnitude(tu), other._magnitude) |
| 713 |
self._units = other._units |
| 714 |
else: |
| 715 |
raise OffsetUnitCalculusError(self._units, other._units) |
| 716 |
|
| 717 |
return self |
| 718 |
|
| 719 |
@check_implemented |
| 720 |
def _add_sub(self, other, op): |
| 721 |
"""Perform addition or subtraction operation and return the result. |
| 722 |
|
| 723 |
Parameters |
| 724 |
---------- |
| 725 |
other : pint.PlainQuantity or any type accepted by :func:`_to_magnitude` |
| 726 |
object to be added to / subtracted from self |
| 727 |
op : function |
| 728 |
operator function (e.g. operator.add, operator.isub) |
| 729 |
""" |
| 730 |
if not self._check(other): |
| 731 |
# other not from same Registry or not a PlainQuantity |
| 732 |
if zero_or_nan(other, True): |
| 733 |
# If the other value is 0 or NaN (but not a PlainQuantity) |
| 734 |
# do the operation without checking units. |
| 735 |
# We do the calculation instead of just returning the same |
| 736 |
# value to enforce any shape checking and type casting due to |
| 737 |
# the operation. |
| 738 |
units = self._units |
| 739 |
magnitude = op( |
| 740 |
self._magnitude, |
| 741 |
_to_magnitude(other, self.force_ndarray, self.force_ndarray_like), |
| 742 |
) |
| 743 |
elif self.dimensionless: |
| 744 |
units = self.UnitsContainer() |
| 745 |
magnitude = op( |
| 746 |
self.to(units)._magnitude, |
| 747 |
_to_magnitude(other, self.force_ndarray, self.force_ndarray_like), |
| 748 |
) |
| 749 |
else: |
| 750 |
raise DimensionalityError(self._units, "dimensionless") |
| 751 |
return self.__class__(magnitude, units) |
| 752 |
|
| 753 |
# Special case for logarithmic units: dB can be added to dBm, dBW, etc. |
| 754 |
# Get non-multiplicative units before checking dimensionality |
| 755 |
self_non_mul_units = self._get_non_multiplicative_units() |
| 756 |
other_non_mul_units = other._get_non_multiplicative_units() |
| 757 |
|
| 758 |
# Next we define some variables to make if-clauses more readable. |
| 759 |
# We already have self_non_mul_units and other_non_mul_units from our logarithmic check |
| 760 |
is_self_multiplicative = len(self_non_mul_units) == 0 |
| 761 |
is_other_multiplicative = len(other_non_mul_units) == 0 |
| 762 |
|
| 763 |
if len(self_non_mul_units) == 1: |
| 764 |
self_non_mul_unit = self_non_mul_units[0] |
| 765 |
if len(other_non_mul_units) == 1: |
| 766 |
other_non_mul_unit = other_non_mul_units[0] |
| 767 |
|
| 768 |
# Check if we're dealing with logarithmic units that can be added (dB + dBm, etc.) |
| 769 |
if self._is_logarithmic and other._is_logarithmic: |
| 770 |
self_base = self.to_base_units() |
| 771 |
other_base = other.to_base_units() |
| 772 |
if op == operator.add: |
| 773 |
result = self_base * other_base |
| 774 |
elif op == operator.sub: |
| 775 |
result = self_base / other_base |
| 776 |
|
| 777 |
if self_base.dimensionless and other_base.dimensionless: |
| 778 |
return result.to(self._units) |
| 779 |
elif self_base.dimensionless: |
| 780 |
return result.to(other._units) |
| 781 |
elif other_base.dimensionless: |
| 782 |
return result.to(self._units) |
| 783 |
else: |
| 784 |
return result |
| 785 |
|
| 786 |
if not self.dimensionality == other.dimensionality: |
| 787 |
raise DimensionalityError( |
| 788 |
self._units, other._units, self.dimensionality, other.dimensionality |
| 789 |
) |
| 790 |
|
| 791 |
# Presence of non-multiplicative units gives rise to several cases. |
| 792 |
if is_self_multiplicative and is_other_multiplicative: |
| 793 |
if self._units == other._units: |
| 794 |
magnitude = op(self._magnitude, other._magnitude) |
| 795 |
units = self._units |
| 796 |
# If only self has a delta unit, other determines unit of result. |
| 797 |
elif self._get_delta_units() and not other._get_delta_units(): |
| 798 |
magnitude = op( |
| 799 |
self._convert_magnitude_not_inplace(other._units), other._magnitude |
| 800 |
) |
| 801 |
units = other._units |
| 802 |
else: |
| 803 |
units = self._units |
| 804 |
magnitude = op(self._magnitude, other.to(self._units).magnitude) |
| 805 |
|
| 806 |
elif ( |
| 807 |
op == operator.sub |
| 808 |
and len(self_non_mul_units) == 1 |
| 809 |
and self._units[self_non_mul_unit] == 1 |
| 810 |
and not other._has_compatible_delta(self_non_mul_unit) |
| 811 |
): |
| 812 |
if self._units == other._units: |
| 813 |
magnitude = op(self._magnitude, other._magnitude) |
| 814 |
else: |
| 815 |
magnitude = op(self._magnitude, other.to(self._units)._magnitude) |
| 816 |
units = self._units.rename(self_non_mul_unit, "delta_" + self_non_mul_unit) |
| 817 |
|
| 818 |
elif ( |
| 819 |
op == operator.sub |
| 820 |
and len(other_non_mul_units) == 1 |
| 821 |
and other._units[other_non_mul_unit] == 1 |
| 822 |
and not self._has_compatible_delta(other_non_mul_unit) |
| 823 |
): |
| 824 |
# we convert to self directly since it is multiplicative |
| 825 |
magnitude = op(self._magnitude, other.to(self._units)._magnitude) |
| 826 |
units = self._units |
| 827 |
|
| 828 |
elif ( |
| 829 |
len(self_non_mul_units) == 1 |
| 830 |
# order of the dimension of offset unit == 1 ? |
| 831 |
and self._units[self_non_mul_unit] == 1 |
| 832 |
and other._has_compatible_delta(self_non_mul_unit) |
| 833 |
): |
| 834 |
# Replace offset unit in self by the corresponding delta unit. |
| 835 |
# This is done to prevent a shift by offset in the to()-call. |
| 836 |
tu = self._units.rename(self_non_mul_unit, "delta_" + self_non_mul_unit) |
| 837 |
magnitude = op(self._magnitude, other.to(tu).magnitude) |
| 838 |
units = self._units |
| 839 |
elif ( |
| 840 |
len(other_non_mul_units) == 1 |
| 841 |
# order of the dimension of offset unit == 1 ? |
| 842 |
and other._units[other_non_mul_unit] == 1 |
| 843 |
and self._has_compatible_delta(other_non_mul_unit) |
| 844 |
): |
| 845 |
# Replace offset unit in other by the corresponding delta unit. |
| 846 |
# This is done to prevent a shift by offset in the to()-call. |
| 847 |
tu = other._units.rename(other_non_mul_unit, "delta_" + other_non_mul_unit) |
| 848 |
magnitude = op(self._convert_magnitude_not_inplace(tu), other._magnitude) |
| 849 |
units = other._units |
| 850 |
else: |
| 851 |
raise OffsetUnitCalculusError(self._units, other._units) |
| 852 |
|
| 853 |
return self.__class__(magnitude, units) |
| 854 |
|
| 855 |
@overload |
| 856 |
def __iadd__(self, other: datetime.datetime) -> datetime.timedelta: # type: ignore[misc] |
| 857 |
... |
| 858 |
|
| 859 |
@overload |
| 860 |
def __iadd__(self, other) -> PlainQuantity[MagnitudeT]: ... |
| 861 |
|
| 862 |
def __iadd__(self, other): |
| 863 |
if isinstance(other, datetime.datetime): |
| 864 |
return self.to_timedelta() + other |
| 865 |
elif is_duck_array_type(type(self._magnitude)): |
| 866 |
return self._iadd_sub(other, operator.iadd) |
| 867 |
|
| 868 |
return self._add_sub(other, operator.add) |
| 869 |
|
| 870 |
def __add__(self, other): |
| 871 |
if isinstance(other, datetime.datetime): |
| 872 |
return self.to_timedelta() + other |
| 873 |
|
| 874 |
return self._add_sub(other, operator.add) |
| 875 |
|
| 876 |
__radd__ = __add__ |
| 877 |
|
| 878 |
def __isub__(self, other): |
| 879 |
if is_duck_array_type(type(self._magnitude)): |
| 880 |
return self._iadd_sub(other, operator.isub) |
| 881 |
|
| 882 |
return self._add_sub(other, operator.sub) |
| 883 |
|
| 884 |
def __sub__(self, other): |
| 885 |
return self._add_sub(other, operator.sub) |
| 886 |
|
| 887 |
def __rsub__(self, other): |
| 888 |
if isinstance(other, datetime.datetime): |
| 889 |
return other - self.to_timedelta() |
| 890 |
|
| 891 |
return -self._add_sub(other, operator.sub) |
| 892 |
|
| 893 |
@check_implemented |
| 894 |
@ireduce_dimensions |
| 895 |
def _imul_div(self, other, magnitude_op, units_op=None): |
| 896 |
"""Perform multiplication or division operation in-place and return the |
| 897 |
result. |
| 898 |
|
| 899 |
Parameters |
| 900 |
---------- |
| 901 |
other : pint.PlainQuantity or any type accepted by :func:`_to_magnitude` |
| 902 |
object to be multiplied/divided with self |
| 903 |
magnitude_op : function |
| 904 |
operator function to perform on the magnitudes |
| 905 |
(e.g. operator.mul) |
| 906 |
units_op : function or None |
| 907 |
operator function to perform on the units; if None, |
| 908 |
*magnitude_op* is used (Default value = None) |
| 909 |
|
| 910 |
Returns |
| 911 |
------- |
| 912 |
|
| 913 |
""" |
| 914 |
if units_op is None: |
| 915 |
units_op = magnitude_op |
| 916 |
|
| 917 |
offset_units_self = self._get_non_multiplicative_units() |
| 918 |
no_offset_units_self = len(offset_units_self) |
| 919 |
|
| 920 |
if not self._check(other): |
| 921 |
if not self._ok_for_muldiv(no_offset_units_self): |
| 922 |
raise OffsetUnitCalculusError(self._units, getattr(other, "units", "")) |
| 923 |
if len(offset_units_self) == 1: |
| 924 |
if self._units[offset_units_self[0]] != 1 or magnitude_op not in ( |
| 925 |
operator.mul, |
| 926 |
operator.imul, |
| 927 |
): |
| 928 |
raise OffsetUnitCalculusError( |
| 929 |
self._units, getattr(other, "units", "") |
| 930 |
) |
| 931 |
try: |
| 932 |
other_magnitude = _to_magnitude( |
| 933 |
other, self.force_ndarray, self.force_ndarray_like |
| 934 |
) |
| 935 |
except PintTypeError: |
| 936 |
raise |
| 937 |
except TypeError: |
| 938 |
return NotImplemented |
| 939 |
self._magnitude = magnitude_op(self._magnitude, other_magnitude) |
| 940 |
self._units = units_op(self._units, self.UnitsContainer()) |
| 941 |
return self |
| 942 |
|
| 943 |
if isinstance(other, self._REGISTRY.Unit): |
| 944 |
other = 1 * other |
| 945 |
|
| 946 |
if not self._ok_for_muldiv(no_offset_units_self): |
| 947 |
raise OffsetUnitCalculusError(self._units, other._units) |
| 948 |
elif no_offset_units_self == len(self._units) == 1: |
| 949 |
self.ito_root_units() |
| 950 |
|
| 951 |
no_offset_units_other = len(other._get_non_multiplicative_units()) |
| 952 |
|
| 953 |
if not other._ok_for_muldiv(no_offset_units_other): |
| 954 |
raise OffsetUnitCalculusError(self._units, other._units) |
| 955 |
elif no_offset_units_other == len(other._units) == 1: |
| 956 |
other.ito_root_units() |
| 957 |
|
| 958 |
self._magnitude = magnitude_op(self._magnitude, other._magnitude) |
| 959 |
self._units = units_op(self._units, other._units) |
| 960 |
|
| 961 |
return self |
| 962 |
|
| 963 |
@check_implemented |
| 964 |
@ireduce_dimensions |
| 965 |
def _mul_div(self, other, magnitude_op, units_op=None): |
| 966 |
"""Perform multiplication or division operation and return the result. |
| 967 |
|
| 968 |
Parameters |
| 969 |
---------- |
| 970 |
other : pint.PlainQuantity or any type accepted by :func:`_to_magnitude` |
| 971 |
object to be multiplied/divided with self |
| 972 |
magnitude_op : function |
| 973 |
operator function to perform on the magnitudes |
| 974 |
(e.g. operator.mul) |
| 975 |
units_op : function or None |
| 976 |
operator function to perform on the units; if None, |
| 977 |
*magnitude_op* is used (Default value = None) |
| 978 |
|
| 979 |
Returns |
| 980 |
------- |
| 981 |
|
| 982 |
""" |
| 983 |
if units_op is None: |
| 984 |
units_op = magnitude_op |
| 985 |
|
| 986 |
offset_units_self = self._get_non_multiplicative_units() |
| 987 |
no_offset_units_self = len(offset_units_self) |
| 988 |
|
| 989 |
if not self._check(other): |
| 990 |
if not self._ok_for_muldiv(no_offset_units_self): |
| 991 |
raise OffsetUnitCalculusError(self._units, getattr(other, "units", "")) |
| 992 |
if len(offset_units_self) == 1: |
| 993 |
if self._units[offset_units_self[0]] != 1 or magnitude_op not in ( |
| 994 |
operator.mul, |
| 995 |
operator.imul, |
| 996 |
): |
| 997 |
raise OffsetUnitCalculusError( |
| 998 |
self._units, getattr(other, "units", "") |
| 999 |
) |
| 1000 |
try: |
| 1001 |
other_magnitude = _to_magnitude( |
| 1002 |
other, self.force_ndarray, self.force_ndarray_like |
| 1003 |
) |
| 1004 |
except PintTypeError: |
| 1005 |
raise |
| 1006 |
except TypeError: |
| 1007 |
return NotImplemented |
| 1008 |
|
| 1009 |
magnitude = magnitude_op(self._magnitude, other_magnitude) |
| 1010 |
units = units_op(self._units, self.UnitsContainer()) |
| 1011 |
|
| 1012 |
return self.__class__(magnitude, units) |
| 1013 |
|
| 1014 |
if isinstance(other, self._REGISTRY.Unit): |
| 1015 |
other = 1 * other |
| 1016 |
|
| 1017 |
new_self = self |
| 1018 |
|
| 1019 |
if not self._ok_for_muldiv(no_offset_units_self): |
| 1020 |
raise OffsetUnitCalculusError(self._units, other._units) |
| 1021 |
elif no_offset_units_self == len(self._units) == 1: |
| 1022 |
new_self = self.to_root_units() |
| 1023 |
|
| 1024 |
no_offset_units_other = len(other._get_non_multiplicative_units()) |
| 1025 |
|
| 1026 |
if not other._ok_for_muldiv(no_offset_units_other): |
| 1027 |
raise OffsetUnitCalculusError(self._units, other._units) |
| 1028 |
elif no_offset_units_other == len(other._units) == 1: |
| 1029 |
other = other.to_root_units() |
| 1030 |
|
| 1031 |
magnitude = magnitude_op(new_self._magnitude, other._magnitude) |
| 1032 |
units = units_op(new_self._units, other._units) |
| 1033 |
|
| 1034 |
return self.__class__(magnitude, units) |
| 1035 |
|
| 1036 |
def __imul__(self, other): |
| 1037 |
if is_duck_array_type(type(self._magnitude)): |
| 1038 |
return self._imul_div(other, operator.imul) |
| 1039 |
|
| 1040 |
return self._mul_div(other, operator.mul) |
| 1041 |
|
| 1042 |
def __mul__(self, other): |
| 1043 |
return self._mul_div(other, operator.mul) |
| 1044 |
|
| 1045 |
__rmul__ = __mul__ |
| 1046 |
|
| 1047 |
def __matmul__(self, other): |
| 1048 |
return np.matmul(self, other) |
| 1049 |
|
| 1050 |
__rmatmul__ = __matmul__ |
| 1051 |
|
| 1052 |
def _truedivide_cast_int(self, a, b): |
| 1053 |
t = self._REGISTRY.non_int_type |
| 1054 |
if isinstance(a, int): |
| 1055 |
a = t(a) |
| 1056 |
if isinstance(b, int): |
| 1057 |
b = t(b) |
| 1058 |
return operator.truediv(a, b) |
| 1059 |
|
| 1060 |
def __itruediv__(self, other): |
| 1061 |
if is_duck_array_type(type(self._magnitude)): |
| 1062 |
return self._imul_div(other, operator.itruediv) |
| 1063 |
|
| 1064 |
return self._mul_div(other, operator.truediv) |
| 1065 |
|
| 1066 |
def __truediv__(self, other): |
| 1067 |
if isinstance(self.m, int) or isinstance(getattr(other, "m", None), int): |
| 1068 |
return self._mul_div(other, self._truedivide_cast_int, operator.truediv) |
| 1069 |
return self._mul_div(other, operator.truediv) |
| 1070 |
|
| 1071 |
def __rtruediv__(self, other): |
| 1072 |
try: |
| 1073 |
other_magnitude = _to_magnitude( |
| 1074 |
other, self.force_ndarray, self.force_ndarray_like |
| 1075 |
) |
| 1076 |
except PintTypeError: |
| 1077 |
raise |
| 1078 |
except TypeError: |
| 1079 |
return NotImplemented |
| 1080 |
|
| 1081 |
no_offset_units_self = len(self._get_non_multiplicative_units()) |
| 1082 |
if not self._ok_for_muldiv(no_offset_units_self): |
| 1083 |
raise OffsetUnitCalculusError(self._units, "") |
| 1084 |
elif no_offset_units_self == len(self._units) == 1: |
| 1085 |
self = self.to_root_units() |
| 1086 |
|
| 1087 |
return self.__class__(other_magnitude / self._magnitude, 1 / self._units) |
| 1088 |
|
| 1089 |
__div__ = __truediv__ |
| 1090 |
__rdiv__ = __rtruediv__ |
| 1091 |
__idiv__ = __itruediv__ |
| 1092 |
|
| 1093 |
def __ifloordiv__(self, other): |
| 1094 |
if self._check(other): |
| 1095 |
self._magnitude //= other.to(self._units)._magnitude |
| 1096 |
elif self.dimensionless: |
| 1097 |
self._magnitude = self.to("")._magnitude // other |
| 1098 |
else: |
| 1099 |
raise DimensionalityError(self._units, "dimensionless") |
| 1100 |
self._units = self.UnitsContainer({}) |
| 1101 |
return self |
| 1102 |
|
| 1103 |
@check_implemented |
| 1104 |
def __floordiv__(self, other): |
| 1105 |
if self._check(other): |
| 1106 |
magnitude = self._magnitude // other.to(self._units)._magnitude |
| 1107 |
elif self.dimensionless: |
| 1108 |
magnitude = self.to("")._magnitude // other |
| 1109 |
else: |
| 1110 |
raise DimensionalityError(self._units, "dimensionless") |
| 1111 |
return self.__class__(magnitude, self.UnitsContainer({})) |
| 1112 |
|
| 1113 |
@check_implemented |
| 1114 |
def __rfloordiv__(self, other): |
| 1115 |
if self._check(other): |
| 1116 |
magnitude = other._magnitude // self.to(other._units)._magnitude |
| 1117 |
elif self.dimensionless: |
| 1118 |
magnitude = other // self.to("")._magnitude |
| 1119 |
else: |
| 1120 |
raise DimensionalityError(self._units, "dimensionless") |
| 1121 |
return self.__class__(magnitude, self.UnitsContainer({})) |
| 1122 |
|
| 1123 |
@check_implemented |
| 1124 |
def __imod__(self, other): |
| 1125 |
if not self._check(other): |
| 1126 |
other = self.__class__(other, self.UnitsContainer({})) |
| 1127 |
self._magnitude %= other.to(self._units)._magnitude |
| 1128 |
return self |
| 1129 |
|
| 1130 |
@check_implemented |
| 1131 |
def __mod__(self, other): |
| 1132 |
if not self._check(other): |
| 1133 |
other = self.__class__(other, self.UnitsContainer({})) |
| 1134 |
magnitude = self._magnitude % other.to(self._units)._magnitude |
| 1135 |
return self.__class__(magnitude, self._units) |
| 1136 |
|
| 1137 |
@check_implemented |
| 1138 |
def __rmod__(self, other): |
| 1139 |
if self._check(other): |
| 1140 |
magnitude = other._magnitude % self.to(other._units)._magnitude |
| 1141 |
return self.__class__(magnitude, other._units) |
| 1142 |
elif self.dimensionless: |
| 1143 |
magnitude = other % self.to("")._magnitude |
| 1144 |
return self.__class__(magnitude, self.UnitsContainer({})) |
| 1145 |
else: |
| 1146 |
raise DimensionalityError(self._units, "dimensionless") |
| 1147 |
|
| 1148 |
@check_implemented |
| 1149 |
def __divmod__(self, other): |
| 1150 |
if not self._check(other): |
| 1151 |
other = self.__class__(other, self.UnitsContainer({})) |
| 1152 |
q, r = divmod(self._magnitude, other.to(self._units)._magnitude) |
| 1153 |
return ( |
| 1154 |
self.__class__(q, self.UnitsContainer({})), |
| 1155 |
self.__class__(r, self._units), |
| 1156 |
) |
| 1157 |
|
| 1158 |
@check_implemented |
| 1159 |
def __rdivmod__(self, other): |
| 1160 |
if self._check(other): |
| 1161 |
q, r = divmod(other._magnitude, self.to(other._units)._magnitude) |
| 1162 |
unit = other._units |
| 1163 |
elif self.dimensionless: |
| 1164 |
q, r = divmod(other, self.to("")._magnitude) |
| 1165 |
unit = self.UnitsContainer({}) |
| 1166 |
else: |
| 1167 |
raise DimensionalityError(self._units, "dimensionless") |
| 1168 |
return (self.__class__(q, self.UnitsContainer({})), self.__class__(r, unit)) |
| 1169 |
|
| 1170 |
@check_implemented |
| 1171 |
def __ipow__(self, other): |
| 1172 |
if not is_duck_array_type(type(self._magnitude)): |
| 1173 |
return self.__pow__(other) |
| 1174 |
|
| 1175 |
try: |
| 1176 |
_to_magnitude(other, self.force_ndarray, self.force_ndarray_like) |
| 1177 |
except PintTypeError: |
| 1178 |
raise |
| 1179 |
except TypeError: |
| 1180 |
return NotImplemented |
| 1181 |
else: |
| 1182 |
if not self._ok_for_muldiv: |
| 1183 |
raise OffsetUnitCalculusError(self._units) |
| 1184 |
|
| 1185 |
if is_duck_array_type(type(getattr(other, "_magnitude", other))): |
| 1186 |
# arrays are refused as exponent, because they would create |
| 1187 |
# len(array) quantities of len(set(array)) different units |
| 1188 |
# unless the plain is dimensionless. Ensure dimensionless |
| 1189 |
# units are reduced to "dimensionless". |
| 1190 |
# Note: this will strip Units of degrees or radians from PlainQuantity |
| 1191 |
if self.dimensionless: |
| 1192 |
if getattr(other, "dimensionless", False): |
| 1193 |
self._magnitude = self.m_as("") ** other.m_as("") |
| 1194 |
self._units = self.UnitsContainer() |
| 1195 |
return self |
| 1196 |
elif not getattr(other, "dimensionless", True): |
| 1197 |
raise DimensionalityError(other._units, "dimensionless") |
| 1198 |
else: |
| 1199 |
self._magnitude = self.m_as("") ** other |
| 1200 |
self._units = self.UnitsContainer() |
| 1201 |
return self |
| 1202 |
elif np.size(other) > 1: |
| 1203 |
raise DimensionalityError( |
| 1204 |
self._units, |
| 1205 |
"dimensionless", |
| 1206 |
extra_msg=". PlainQuantity array exponents are only allowed if the " |
| 1207 |
"plain is dimensionless", |
| 1208 |
) |
| 1209 |
|
| 1210 |
if other == 1: |
| 1211 |
return self |
| 1212 |
elif other == 0: |
| 1213 |
self._units = self.UnitsContainer() |
| 1214 |
else: |
| 1215 |
if not self._is_multiplicative: |
| 1216 |
if self._REGISTRY.autoconvert_offset_to_baseunit: |
| 1217 |
self.ito_base_units() |
| 1218 |
else: |
| 1219 |
raise OffsetUnitCalculusError(self._units) |
| 1220 |
|
| 1221 |
if getattr(other, "dimensionless", False): |
| 1222 |
other = other.to_base_units().magnitude |
| 1223 |
self._units **= other |
| 1224 |
elif not getattr(other, "dimensionless", True): |
| 1225 |
raise DimensionalityError(self._units, "dimensionless") |
| 1226 |
else: |
| 1227 |
self._units **= other |
| 1228 |
|
| 1229 |
self._magnitude **= _to_magnitude( |
| 1230 |
other, self.force_ndarray, self.force_ndarray_like |
| 1231 |
) |
| 1232 |
return self |
| 1233 |
|
| 1234 |
@check_implemented |
| 1235 |
def __pow__(self, other) -> PlainQuantity[MagnitudeT]: |
| 1236 |
try: |
| 1237 |
_to_magnitude(other, self.force_ndarray, self.force_ndarray_like) |
| 1238 |
except PintTypeError: |
| 1239 |
raise |
| 1240 |
except TypeError: |
| 1241 |
return NotImplemented |
| 1242 |
else: |
| 1243 |
if not self._ok_for_muldiv: |
| 1244 |
raise OffsetUnitCalculusError(self._units) |
| 1245 |
|
| 1246 |
if is_duck_array_type(type(getattr(other, "_magnitude", other))): |
| 1247 |
# arrays are refused as exponent, because they would create |
| 1248 |
# len(array) quantities of len(set(array)) different units |
| 1249 |
# unless the plain is dimensionless. |
| 1250 |
# Note: this will strip Units of degrees or radians from PlainQuantity |
| 1251 |
if self.dimensionless: |
| 1252 |
if getattr(other, "dimensionless", False): |
| 1253 |
return self.__class__( |
| 1254 |
self._convert_magnitude_not_inplace(self.UnitsContainer()) |
| 1255 |
** other.m_as("") |
| 1256 |
) |
| 1257 |
elif not getattr(other, "dimensionless", True): |
| 1258 |
raise DimensionalityError(other._units, "dimensionless") |
| 1259 |
else: |
| 1260 |
return self.__class__( |
| 1261 |
self._convert_magnitude_not_inplace(self.UnitsContainer()) |
| 1262 |
** other |
| 1263 |
) |
| 1264 |
elif np.size(other) > 1: |
| 1265 |
raise DimensionalityError( |
| 1266 |
self._units, |
| 1267 |
"dimensionless", |
| 1268 |
extra_msg=". PlainQuantity array exponents are only allowed if the " |
| 1269 |
"plain is dimensionless", |
| 1270 |
) |
| 1271 |
|
| 1272 |
new_self = self |
| 1273 |
if other == 1: |
| 1274 |
return self |
| 1275 |
elif other == 0: |
| 1276 |
exponent = 0 |
| 1277 |
units = self.UnitsContainer() |
| 1278 |
else: |
| 1279 |
if not self._is_multiplicative: |
| 1280 |
if self._REGISTRY.autoconvert_offset_to_baseunit: |
| 1281 |
new_self = self.to_root_units() |
| 1282 |
else: |
| 1283 |
raise OffsetUnitCalculusError(self._units) |
| 1284 |
|
| 1285 |
if getattr(other, "dimensionless", False): |
| 1286 |
exponent = other.to_root_units().magnitude |
| 1287 |
units = new_self._units**exponent |
| 1288 |
elif not getattr(other, "dimensionless", True): |
| 1289 |
raise DimensionalityError(other._units, "dimensionless") |
| 1290 |
else: |
| 1291 |
exponent = _to_magnitude( |
| 1292 |
other, force_ndarray=False, force_ndarray_like=False |
| 1293 |
) |
| 1294 |
units = new_self._units**exponent |
| 1295 |
|
| 1296 |
magnitude = new_self._magnitude**exponent |
| 1297 |
return self.__class__(magnitude, units) |
| 1298 |
|
| 1299 |
@check_implemented |
| 1300 |
def __rpow__(self, other) -> PlainQuantity[MagnitudeT]: |
| 1301 |
try: |
| 1302 |
_to_magnitude(other, self.force_ndarray, self.force_ndarray_like) |
| 1303 |
except PintTypeError: |
| 1304 |
raise |
| 1305 |
except TypeError: |
| 1306 |
return NotImplemented |
| 1307 |
else: |
| 1308 |
if not self.dimensionless: |
| 1309 |
raise DimensionalityError(self._units, "dimensionless") |
| 1310 |
new_self = self.to_root_units() |
| 1311 |
return other**new_self._magnitude |
| 1312 |
|
| 1313 |
def __abs__(self) -> PlainQuantity[MagnitudeT]: |
| 1314 |
return self.__class__(abs(self._magnitude), self._units) |
| 1315 |
|
| 1316 |
def __round__(self, ndigits: int | None = None) -> PlainQuantity[int]: |
| 1317 |
return self.__class__(round(self._magnitude, ndigits), self._units) |
| 1318 |
|
| 1319 |
def __pos__(self) -> PlainQuantity[MagnitudeT]: |
| 1320 |
return self.__class__(operator.pos(self._magnitude), self._units) |
| 1321 |
|
| 1322 |
def __neg__(self) -> PlainQuantity[MagnitudeT]: |
| 1323 |
return self.__class__(operator.neg(self._magnitude), self._units) |
| 1324 |
|
| 1325 |
@check_implemented |
| 1326 |
def __eq__(self, other): |
| 1327 |
def bool_result(value): |
| 1328 |
nonlocal other |
| 1329 |
|
| 1330 |
if not is_duck_array_type(type(self._magnitude)): |
| 1331 |
return value |
| 1332 |
|
| 1333 |
if isinstance(other, PlainQuantity): |
| 1334 |
other = other._magnitude |
| 1335 |
|
| 1336 |
template, _ = np.broadcast_arrays(self._magnitude, other) |
| 1337 |
return np.full_like(template, fill_value=value, dtype=np.bool_) |
| 1338 |
|
| 1339 |
# We compare to the plain class of PlainQuantity because |
| 1340 |
# each PlainQuantity class is unique. |
| 1341 |
if not isinstance(other, PlainQuantity): |
| 1342 |
if other is None: |
| 1343 |
# A loop in pandas-dev/pandas/core/common.py(86)consensus_name_attr() can result in OTHER being None |
| 1344 |
return bool_result(False) |
| 1345 |
if zero_or_nan(other, True): |
| 1346 |
# Handle the special case in which we compare to zero or NaN |
| 1347 |
# (or an array of zeros or NaNs) |
| 1348 |
if self._is_multiplicative: |
| 1349 |
# compare magnitude |
| 1350 |
return eq(self._magnitude, other, False) |
| 1351 |
else: |
| 1352 |
# compare the magnitude after converting the |
| 1353 |
# non-multiplicative quantity to plain units |
| 1354 |
if self._REGISTRY.autoconvert_offset_to_baseunit: |
| 1355 |
return eq(self.to_base_units()._magnitude, other, False) |
| 1356 |
else: |
| 1357 |
raise OffsetUnitCalculusError(self._units) |
| 1358 |
|
| 1359 |
if self.dimensionless: |
| 1360 |
return eq( |
| 1361 |
self._convert_magnitude_not_inplace(self.UnitsContainer()), |
| 1362 |
other, |
| 1363 |
False, |
| 1364 |
) |
| 1365 |
|
| 1366 |
return bool_result(False) |
| 1367 |
|
| 1368 |
# TODO: this might be expensive. Do we even need it? |
| 1369 |
if eq(self._magnitude, 0, True) and eq(other._magnitude, 0, True): |
| 1370 |
return bool_result(self.dimensionality == other.dimensionality) |
| 1371 |
|
| 1372 |
if self._units == other._units: |
| 1373 |
return eq(self._magnitude, other._magnitude, False) |
| 1374 |
|
| 1375 |
try: |
| 1376 |
return eq( |
| 1377 |
self._convert_magnitude_not_inplace(other._units), |
| 1378 |
other._magnitude, |
| 1379 |
False, |
| 1380 |
) |
| 1381 |
except DimensionalityError: |
| 1382 |
return bool_result(False) |
| 1383 |
|
| 1384 |
@check_implemented |
| 1385 |
def __ne__(self, other): |
| 1386 |
out = self.__eq__(other) |
| 1387 |
if is_duck_array_type(type(out)): |
| 1388 |
return np.logical_not(out) |
| 1389 |
return not out |
| 1390 |
|
| 1391 |
@check_implemented |
| 1392 |
def compare(self, other, op): |
| 1393 |
if not isinstance(other, PlainQuantity): |
| 1394 |
if self.dimensionless: |
| 1395 |
return op( |
| 1396 |
self._convert_magnitude_not_inplace(self.UnitsContainer()), other |
| 1397 |
) |
| 1398 |
elif zero_or_nan(other, True): |
| 1399 |
# Handle the special case in which we compare to zero or NaN |
| 1400 |
# (or an array of zeros or NaNs) |
| 1401 |
if self._is_multiplicative: |
| 1402 |
# compare magnitude |
| 1403 |
return op(self._magnitude, other) |
| 1404 |
else: |
| 1405 |
# compare the magnitude after converting the |
| 1406 |
# non-multiplicative quantity to plain units |
| 1407 |
if self._REGISTRY.autoconvert_offset_to_baseunit: |
| 1408 |
return op(self.to_base_units()._magnitude, other) |
| 1409 |
else: |
| 1410 |
raise OffsetUnitCalculusError(self._units) |
| 1411 |
else: |
| 1412 |
raise ValueError(f"Cannot compare PlainQuantity and {type(other)}") |
| 1413 |
|
| 1414 |
# Registry equality check based on util.SharedRegistryObject |
| 1415 |
if self._REGISTRY is not other._REGISTRY: |
| 1416 |
mess = "Cannot operate with {} and {} of different registries." |
| 1417 |
raise ValueError( |
| 1418 |
mess.format(self.__class__.__name__, other.__class__.__name__) |
| 1419 |
) |
| 1420 |
|
| 1421 |
if self._units == other._units: |
| 1422 |
return op(self._magnitude, other._magnitude) |
| 1423 |
if self.dimensionality != other.dimensionality: |
| 1424 |
raise DimensionalityError( |
| 1425 |
self._units, other._units, self.dimensionality, other.dimensionality |
| 1426 |
) |
| 1427 |
return op(self.to_root_units().magnitude, other.to_root_units().magnitude) |
| 1428 |
|
| 1429 |
__lt__ = lambda self, other: self.compare(other, op=operator.lt) |
| 1430 |
__le__ = lambda self, other: self.compare(other, op=operator.le) |
| 1431 |
__ge__ = lambda self, other: self.compare(other, op=operator.ge) |
| 1432 |
__gt__ = lambda self, other: self.compare(other, op=operator.gt) |
| 1433 |
|
| 1434 |
def __bool__(self) -> bool: |
| 1435 |
# Only cast when non-ambiguous (when multiplicative unit) |
| 1436 |
if self._is_multiplicative: |
| 1437 |
return bool(self._magnitude) |
| 1438 |
else: |
| 1439 |
raise ValueError( |
| 1440 |
"Boolean value of PlainQuantity with offset unit is ambiguous." |
| 1441 |
) |
| 1442 |
|
| 1443 |
__nonzero__ = __bool__ |
| 1444 |
|
| 1445 |
def tolist(self): |
| 1446 |
units = self._units |
| 1447 |
|
| 1448 |
try: |
| 1449 |
values = self._magnitude.tolist() |
| 1450 |
if not isinstance(values, list): |
| 1451 |
return self.__class__(values, units) |
| 1452 |
|
| 1453 |
return [ |
| 1454 |
self.__class__(value, units).tolist() |
| 1455 |
if isinstance(value, list) |
| 1456 |
else self.__class__(value, units) |
| 1457 |
for value in self._magnitude.tolist() |
| 1458 |
] |
| 1459 |
except AttributeError: |
| 1460 |
raise AttributeError( |
| 1461 |
f"Magnitude '{type(self._magnitude).__name__}' does not support tolist." |
| 1462 |
) |
| 1463 |
|
| 1464 |
def _get_unit_definition(self, unit: str) -> UnitDefinition: |
| 1465 |
try: |
| 1466 |
return self._REGISTRY._units[unit] |
| 1467 |
except KeyError: |
| 1468 |
# pint#1062: The __init__ method of this object added the unit to |
| 1469 |
# UnitRegistry._units (e.g. units with prefix are added on the fly the |
| 1470 |
# first time they're used) but the key was later removed, e.g. because |
| 1471 |
# a Context with unit redefinitions was deactivated. |
| 1472 |
self._REGISTRY.parse_units(unit) |
| 1473 |
return self._REGISTRY._units[unit] |
| 1474 |
|
| 1475 |
# methods/properties that help for math operations with offset units |
| 1476 |
@property |
| 1477 |
def _is_multiplicative(self) -> bool: |
| 1478 |
"""Check if the PlainQuantity object has only multiplicative units.""" |
| 1479 |
return True |
| 1480 |
|
| 1481 |
def _get_non_multiplicative_units(self) -> list[str]: |
| 1482 |
"""Return a list of the of non-multiplicative units of the PlainQuantity object.""" |
| 1483 |
return [] |
| 1484 |
|
| 1485 |
@property |
| 1486 |
def _is_logarithmic(self) -> bool: |
| 1487 |
"""Check if the PlainQuantity object has logarithmic units.""" |
| 1488 |
return False |
| 1489 |
|
| 1490 |
def _get_delta_units(self) -> list[str]: |
| 1491 |
"""Return list of delta units ot the PlainQuantity object.""" |
| 1492 |
return [u for u in self._units if u.startswith("delta_")] |
| 1493 |
|
| 1494 |
def _has_compatible_delta(self, unit: str) -> bool: |
| 1495 |
""" "Check if PlainQuantity object has a delta_unit that is compatible with unit""" |
| 1496 |
return False |
| 1497 |
|
| 1498 |
def _ok_for_muldiv(self, no_offset_units=None) -> bool: |
| 1499 |
return True |
| 1500 |
|
| 1501 |
def to_timedelta(self: PlainQuantity[MagnitudeT]) -> datetime.timedelta: |
| 1502 |
return datetime.timedelta(microseconds=self.to("microseconds").magnitude) |
| 1503 |
|
| 1504 |
# We put this last to avoid overriding UnitsContainer |
| 1505 |
# and I do not want to rename it. |
| 1506 |
# TODO: Maybe in the future we need to change it to a more meaningful |
| 1507 |
# non-colliding name. |
| 1508 |
|
| 1509 |
@property |
| 1510 |
def UnitsContainer(self) -> Callable[..., UnitsContainerT]: |
| 1511 |
return self._REGISTRY.UnitsContainer |