← Back to team overview

python-quantities-developers team mailing list archive

[Bug 390689] Re: Adding different units raises a ValueError

 

This is fixed in the trunk, you can do:

pq.m+pq.ft

but you can't do:

np.add(pq.m,pq.ft)

The former is handled by overriding the __add__ method, where we can
rescale the quantity before passing it as input to the ufunc. I don't
think there is a clean solution for the latter, since by the time we
have a chance to call __array_prepare__, the input arrays have already
been passed to the ufunc, there is no opportunity to modify them and
pass them back to the ufunc. Real generic functions as described in PEP
3124 would be a better solution, but that PEP is a long way off (maybe
even unlikely to be accepted).

-- 
Adding different units raises a ValueError
https://bugs.launchpad.net/bugs/390689
You received this bug notification because you are a member of Python
Quantities Development Team, which is subscribed to python-quantities.

Status in Physical Quantities for Python: Fix Committed

Bug description:
Adding values of different (but compatible) units raises a ValueError. Below is a simple example to reproduce the error.

>>> import quantities as pq
>>> a = 10 * pq.m
>>> b = 1 * pq.mm
>>> a + b

My guess is that this is a known issue, in which case, I'd suggest that a Known Issues page be added to the website.

I dug through the code and found that the __array_wrap__ method gets called *after* numpy has already added the values together. To properly handle addition, you'd need to alter the values before numpy got its hands on the data. Darren, I guess this is one of the reasons you've been lobbying for __gfunc_pre__ and __gfunc_post__:

http://www.nabble.com/suggestion-for-generalizing-numpy-functions-tt22413628.html#a22413628
http://www.nabble.com/Plans-for-Numpy-1.4.0-and-scipy-0.8.0-tt24132765.html

In any case, I thought it'd be a good idea to document this issue. The obvious work around is to just alter the units of one of the values before addition. In other words.

>>> b.units = pq.m
>>> a + b

Good luck getting __gfunc_pre__ (or __array_prepare__) into numpy 1.4.