Repository navigation
Open
Labels
Milestone
Description
In [1]: import quantities as pq
In [2]: import numpy as np
In [3]: np.add(1*pq.kg, 1*pq.g)
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
/opt/miniconda/envs/py3/lib/python3.7/site-packages/quantities/dimensionality.py in _d_check_uniform(q1, q2, out)
256 try:
--> 257 assert q1._dimensionality == q2._dimensionality
258 return q1.dimensionality
AssertionError:
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
<ipython-input-3-91c844f67315> in <module>
----> 1 np.add(1*pq.kg, 1*pq.g)
/opt/miniconda/envs/py3/lib/python3.7/site-packages/quantities/quantity.py in __array_prepare__(self, obj, context)
245 #print self, obj, res, uf, objs
246 try:
--> 247 res._dimensionality = p_dict[uf](*objs)
248 except KeyError:
249 raise ValueError(
/opt/miniconda/envs/py3/lib/python3.7/site-packages/quantities/dimensionality.py in _d_check_uniform(q1, q2, out)
260 raise ValueError(
261 'quantities must have identical units, got "%s" and "%s"' %
--> 262 (q1.units, q2.units)
263 )
264 except AttributeError:
Other quantity libraries like pint, astropy.units and unyt don't raise an exception when np.add is called with quantities with different (rescalable) units.
BTW quantities has the same problem when np.sub or np.equal is used.
Activity
twmr commentedon Oct 28, 2019
The reason why I noticed this regression is that the benchmark tool, that is part of unyt uses np.add for tests. See https://github.com/yt-project/unyt/tree/master/benchmarks
apdavison commentedon Nov 28, 2019
I've briefly looked into this, it looks as though the
__array_ufunc__method (introduced in NumPy 1.13) would be a good approach for doing the necessary scaling, but I haven't had time to try this out.OmkarGowda990 commentedon Nov 20, 2026
I'd like to work on this. It still happens on quantities 0.17.0 with NumPy 2.5.5:
np.add(1*pq.kg, 1*pq.g)raisesValueError: quantities must have identical units, got "1.0 kg" and "1.0 g", and so donp.subtractandnp.equal, while1*pq.kg + 1*pq.ggives1.001 kg.My plan is to rescale the second operand to the first operand's units for these ufuncs when the dimensions are compatible, keep the current error when they aren't, and add tests. Would a PR along those lines be welcome?