| 1 |
""" |
| 2 |
pint.facets.numpy.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 functools |
| 12 |
import math |
| 13 |
import warnings |
| 14 |
from typing import Any, Generic |
| 15 |
|
| 16 |
from ..._typing import Shape |
| 17 |
from ...compat import HAS_NUMPY, _to_magnitude, np |
| 18 |
from ...errors import DimensionalityError, PintTypeError, UnitStrippedWarning |
| 19 |
from ..plain import MagnitudeT, PlainQuantity |
| 20 |
from .numpy_func import ( |
| 21 |
HANDLED_UFUNCS, |
| 22 |
copy_units_output_ufuncs, |
| 23 |
get_op_output_unit, |
| 24 |
matching_input_copy_units_output_ufuncs, |
| 25 |
matching_input_set_units_output_ufuncs, |
| 26 |
numpy_wrap, |
| 27 |
op_units_output_ufuncs, |
| 28 |
set_units_ufuncs, |
| 29 |
) |
| 30 |
|
| 31 |
try: |
| 32 |
import uncertainties.unumpy as unp |
| 33 |
from uncertainties import UFloat, ufloat |
| 34 |
|
| 35 |
HAS_UNCERTAINTIES = True |
| 36 |
except ImportError: |
| 37 |
unp = np |
| 38 |
ufloat = Ufloat = None |
| 39 |
HAS_UNCERTAINTIES = False |
| 40 |
|
| 41 |
|
| 42 |
def method_wraps(numpy_func): |
| 43 |
if isinstance(numpy_func, str): |
| 44 |
numpy_func = getattr(np, numpy_func, None) |
| 45 |
|
| 46 |
def wrapper(func): |
| 47 |
func.__wrapped__ = numpy_func |
| 48 |
|
| 49 |
return func |
| 50 |
|
| 51 |
return wrapper |
| 52 |
|
| 53 |
|
| 54 |
class NumpyQuantity(Generic[MagnitudeT], PlainQuantity[MagnitudeT]): |
| 55 |
""" """ |
| 56 |
|
| 57 |
# NumPy function/ufunc support |
| 58 |
__array_priority__ = 17 |
| 59 |
|
| 60 |
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): |
| 61 |
if method != "__call__": |
| 62 |
# Only handle ufuncs as callables |
| 63 |
return NotImplemented |
| 64 |
|
| 65 |
# Replicate types from __array_function__ |
| 66 |
types = { |
| 67 |
type(arg) |
| 68 |
for arg in list(inputs) + list(kwargs.values()) |
| 69 |
if hasattr(arg, "__array_ufunc__") |
| 70 |
} |
| 71 |
|
| 72 |
return numpy_wrap("ufunc", ufunc, inputs, kwargs, types) |
| 73 |
|
| 74 |
def __array_function__(self, func, types, args, kwargs): |
| 75 |
return numpy_wrap("function", func, args, kwargs, types) |
| 76 |
|
| 77 |
_wrapped_numpy_methods = ["flatten", "astype", "item"] |
| 78 |
|
| 79 |
def _numpy_method_wrap(self, func, *args, **kwargs): |
| 80 |
"""Convenience method to wrap on the fly NumPy ndarray methods taking |
| 81 |
care of the units. |
| 82 |
""" |
| 83 |
|
| 84 |
# Set input units if needed |
| 85 |
if func.__name__ in set_units_ufuncs: |
| 86 |
self.__ito_if_needed(set_units_ufuncs[func.__name__][0]) |
| 87 |
|
| 88 |
value = func(*args, **kwargs) |
| 89 |
|
| 90 |
# Set output units as needed |
| 91 |
if func.__name__ in ( |
| 92 |
matching_input_copy_units_output_ufuncs |
| 93 |
+ copy_units_output_ufuncs |
| 94 |
+ self._wrapped_numpy_methods |
| 95 |
): |
| 96 |
output_unit = self._units |
| 97 |
elif func.__name__ in set_units_ufuncs: |
| 98 |
output_unit = set_units_ufuncs[func.__name__][1] |
| 99 |
elif func.__name__ in matching_input_set_units_output_ufuncs: |
| 100 |
output_unit = matching_input_set_units_output_ufuncs[func.__name__] |
| 101 |
elif func.__name__ in op_units_output_ufuncs: |
| 102 |
output_unit = get_op_output_unit( |
| 103 |
op_units_output_ufuncs[func.__name__], |
| 104 |
self.units, |
| 105 |
list(args) + list(kwargs.values()), |
| 106 |
self._magnitude.size, |
| 107 |
) |
| 108 |
else: |
| 109 |
output_unit = None |
| 110 |
|
| 111 |
if output_unit is not None: |
| 112 |
return self.__class__(value, output_unit) |
| 113 |
|
| 114 |
return value |
| 115 |
|
| 116 |
def __array__(self, t=None) -> np.ndarray: |
| 117 |
if HAS_NUMPY and isinstance(self._magnitude, np.ndarray): |
| 118 |
warnings.warn( |
| 119 |
"The unit of the quantity is stripped when downcasting to ndarray.", |
| 120 |
UnitStrippedWarning, |
| 121 |
stacklevel=2, |
| 122 |
) |
| 123 |
return _to_magnitude(self._magnitude, force_ndarray=True) |
| 124 |
|
| 125 |
def clip(self, min=None, max=None, out=None, **kwargs): |
| 126 |
if min is not None: |
| 127 |
if isinstance(min, self.__class__): |
| 128 |
min = min.to(self).magnitude |
| 129 |
elif self.dimensionless: |
| 130 |
pass |
| 131 |
else: |
| 132 |
raise DimensionalityError("dimensionless", self._units) |
| 133 |
|
| 134 |
if max is not None: |
| 135 |
if isinstance(max, self.__class__): |
| 136 |
max = max.to(self).magnitude |
| 137 |
elif self.dimensionless: |
| 138 |
pass |
| 139 |
else: |
| 140 |
raise DimensionalityError("dimensionless", self._units) |
| 141 |
return self.__class__(self.magnitude.clip(min, max, out, **kwargs), self._units) |
| 142 |
|
| 143 |
def fill(self: NumpyQuantity, value) -> None: |
| 144 |
self._units = value._units |
| 145 |
return self.magnitude.fill(value.magnitude) |
| 146 |
|
| 147 |
def put(self: NumpyQuantity, indices, values, mode="raise") -> None: |
| 148 |
if isinstance(values, self.__class__): |
| 149 |
values = values.to(self).magnitude |
| 150 |
elif self.dimensionless: |
| 151 |
values = self.__class__(values, "").to(self) |
| 152 |
else: |
| 153 |
raise DimensionalityError("dimensionless", self._units) |
| 154 |
self.magnitude.put(indices, values, mode) |
| 155 |
|
| 156 |
@property |
| 157 |
def real(self) -> NumpyQuantity: |
| 158 |
return self.__class__(self._magnitude.real, self._units) |
| 159 |
|
| 160 |
@property |
| 161 |
def imag(self) -> NumpyQuantity: |
| 162 |
return self.__class__(self._magnitude.imag, self._units) |
| 163 |
|
| 164 |
@property |
| 165 |
def T(self): |
| 166 |
return self.__class__(self._magnitude.T, self._units) |
| 167 |
|
| 168 |
@property |
| 169 |
def flat(self): |
| 170 |
for v in self._magnitude.flat: |
| 171 |
yield self.__class__(v, self._units) |
| 172 |
|
| 173 |
@property |
| 174 |
def shape(self) -> Shape: |
| 175 |
return self._magnitude.shape |
| 176 |
|
| 177 |
@property |
| 178 |
def dtype(self): |
| 179 |
return self._magnitude.dtype |
| 180 |
|
| 181 |
@shape.setter |
| 182 |
def shape(self, value): |
| 183 |
self._magnitude.shape = value |
| 184 |
|
| 185 |
def searchsorted(self, v, side="left", sorter=None): |
| 186 |
if isinstance(v, self.__class__): |
| 187 |
v = v.to(self).magnitude |
| 188 |
elif self.dimensionless: |
| 189 |
v = self.__class__(v, "").to(self) |
| 190 |
else: |
| 191 |
raise DimensionalityError("dimensionless", self._units) |
| 192 |
return self.magnitude.searchsorted(v, side) |
| 193 |
|
| 194 |
def dot(self, b): |
| 195 |
"""Dot product of two arrays. |
| 196 |
|
| 197 |
Wraps np.dot(). |
| 198 |
""" |
| 199 |
|
| 200 |
return np.dot(self, b) |
| 201 |
|
| 202 |
@method_wraps("prod") |
| 203 |
def prod(self, *args, **kwargs): |
| 204 |
"""Return the product of quantity elements over a given axis |
| 205 |
|
| 206 |
Wraps np.prod(). |
| 207 |
""" |
| 208 |
return np.prod(self, *args, **kwargs) |
| 209 |
|
| 210 |
def __ito_if_needed(self, to_units): |
| 211 |
if self.unitless and to_units == "radian": |
| 212 |
return |
| 213 |
|
| 214 |
self.ito(to_units) |
| 215 |
|
| 216 |
def __len__(self) -> int: |
| 217 |
return len(self._magnitude) |
| 218 |
|
| 219 |
def __getattr__(self, item) -> Any: |
| 220 |
if item.startswith("__array_"): |
| 221 |
# Handle array protocol attributes other than `__array__` |
| 222 |
raise AttributeError(f"Array protocol attribute {item} not available.") |
| 223 |
elif item in HANDLED_UFUNCS or item in self._wrapped_numpy_methods: |
| 224 |
magnitude_as_duck_array = _to_magnitude( |
| 225 |
self._magnitude, force_ndarray_like=True |
| 226 |
) |
| 227 |
try: |
| 228 |
attr = getattr(magnitude_as_duck_array, item) |
| 229 |
return functools.partial(self._numpy_method_wrap, attr) |
| 230 |
except AttributeError: |
| 231 |
raise AttributeError( |
| 232 |
f"NumPy method {item} not available on {type(magnitude_as_duck_array)}" |
| 233 |
) |
| 234 |
except TypeError as exc: |
| 235 |
if "not callable" in str(exc): |
| 236 |
raise AttributeError( |
| 237 |
f"NumPy method {item} not callable on {type(magnitude_as_duck_array)}" |
| 238 |
) |
| 239 |
else: |
| 240 |
raise exc |
| 241 |
elif ( |
| 242 |
HAS_UNCERTAINTIES and item == "ndim" and isinstance(self._magnitude, UFloat) |
| 243 |
): |
| 244 |
# Dimensionality of a single UFloat is 0, like any other scalar |
| 245 |
return 0 |
| 246 |
|
| 247 |
try: |
| 248 |
return getattr(self._magnitude, item) |
| 249 |
except AttributeError: |
| 250 |
raise AttributeError( |
| 251 |
"Neither Quantity object nor its magnitude ({}) " |
| 252 |
"has attribute '{}'".format(self._magnitude, item) |
| 253 |
) |
| 254 |
|
| 255 |
def __getitem__(self, key): |
| 256 |
try: |
| 257 |
return type(self)(self._magnitude[key], self._units) |
| 258 |
except PintTypeError: |
| 259 |
raise |
| 260 |
except TypeError: |
| 261 |
raise TypeError( |
| 262 |
"Neither Quantity object nor its magnitude ({})" |
| 263 |
"supports indexing".format(self._magnitude) |
| 264 |
) |
| 265 |
|
| 266 |
def __setitem__(self, key, value): |
| 267 |
try: |
| 268 |
# If we're dealing with a masked single value or a nan, set it |
| 269 |
if ( |
| 270 |
isinstance(self._magnitude, np.ma.MaskedArray) |
| 271 |
and np.ma.is_masked(value) |
| 272 |
and getattr(value, "size", 0) == 1 |
| 273 |
) or (getattr(value, "ndim", 0) == 0 and math.isnan(value)): |
| 274 |
self._magnitude[key] = value |
| 275 |
return |
| 276 |
except TypeError: |
| 277 |
pass |
| 278 |
|
| 279 |
try: |
| 280 |
if isinstance(value, self.__class__): |
| 281 |
factor = self.__class__( |
| 282 |
value.magnitude, value._units / self._units |
| 283 |
).to_root_units() |
| 284 |
else: |
| 285 |
factor = self.__class__(value, self._units ** (-1)).to_root_units() |
| 286 |
|
| 287 |
if isinstance(factor, self.__class__): |
| 288 |
if not factor.dimensionless: |
| 289 |
raise DimensionalityError( |
| 290 |
value, |
| 291 |
self.units, |
| 292 |
extra_msg=". Assign a quantity with the same dimensionality " |
| 293 |
"or access the magnitude directly as " |
| 294 |
f"`obj.magnitude[{key}] = {value}`.", |
| 295 |
) |
| 296 |
self._magnitude[key] = factor.magnitude |
| 297 |
else: |
| 298 |
self._magnitude[key] = factor |
| 299 |
|
| 300 |
except PintTypeError: |
| 301 |
raise |
| 302 |
except TypeError as exc: |
| 303 |
raise TypeError( |
| 304 |
f"Neither Quantity object nor its magnitude ({self._magnitude}) " |
| 305 |
"supports indexing" |
| 306 |
) from exc |