Debian Codegraph @

pint/facets/numpy/numpy_func.py

raw
1 """
2 pint.facets.numpy.numpy_func
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 warnings
12 from inspect import signature
13 from itertools import chain
14
15 from ...compat import is_upcast_type, np, zero_or_nan
16 from ...errors import DimensionalityError, OffsetUnitCalculusError, UnitStrippedWarning
17 from ...util import iterable, sized
18
19 HANDLED_UFUNCS = {}
20 HANDLED_FUNCTIONS = {}
21
22
23 # Shared Implementation Utilities
24
25
26 def _is_quantity(obj):
27 """Test for _units and _magnitude attrs.
28
29 This is done in place of isinstance(Quantity, arg), which would cause a circular import.
30
31 Parameters
32 ----------
33 obj : Object
34
35
36 Returns
37 -------
38 bool
39 """
40 return hasattr(obj, "_units") and hasattr(obj, "_magnitude")
41
42
43 def _is_sequence_with_quantity_elements(obj):
44 """Test for sequences of quantities.
45
46 Parameters
47 ----------
48 obj : object
49
50
51 Returns
52 -------
53 True if obj is a sequence and at least one element is a Quantity; False otherwise
54 """
55 if np is not None and isinstance(obj, np.ndarray) and not obj.dtype.hasobject:
56 # If obj is a numpy array, avoid looping on all elements
57 # if dtype does not have objects
58 return False
59 return (
60 iterable(obj)
61 and sized(obj)
62 and not isinstance(obj, str)
63 and any(_is_quantity(item) for item in obj)
64 )
65
66
67 def _get_first_input_units(args, kwargs=None):
68 """Obtain the first valid unit from a collection of args and kwargs."""
69 kwargs = kwargs or {}
70 for arg in chain(args, kwargs.values()):
71 if _is_quantity(arg):
72 return arg.units
73 elif _is_sequence_with_quantity_elements(arg):
74 return next(arg_i.units for arg_i in arg if _is_quantity(arg_i))
75 raise TypeError("Expected at least one Quantity; found none")
76
77
78 def convert_arg(arg, pre_calc_units):
79 """Convert quantities and sequences of quantities to pre_calc_units and strip units.
80
81 Helper function for convert_to_consistent_units. pre_calc_units must be given as a
82 pint Unit or None.
83 """
84 if isinstance(arg, bool):
85 return arg
86 if pre_calc_units is not None:
87 if _is_quantity(arg):
88 return arg.m_as(pre_calc_units)
89 elif _is_sequence_with_quantity_elements(arg):
90 return [convert_arg(item, pre_calc_units) for item in arg]
91 elif arg is not None:
92 if pre_calc_units.dimensionless:
93 return pre_calc_units._REGISTRY.Quantity(arg).m_as(pre_calc_units)
94 elif not _is_quantity(arg) and zero_or_nan(arg, True):
95 return arg
96 else:
97 raise DimensionalityError("dimensionless", pre_calc_units)
98 elif _is_quantity(arg):
99 return arg.m
100 elif _is_sequence_with_quantity_elements(arg):
101 return [convert_arg(item, pre_calc_units) for item in arg]
102 return arg
103
104
105 def convert_to_consistent_units(*args, pre_calc_units=None, **kwargs):
106 """Prepare args and kwargs for wrapping by unit conversion and stripping.
107
108 If pre_calc_units is not None, takes the args and kwargs for a NumPy function and
109 converts any Quantity or Sequence of Quantities into the units of the first
110 Quantity/Sequence of Quantities and returns the magnitudes. Other args/kwargs (except booleans) are
111 treated as dimensionless Quantities. If pre_calc_units is None, units are simply
112 stripped.
113 """
114 return (
115 tuple(convert_arg(arg, pre_calc_units=pre_calc_units) for arg in args),
116 {
117 key: convert_arg(arg, pre_calc_units=pre_calc_units)
118 for key, arg in kwargs.items()
119 },
120 )
121
122
123 def unwrap_and_wrap_consistent_units(*args):
124 """Strip units from args while providing a rewrapping function.
125
126 Returns the given args as parsed by convert_to_consistent_units assuming units of
127 first arg with units, along with a wrapper to restore that unit to the output.
128
129 """
130 if all(not _is_quantity(arg) for arg in args):
131 return args, lambda x: x
132
133 first_input_units = _get_first_input_units(args)
134 args, _ = convert_to_consistent_units(*args, pre_calc_units=first_input_units)
135 return (
136 args,
137 lambda value: first_input_units._REGISTRY.Quantity(value, first_input_units),
138 )
139
140
141 def get_op_output_unit(unit_op, first_input_units, all_args=None, size=None):
142 """Determine resulting unit from given operation.
143
144 Options for `unit_op`:
145
146 - "sum": `first_input_units`, unless non-multiplicative, which raises
147 OffsetUnitCalculusError
148 - "mul": product of all units in `all_args`
149 - "delta": `first_input_units`, unless non-multiplicative, which uses delta version
150 - "delta,div": like "delta", but divided by all units in `all_args` except the first
151 - "div": unit of first argument in `all_args` (or dimensionless if not a Quantity) divided
152 by all following units
153 - "variance": square of `first_input_units`, unless non-multiplicative, which raises
154 OffsetUnitCalculusError
155 - "square": square of `first_input_units`
156 - "sqrt": square root of `first_input_units`
157 - "reciprocal": reciprocal of `first_input_units`
158 - "size": `first_input_units` raised to the power of `size`
159 - "invdiv": inverse of `div`, product of all following units divided by first argument unit
160
161 Parameters
162 ----------
163 unit_op :
164
165 first_input_units :
166
167 all_args :
168 (Default value = None)
169 size :
170 (Default value = None)
171
172 Returns
173 -------
174
175 """
176 all_args = all_args or []
177
178 if unit_op == "sum":
179 result_unit = (1 * first_input_units + 1 * first_input_units).units
180 elif unit_op == "mul":
181 product = first_input_units._REGISTRY.parse_units("")
182 for x in all_args:
183 if hasattr(x, "units"):
184 product *= x.units
185 result_unit = product
186 elif unit_op == "delta":
187 result_unit = (1 * first_input_units - 1 * first_input_units).units
188 elif unit_op == "delta,div":
189 product = (1 * first_input_units - 1 * first_input_units).units
190 for x in all_args[1:]:
191 if hasattr(x, "units"):
192 product /= x.units
193 result_unit = product
194 elif unit_op == "div":
195 # Start with first arg in numerator, all others in denominator
196 product = getattr(
197 all_args[0], "units", first_input_units._REGISTRY.parse_units("")
198 )
199 for x in all_args[1:]:
200 if hasattr(x, "units"):
201 product /= x.units
202 result_unit = product
203 elif unit_op == "variance":
204 result_unit = ((1 * first_input_units - 1 * first_input_units) ** 2).units
205 elif unit_op == "square":
206 result_unit = first_input_units**2
207 elif unit_op == "sqrt":
208 result_unit = first_input_units**0.5
209 elif unit_op == "cbrt":
210 result_unit = first_input_units ** (1 / 3)
211 elif unit_op == "reciprocal":
212 result_unit = first_input_units**-1
213 elif unit_op == "size":
214 if size is None:
215 raise ValueError('size argument must be given when unit_op=="size"')
216 result_unit = first_input_units**size
217 elif unit_op == "invdiv":
218 # Start with first arg in numerator, all others in denominator
219 product = getattr(
220 all_args[0], "units", first_input_units._REGISTRY.parse_units("")
221 )
222 for x in all_args[1:]:
223 if hasattr(x, "units"):
224 product /= x.units
225 result_unit = product**-1
226 else:
227 raise ValueError(f"Output unit method {unit_op} not understood")
228
229 return result_unit
230
231
232 def implements(numpy_func_string, func_type):
233 """Register an __array_function__/__array_ufunc__ implementation for Quantity
234 objects.
235
236 """
237
238 def decorator(func):
239 if func_type == "function":
240 HANDLED_FUNCTIONS[numpy_func_string] = func
241 elif func_type == "ufunc":
242 HANDLED_UFUNCS[numpy_func_string] = func
243 else:
244 raise ValueError(f"Invalid func_type {func_type}")
245 return func
246
247 return decorator
248
249
250 def implement_func(func_type, func_str, input_units=None, output_unit=None):
251 """Add default-behavior NumPy function/ufunc to the handled list.
252
253 Parameters
254 ----------
255 func_type : str
256 "function" for NumPy functions, "ufunc" for NumPy ufuncs
257 func_str : str
258 String representing the name of the NumPy function/ufunc to add
259 input_units : pint.Unit or str or None
260 Parameter to control how the function downcasts to magnitudes of arguments. If
261 `pint.Unit`, converts all args and kwargs to this unit before downcasting to
262 magnitude. If "all_consistent", converts all args and kwargs to the unit of the
263 first Quantity in args and kwargs before downcasting to magnitude. If some
264 other string, the string is parsed as a unit, and all args and kwargs are
265 converted to that unit. If None, units are stripped without conversion.
266 output_unit : pint.Unit or str or None
267 Parameter to control the unit of the output. If `pint.Unit`, output is wrapped
268 with that unit. If "match_input", output is wrapped with the unit of the first
269 Quantity in args and kwargs. If a string representing a unit operation defined
270 in `get_op_output_unit`, output is wrapped by the unit determined by
271 `get_op_output_unit`. If some other string, the string is parsed as a unit,
272 which becomes the unit of the output. If None, the bare magnitude is returned.
273
274
275 """
276 # If NumPy is not available, do not attempt implement that which does not exist
277 if np is None:
278 return
279
280 # Handle functions in submodules
281 func_str_split = func_str.split(".")
282 func = getattr(np, func_str_split[0], None)
283 # If the function is not available, do not attempt to implement it
284 if func is None:
285 return
286 for func_str_piece in func_str_split[1:]:
287 func = getattr(func, func_str_piece, None)
288 if func is None:
289 return
290
291 @implements(func_str, func_type)
292 def implementation(*args, **kwargs):
293 if func_str in ["multiply", "true_divide", "divide", "floor_divide"] and any(
294 [
295 not _is_quantity(arg) and _is_sequence_with_quantity_elements(arg)
296 for arg in args
297 ]
298 ):
299 # the sequence may contain different units, so fall back to element-wise
300 return np.array(
301 [func(*func_args) for func_args in zip(*args)], dtype=object
302 )
303
304 first_input_units = _get_first_input_units(args, kwargs)
305 if input_units == "all_consistent":
306 # Match all input args/kwargs to same units
307 stripped_args, stripped_kwargs = convert_to_consistent_units(
308 *args, pre_calc_units=first_input_units, **kwargs
309 )
310 else:
311 if isinstance(input_units, str):
312 # Conversion requires Unit, not str
313 pre_calc_units = first_input_units._REGISTRY.parse_units(input_units)
314 else:
315 pre_calc_units = input_units
316
317 # Match all input args/kwargs to input_units, or if input_units is None,
318 # simply strip units
319 stripped_args, stripped_kwargs = convert_to_consistent_units(
320 *args, pre_calc_units=pre_calc_units, **kwargs
321 )
322
323 # Determine result through plain numpy function on stripped arguments
324 result_magnitude = func(*stripped_args, **stripped_kwargs)
325
326 if output_unit is None:
327 # Short circuit and return magnitude alone
328 return result_magnitude
329 elif output_unit == "match_input":
330 result_unit = first_input_units
331 elif output_unit in (
332 "sum",
333 "mul",
334 "delta",
335 "delta,div",
336 "div",
337 "invdiv",
338 "variance",
339 "square",
340 "sqrt",
341 "cbrt",
342 "reciprocal",
343 "size",
344 ):
345 result_unit = get_op_output_unit(
346 output_unit, first_input_units, tuple(chain(args, kwargs.values()))
347 )
348 else:
349 result_unit = output_unit
350
351 return first_input_units._REGISTRY.Quantity(result_magnitude, result_unit)
352
353
354 """
355 Define ufunc behavior collections.
356
357 - `strip_unit_input_output_ufuncs`: units should be ignored on both input and output
358 - `matching_input_bare_output_ufuncs`: inputs are converted to matching units, but
359 outputs are returned as-is
360 - `matching_input_set_units_output_ufuncs`: inputs are converted to matching units, and
361 the output units are as set by the dict value
362 - `set_units_ufuncs`: dict values are specified as (in_unit, out_unit), so that inputs
363 are converted to in_unit before having magnitude passed to NumPy ufunc, and outputs
364 are set to have out_unit
365 - `matching_input_copy_units_output_ufuncs`: inputs are converted to matching units, and
366 outputs are set to that unit
367 - `copy_units_output_ufuncs`: input units (except the first) are ignored, and output is
368 set to that of the first input unit
369 - `op_units_output_ufuncs`: determine output unit from input unit as determined by
370 operation (see `get_op_output_unit`)
371 """
372 strip_unit_input_output_ufuncs = ["isnan", "isinf", "isfinite", "signbit", "sign"]
373 matching_input_bare_output_ufuncs = [
374 "equal",
375 "greater",
376 "greater_equal",
377 "less",
378 "less_equal",
379 "not_equal",
380 ]
381 matching_input_set_units_output_ufuncs = {"arctan2": "radian"}
382 set_units_ufuncs = {
383 "cumprod": ("", ""),
384 "arccos": ("", "radian"),
385 "arcsin": ("", "radian"),
386 "arctan": ("", "radian"),
387 "arccosh": ("", "radian"),
388 "arcsinh": ("", "radian"),
389 "arctanh": ("", "radian"),
390 "exp": ("", ""),
391 "expm1": ("", ""),
392 "exp2": ("", ""),
393 "log": ("", ""),
394 "log10": ("", ""),
395 "log1p": ("", ""),
396 "log2": ("", ""),
397 "sin": ("radian", ""),
398 "cos": ("radian", ""),
399 "tan": ("radian", ""),
400 "sinh": ("radian", ""),
401 "cosh": ("radian", ""),
402 "tanh": ("radian", ""),
403 "radians": ("degree", "radian"),
404 "degrees": ("radian", "degree"),
405 "deg2rad": ("degree", "radian"),
406 "rad2deg": ("radian", "degree"),
407 "logaddexp": ("", ""),
408 "logaddexp2": ("", ""),
409 }
410 # TODO (#905 follow-up):
411 # while this matches previous behavior, some of these have optional arguments that
412 # should not be Quantities. This should be fixed, and tests using these optional
413 # arguments should be added.
414 matching_input_copy_units_output_ufuncs = [
415 "compress",
416 "conj",
417 "conjugate",
418 "copy",
419 "diagonal",
420 "max",
421 "mean",
422 "min",
423 "ptp",
424 "ravel",
425 "repeat",
426 "reshape",
427 "round",
428 "squeeze",
429 "swapaxes",
430 "take",
431 "trace",
432 "transpose",
433 "roll",
434 "ceil",
435 "floor",
436 "hypot",
437 "rint",
438 "copysign",
439 "nextafter",
440 "trunc",
441 "absolute",
442 "positive",
443 "negative",
444 "maximum",
445 "minimum",
446 "fabs",
447 ]
448 copy_units_output_ufuncs = ["ldexp", "fmod", "mod", "remainder"]
449 op_units_output_ufuncs = {
450 "var": "variance",
451 "multiply": "mul",
452 "true_divide": "div",
453 "divide": "div",
454 "floor_divide": "div",
455 "sqrt": "sqrt",
456 "cbrt": "cbrt",
457 "square": "square",
458 "reciprocal": "reciprocal",
459 "std": "delta",
460 "sum": "sum",
461 "cumsum": "sum",
462 "matmul": "mul",
463 }
464
465
466 # Perform the standard ufunc implementations based on behavior collections
467
468 for ufunc_str in strip_unit_input_output_ufuncs:
469 # Ignore units
470 implement_func("ufunc", ufunc_str, input_units=None, output_unit=None)
471
472 for ufunc_str in matching_input_bare_output_ufuncs:
473 # Require all inputs to match units, but output plain ndarray/duck array
474 implement_func("ufunc", ufunc_str, input_units="all_consistent", output_unit=None)
475
476 for ufunc_str, out_unit in matching_input_set_units_output_ufuncs.items():
477 # Require all inputs to match units, but output in specified unit
478 implement_func(
479 "ufunc", ufunc_str, input_units="all_consistent", output_unit=out_unit
480 )
481
482 for ufunc_str, (in_unit, out_unit) in set_units_ufuncs.items():
483 # Require inputs in specified unit, and output in specified unit
484 implement_func("ufunc", ufunc_str, input_units=in_unit, output_unit=out_unit)
485
486 for ufunc_str in matching_input_copy_units_output_ufuncs:
487 # Require all inputs to match units, and output as first unit in arguments
488 implement_func(
489 "ufunc", ufunc_str, input_units="all_consistent", output_unit="match_input"
490 )
491
492 for ufunc_str in copy_units_output_ufuncs:
493 # Output as first unit in arguments, but do not convert inputs
494 implement_func("ufunc", ufunc_str, input_units=None, output_unit="match_input")
495
496 for ufunc_str, unit_op in op_units_output_ufuncs.items():
497 implement_func("ufunc", ufunc_str, input_units=None, output_unit=unit_op)
498
499
500 # Define custom ufunc implementations for atypical cases
501
502
503 @implements("modf", "ufunc")
504 def _modf(x, *args, **kwargs):
505 (x,), output_wrap = unwrap_and_wrap_consistent_units(x)
506 return tuple(output_wrap(y) for y in np.modf(x, *args, **kwargs))
507
508
509 @implements("frexp", "ufunc")
510 def _frexp(x, *args, **kwargs):
511 (x,), output_wrap = unwrap_and_wrap_consistent_units(x)
512 mantissa, exponent = np.frexp(x, *args, **kwargs)
513 return output_wrap(mantissa), exponent
514
515
516 @implements("power", "ufunc")
517 def _power(x1, x2):
518 if _is_quantity(x1):
519 return x1**x2
520
521 return x2.__rpow__(x1)
522
523
524 @implements("add", "ufunc")
525 def _add(x1, x2, *args, **kwargs):
526 (x1, x2), output_wrap = unwrap_and_wrap_consistent_units(x1, x2)
527 return output_wrap(np.add(x1, x2, *args, **kwargs))
528
529
530 @implements("subtract", "ufunc")
531 def _subtract(x1, x2, *args, **kwargs):
532 (x1, x2), output_wrap = unwrap_and_wrap_consistent_units(x1, x2)
533 return output_wrap(np.subtract(x1, x2, *args, **kwargs))
534
535
536 # Define custom function implementations
537
538
539 @implements("meshgrid", "function")
540 def _meshgrid(*xi, **kwargs):
541 # Simply need to map input units to onto list of outputs
542 input_units = (x.units for x in xi)
543 res = np.meshgrid(*(x.m for x in xi), **kwargs)
544 return [out * unit for out, unit in zip(res, input_units)]
545
546
547 @implements("full_like", "function")
548 def _full_like(a, fill_value, **kwargs):
549 # Make full_like by multiplying with array from ones_like in a
550 # non-multiplicative-unit-safe way
551 if hasattr(fill_value, "_REGISTRY"):
552 return fill_value._REGISTRY.Quantity(
553 np.ones_like(a, **kwargs) * fill_value.m,
554 fill_value.units,
555 )
556
557 return np.ones_like(a, **kwargs) * fill_value
558
559
560 @implements("interp", "function")
561 def _interp(x, xp, fp, left=None, right=None, period=None):
562 # Need to handle x and y units separately
563 (x, xp, period), _ = unwrap_and_wrap_consistent_units(x, xp, period)
564 (fp, left, right), output_wrap = unwrap_and_wrap_consistent_units(fp, left, right)
565 return output_wrap(np.interp(x, xp, fp, left=left, right=right, period=period))
566
567
568 @implements("where", "function")
569 def _where(condition, *args):
570 if not getattr(condition, "_is_multiplicative", True):
571 raise ValueError(
572 "Invalid units of the condition: Boolean value of Quantity with offset unit is ambiguous."
573 )
574
575 condition = getattr(condition, "magnitude", condition)
576 args, output_wrap = unwrap_and_wrap_consistent_units(*args)
577 return output_wrap(np.where(condition, *args))
578
579
580 @implements("concatenate", "function")
581 def _concatenate(sequence, *args, **kwargs):
582 sequence, output_wrap = unwrap_and_wrap_consistent_units(*sequence)
583 return output_wrap(np.concatenate(sequence, *args, **kwargs))
584
585
586 @implements("stack", "function")
587 def _stack(arrays, *args, **kwargs):
588 arrays, output_wrap = unwrap_and_wrap_consistent_units(*arrays)
589 return output_wrap(np.stack(arrays, *args, **kwargs))
590
591
592 @implements("unwrap", "function")
593 def _unwrap(p, discont=None, axis=-1):
594 # np.unwrap only dispatches over p argument, so assume it is a Quantity
595 discont = np.pi if discont is None else discont
596 return p._REGISTRY.Quantity(np.unwrap(p.m_as("rad"), discont, axis=axis), "rad").to(
597 p.units
598 )
599
600
601 @implements("copyto", "function")
602 def _copyto(dst, src, casting="same_kind", where=True):
603 if _is_quantity(dst):
604 if _is_quantity(src):
605 src = src.m_as(dst.units)
606 np.copyto(dst._magnitude, src, casting=casting, where=where)
607 else:
608 warnings.warn(
609 "The unit of the quantity is stripped when copying to non-quantity",
610 UnitStrippedWarning,
611 stacklevel=2,
612 )
613 np.copyto(dst, src.m, casting=casting, where=where)
614
615
616 @implements("einsum", "function")
617 def _einsum(subscripts, *operands, **kwargs):
618 operand_magnitudes, _ = convert_to_consistent_units(*operands, pre_calc_units=None)
619 output_unit = get_op_output_unit("mul", _get_first_input_units(operands), operands)
620 return np.einsum(subscripts, *operand_magnitudes, **kwargs) * output_unit
621
622
623 @implements("isin", "function")
624 def _isin(element, test_elements, assume_unique=False, invert=False):
625 if not _is_quantity(element):
626 raise ValueError(
627 "Cannot test if unit-aware elements are in not-unit-aware array"
628 )
629
630 if _is_quantity(test_elements):
631 try:
632 test_elements = test_elements.m_as(element.units)
633 except DimensionalityError:
634 # Incompatible unit test elements cannot be in element
635 return np.full(element.shape, False)
636 elif _is_sequence_with_quantity_elements(test_elements):
637 compatible_test_elements = []
638 for test_element in test_elements:
639 if not _is_quantity(test_element):
640 pass
641 try:
642 compatible_test_elements.append(test_element.m_as(element.units))
643 except DimensionalityError:
644 # Incompatible unit test elements cannot be in element, but others in
645 # sequence may
646 pass
647 test_elements = compatible_test_elements
648 else:
649 # Consider non-quantity like dimensionless quantity
650 if not element.dimensionless:
651 # Unit do not match, so all false
652 return np.full(element.shape, False)
653 else:
654 # Convert to units of element
655 element._REGISTRY.Quantity(test_elements).m_as(element.units)
656
657 return np.isin(element.m, test_elements, assume_unique=assume_unique, invert=invert)
658
659
660 @implements("pad", "function")
661 def _pad(array, pad_width, mode="constant", **kwargs):
662 def _recursive_convert(arg, unit):
663 if iterable(arg):
664 return tuple(_recursive_convert(a, unit=unit) for a in arg)
665 elif not _is_quantity(arg):
666 if arg == 0 or np.isnan(arg):
667 arg = unit._REGISTRY.Quantity(arg, unit)
668 else:
669 arg = unit._REGISTRY.Quantity(arg, "dimensionless")
670
671 return arg.m_as(unit)
672
673 # pad only dispatches on array argument, so we know it is a Quantity
674 units = array.units
675
676 # Handle flexible constant_values and end_values, converting to units if Quantity
677 # and ignoring if not
678 for key in ("constant_values", "end_values"):
679 if key in kwargs:
680 kwargs[key] = _recursive_convert(kwargs[key], units)
681
682 return units._REGISTRY.Quantity(
683 np.pad(array._magnitude, pad_width, mode=mode, **kwargs), units
684 )
685
686
687 @implements("any", "function")
688 def _any(a, *args, **kwargs):
689 # Only valid when multiplicative unit/no offset
690 if a._is_multiplicative:
691 return np.any(a._magnitude, *args, **kwargs)
692
693 raise ValueError("Boolean value of Quantity with offset unit is ambiguous.")
694
695
696 @implements("all", "function")
697 def _all(a, *args, **kwargs):
698 # Only valid when multiplicative unit/no offset
699 if a._is_multiplicative:
700 return np.all(a._magnitude, *args, **kwargs)
701 else:
702 raise ValueError("Boolean value of Quantity with offset unit is ambiguous.")
703
704
705 def implement_prod_func(name):
706 if np is None:
707 return
708
709 func = getattr(np, name, None)
710 if func is None:
711 return
712
713 @implements(name, "function")
714 def _prod(a, *args, **kwargs):
715 arg_names = ("axis", "dtype", "out", "keepdims", "initial", "where")
716 all_kwargs = dict(**dict(zip(arg_names, args)), **kwargs)
717 axis = all_kwargs.get("axis", None)
718 where = all_kwargs.get("where", None)
719
720 registry = a.units._REGISTRY
721
722 if axis is not None and where is not None:
723 _, where_ = np.broadcast_arrays(a._magnitude, where)
724 exponents = np.unique(np.sum(where_, axis=axis))
725 if len(exponents) == 1 or (len(exponents) == 2 and 0 in exponents):
726 units = a.units ** np.max(exponents)
727 else:
728 units = registry.dimensionless
729 a = a.to(units)
730 elif axis is not None:
731 units = a.units ** a.shape[axis]
732 elif where is not None:
733 exponent = np.sum(where)
734 units = a.units**exponent
735 else:
736 exponent = (
737 np.sum(np.logical_not(np.isnan(a))) if name == "nanprod" else a.size
738 )
739 units = a.units**exponent
740
741 result = func(a._magnitude, *args, **kwargs)
742
743 return registry.Quantity(result, units)
744
745
746 for name in ("prod", "nanprod"):
747 implement_prod_func(name)
748
749
750 # Handle mutliplicative functions separately to deal with non-multiplicative units
751 def _base_unit_if_needed(a):
752 if a._is_multiplicative:
753 return a
754 else:
755 if a.units._REGISTRY.autoconvert_offset_to_baseunit:
756 return a.to_base_units()
757 else:
758 raise OffsetUnitCalculusError(a.units)
759
760
761 # NP2 Can remove trapz wrapping when we only support numpy>=2
762 @implements("trapz", "function")
763 @implements("trapezoid", "function")
764 def _trapz(y, x=None, dx=1.0, **kwargs):
765 trapezoid = np.trapezoid if hasattr(np, "trapezoid") else np.trapz
766 y = _base_unit_if_needed(y)
767 units = y.units
768 if x is not None:
769 if hasattr(x, "units"):
770 x = _base_unit_if_needed(x)
771 units *= x.units
772 x = x._magnitude
773 ret = trapezoid(y._magnitude, x, **kwargs)
774 else:
775 if hasattr(dx, "units"):
776 dx = _base_unit_if_needed(dx)
777 units *= dx.units
778 dx = dx._magnitude
779 ret = trapezoid(y._magnitude, dx=dx, **kwargs)
780
781 return y.units._REGISTRY.Quantity(ret, units)
782
783
784 @implements("correlate", "function")
785 def _correlate(a, v, mode="valid", **kwargs):
786 a = _base_unit_if_needed(a)
787 v = _base_unit_if_needed(v)
788 units = a.units * v.units
789 ret = np.correlate(a._magnitude, v._magnitude, mode=mode, **kwargs)
790 return a.units._REGISTRY.Quantity(ret, units)
791
792
793 def _dimensionless_if_needed(*args):
794 registry = None
795 for arg in args:
796 if _is_quantity(arg):
797 registry = arg.units._REGISTRY
798 break
799 if registry is None:
800 raise ValueError(
801 "At least one argument must be a Quantity to determine the registry."
802 )
803 new_args = []
804 for arg in args:
805 if _is_quantity(arg):
806 new_args.append(arg)
807 else:
808 new_args.append(registry.Quantity(arg, "dimensionless"))
809 return new_args
810
811
812 def implement_mul_func(func):
813 # If NumPy is not available, do not attempt implement that which does not exist
814 if np is None:
815 return
816 if "." not in func_str:
817 func = getattr(np, func_str, None)
818 else:
819 parts = func_str.split(".")
820 module = np
821 for part in parts[:-1]:
822 module = getattr(module, part, None)
823 func = getattr(module, parts[-1], None)
824
825 # if NumPy does not implement it, do not implement it either
826 if func is None:
827 return
828
829 @implements(func_str, "function")
830 def implementation(a, b, **kwargs):
831 a, b = _dimensionless_if_needed(a, b)
832 a = _base_unit_if_needed(a)
833 b = _base_unit_if_needed(b)
834 units = a.units * b.units
835 mag = func(a._magnitude, b._magnitude, **kwargs)
836 return mag * units
837
838
839 for func_str in (
840 "cross",
841 "dot",
842 "vdot",
843 "inner",
844 "outer",
845 "linalg.outer",
846 "matvec",
847 "vecmat",
848 "tensordot",
849 "linalg.tensordot",
850 ):
851 implement_mul_func(func_str)
852
853
854 # Implement simple matching-unit or stripped-unit functions based on signature
855
856
857 def implement_consistent_units_by_argument(func_str, unit_arguments, wrap_output=True):
858 # If NumPy is not available, do not attempt implement that which does not exist
859 if np is None:
860 return
861
862 if "." not in func_str:
863 func = getattr(np, func_str, None)
864 else:
865 parts = func_str.split(".")
866 module = np
867 for part in parts[:-1]:
868 module = getattr(module, part, None)
869 func = getattr(module, parts[-1], None)
870
871 # if NumPy does not implement it, do not implement it either
872 if func is None:
873 return
874
875 @implements(func_str, "function")
876 def implementation(*args, **kwargs):
877 # Bind given arguments to the NumPy function signature
878 bound_args = signature(func).bind(*args, **kwargs)
879
880 # Skip unit arguments that are supplied as None
881 valid_unit_arguments = [
882 label
883 for label in unit_arguments
884 if label in bound_args.arguments and bound_args.arguments[label] is not None
885 ]
886
887 # Unwrap valid unit arguments, ensure consistency, and obtain output wrapper
888 unwrapped_unit_args, output_wrap = unwrap_and_wrap_consistent_units(
889 *(bound_args.arguments[label] for label in valid_unit_arguments)
890 )
891
892 # Call NumPy function with updated arguments
893 for i, unwrapped_unit_arg in enumerate(unwrapped_unit_args):
894 bound_args.arguments[valid_unit_arguments[i]] = unwrapped_unit_arg
895 ret = func(*bound_args.args, **bound_args.kwargs)
896
897 # Conditionally wrap output
898 if wrap_output:
899 return output_wrap(ret)
900
901 return ret
902
903
904 for func_str, unit_arguments, wrap_output in (
905 ("expand_dims", "a", True),
906 ("squeeze", "a", True),
907 ("rollaxis", "a", True),
908 ("moveaxis", "a", True),
909 ("around", "a", True),
910 ("diagonal", "a", True),
911 ("linalg.diagonal", "x", True),
912 ("mean", "a", True),
913 ("ptp", "a", True),
914 ("ravel", "a", True),
915 ("round_", "a", True),
916 ("round", "a", True),
917 ("sort", "a", True),
918 ("median", "a", True),
919 ("nanmedian", "a", True),
920 ("transpose", "a", True),
921 ("linalg.matrix_transpose", "x", True),
922 ("roll", "a", True),
923 ("copy", "a", True),
924 ("average", "a", True),
925 ("nanmean", "a", True),
926 ("swapaxes", "a", True),
927 ("nanmin", "a", True),
928 ("nanmax", "a", True),
929 ("percentile", "a", True),
930 ("nanpercentile", "a", True),
931 ("quantile", "a", True),
932 ("nanquantile", "a", True),
933 ("flip", "m", True),
934 ("fix", "x", True),
935 ("trim_zeros", ["filt"], True),
936 ("broadcast_to", ["array"], True),
937 ("amax", ["a", "initial"], True),
938 ("amin", ["a", "initial"], True),
939 ("max", ["a", "initial"], True),
940 ("min", ["a", "initial"], True),
941 ("searchsorted", ["a", "v"], False),
942 ("nan_to_num", ["x", "nan", "posinf", "neginf"], True),
943 ("clip", ["a", "a_min", "a_max"], True),
944 ("append", ["arr", "values"], True),
945 ("compress", "a", True),
946 ("linspace", ["start", "stop"], True),
947 ("tile", "A", True),
948 ("lib.stride_tricks.sliding_window_view", "x", True),
949 ("rot90", "m", True),
950 ("insert", ["arr", "values"], True),
951 ("delete", ["arr"], True),
952 ("resize", "a", True),
953 ("reshape", "a", True),
954 ("intersect1d", ["ar1", "ar2"], True),
955 ):
956 implement_consistent_units_by_argument(func_str, unit_arguments, wrap_output)
957
958
959 # implement isclose and allclose
960 def implement_close(func_str):
961 if np is None:
962 return
963
964 func = getattr(np, func_str)
965
966 @implements(func_str, "function")
967 def implementation(*args, **kwargs):
968 bound_args = signature(func).bind(*args, **kwargs)
969 labels = ["a", "b"]
970 arrays = {label: bound_args.arguments[label] for label in labels}
971 if "atol" in bound_args.arguments:
972 atol = bound_args.arguments["atol"]
973 a = arrays["a"]
974 if not hasattr(atol, "_REGISTRY") and hasattr(a, "_REGISTRY"):
975 # always use the units of `a`
976 atol_ = a._REGISTRY.Quantity(atol, a.units)
977 else:
978 atol_ = atol
979 arrays["atol"] = atol_
980
981 args, _ = unwrap_and_wrap_consistent_units(*arrays.values())
982 for label, value in zip(arrays.keys(), args):
983 bound_args.arguments[label] = value
984
985 return func(*bound_args.args, **bound_args.kwargs)
986
987
988 for func_str in ("isclose", "allclose"):
989 implement_close(func_str)
990
991 # Handle atleast_nd functions
992
993
994 def implement_atleast_nd(func_str):
995 # If NumPy is not available, do not attempt implement that which does not exist
996 if np is None:
997 return
998
999 func = getattr(np, func_str)
1000
1001 @implements(func_str, "function")
1002 def implementation(*arrays):
1003 stripped_arrays, _ = convert_to_consistent_units(*arrays)
1004 arrays_magnitude = func(*stripped_arrays)
1005 if len(arrays) > 1:
1006 return [
1007 array_magnitude
1008 if not hasattr(original, "_REGISTRY")
1009 else original._REGISTRY.Quantity(array_magnitude, original.units)
1010 for array_magnitude, original in zip(arrays_magnitude, arrays)
1011 ]
1012 else:
1013 output_unit = arrays[0].units
1014 return output_unit._REGISTRY.Quantity(arrays_magnitude, output_unit)
1015
1016
1017 for func_str in ("atleast_1d", "atleast_2d", "atleast_3d"):
1018 implement_atleast_nd(func_str)
1019
1020
1021 # Handle cumulative products (which must be dimensionless for consistent units across
1022 # output array)
1023 def implement_single_dimensionless_argument_func(func_str):
1024 # If NumPy is not available, do not attempt implement that which does not exist
1025 if np is None:
1026 return
1027
1028 func = getattr(np, func_str)
1029
1030 @implements(func_str, "function")
1031 def implementation(a, *args, **kwargs):
1032 (a_stripped,), _ = convert_to_consistent_units(
1033 a, pre_calc_units=a._REGISTRY.parse_units("dimensionless")
1034 )
1035 return a._REGISTRY.Quantity(func(a_stripped, *args, **kwargs))
1036
1037
1038 for func_str in ("cumprod", "nancumprod"):
1039 implement_single_dimensionless_argument_func(func_str)
1040
1041 # Handle single-argument consistent unit functions
1042 for func_str in (
1043 "block",
1044 "hstack",
1045 "vstack",
1046 "dstack",
1047 "column_stack",
1048 "broadcast_arrays",
1049 ):
1050 implement_func(
1051 "function", func_str, input_units="all_consistent", output_unit="match_input"
1052 )
1053
1054 # Handle functions that ignore units on input and output
1055 for func_str in (
1056 "size",
1057 "isreal",
1058 "iscomplex",
1059 "shape",
1060 "ones_like",
1061 "zeros_like",
1062 "empty_like",
1063 "argsort",
1064 "argmin",
1065 "argmax",
1066 "ndim",
1067 "nanargmax",
1068 "nanargmin",
1069 "count_nonzero",
1070 "nonzero",
1071 "result_type",
1072 ):
1073 implement_func("function", func_str, input_units=None, output_unit=None)
1074
1075 # Handle functions with output unit defined by operation
1076 for func_str in (
1077 "sum",
1078 "diag",
1079 "tril",
1080 "triu",
1081 "nansum",
1082 "cumsum",
1083 "nancumsum",
1084 "linalg.norm",
1085 "linalg.eigvals",
1086 "linalg.eigvalsh",
1087 "linalg.matrix_norm",
1088 "linalg.vector_norm",
1089 ):
1090 implement_func("function", func_str, input_units=None, output_unit="sum")
1091 for func_str in ("diff", "ediff1d", "std", "nanstd"):
1092 implement_func("function", func_str, input_units=None, output_unit="delta")
1093 for func_str in ("gradient",):
1094 implement_func("function", func_str, input_units=None, output_unit="delta,div")
1095 for func_str in ("linalg.solve",):
1096 implement_func("function", func_str, input_units=None, output_unit="invdiv")
1097 for func_str in ("var", "nanvar"):
1098 implement_func("function", func_str, input_units=None, output_unit="variance")
1099
1100
1101 @implements("geomspace", "function")
1102 def _geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0):
1103 if all(not _is_quantity(arg) for arg in (start, stop)):
1104 return np.geomspace(start, stop, num, endpoint, dtype, axis)
1105 first_input_units = _get_first_input_units((start, stop))
1106 if not _is_quantity(start):
1107 start = start * first_input_units._REGISTRY.parse_units("dimensionless")
1108 if not _is_quantity(stop):
1109 stop = stop * first_input_units._REGISTRY.parse_units("dimensionless")
1110
1111 start = _base_unit_if_needed(start)
1112 stop = _base_unit_if_needed(stop)
1113 (start, stop), output_wrap = unwrap_and_wrap_consistent_units(start, stop)
1114 return output_wrap(np.geomspace(start, stop, num, endpoint, dtype, axis))
1115
1116
1117 def numpy_wrap(func_type, func, args, kwargs, types):
1118 """Return the result from a NumPy function/ufunc as wrapped by Pint."""
1119
1120 if func_type == "function":
1121 handled = HANDLED_FUNCTIONS
1122 # Need to handle functions in submodules
1123 name = ".".join(func.__module__.split(".")[1:] + [func.__name__])
1124 elif func_type == "ufunc":
1125 handled = HANDLED_UFUNCS
1126 # ufuncs do not have func.__module__
1127 name = func.__name__
1128 else:
1129 raise ValueError(f"Invalid func_type {func_type}")
1130
1131 if name not in handled or any(is_upcast_type(t) for t in types):
1132 return NotImplemented
1133 return handled[name](*args, **kwargs)