MCPcopy Index your code
hub / github.com/matplotlib/matplotlib / QuantityND

Class QuantityND

lib/matplotlib/tests/test_image.py:1294–1351  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1292# There is just enough implemented to test handling of ndarray
1293# subclasses.
1294class QuantityND(np.ndarray):
1295 def __new__(cls, input_array, units):
1296 obj = np.asarray(input_array).view(cls)
1297 obj.units = units
1298 return obj
1299
1300 def __array_finalize__(self, obj):
1301 self.units = getattr(obj, "units", None)
1302
1303 def __getitem__(self, item):
1304 units = getattr(self, "units", None)
1305 ret = super().__getitem__(item)
1306 if isinstance(ret, QuantityND) or units is not None:
1307 ret = QuantityND(ret, units)
1308 return ret
1309
1310 def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
1311 func = getattr(ufunc, method)
1312 if "out" in kwargs:
1313 return NotImplemented
1314 if len(inputs) == 1:
1315 i0 = inputs[0]
1316 unit = getattr(i0, "units", "dimensionless")
1317 out_arr = func(np.asarray(i0), **kwargs)
1318 elif len(inputs) == 2:
1319 i0 = inputs[0]
1320 i1 = inputs[1]
1321 u0 = getattr(i0, "units", "dimensionless")
1322 u1 = getattr(i1, "units", "dimensionless")
1323 u0 = u1 if u0 is None else u0
1324 u1 = u0 if u1 is None else u1
1325 if ufunc in [np.add, np.subtract]:
1326 if u0 != u1:
1327 raise ValueError
1328 unit = u0
1329 elif ufunc == np.multiply:
1330 unit = f"{u0}*{u1}"
1331 elif ufunc == np.divide:
1332 unit = f"{u0}/({u1})"
1333 elif ufunc in (np.greater, np.greater_equal,
1334 np.equal, np.not_equal,
1335 np.less, np.less_equal):
1336 # Comparisons produce unitless booleans for output
1337 unit = None
1338 else:
1339 return NotImplemented
1340 out_arr = func(i0.view(np.ndarray), i1.view(np.ndarray), **kwargs)
1341 else:
1342 return NotImplemented
1343 if unit is None:
1344 out_arr = np.array(out_arr)
1345 else:
1346 out_arr = QuantityND(out_arr, unit)
1347 return out_arr
1348
1349 @property
1350 def v(self):
1351 return self.view(np.ndarray)

Callers 4

__getitem__Method · 0.85
__array_ufunc__Method · 0.85
test_quantityndFunction · 0.85
test_imshow_quantityndFunction · 0.85

Calls

no outgoing calls

Tested by 4

__getitem__Method · 0.68
__array_ufunc__Method · 0.68
test_quantityndFunction · 0.68
test_imshow_quantityndFunction · 0.68

Used in the wild real call sites across dependent graphs

searching dependent graphs…