Repository navigation
Support exponential and logarithmic functions in umath and allow compound dimensionless units - #287
Conversation
…ound dimensionless units - Add exp, exp2, expm1, log, log2, log10, and log1p functions in quantities.umath with automatic rescaling to dimensionless quantities. - Update _d_dimensionless in quantities.dimensionality to check all positional arguments (handling binary ufuncs like logaddexp and logaddexp2) and verify whether dimensionality simplifies to dimensionless (fixing python-quantities#217). - Add unit tests in test_umath.py covering the new functions and compound dimensionless inputs.
apdavison
left a comment
There was a problem hiding this comment.
Thank you for this. The new umath functions are a useful addition, and they rescale their input correctly.
However, the change to _d_dimensionless and _d_arctrig lets NumPy's own ufuncs give wrong results without any error. quantities computes a ufunc on the raw magnitudes and only checks the units afterwards, in __array_wrap__, so these functions can't rescale the input. Accepting any input that simplifies to dimensionless therefore uses the magnitude unscaled whenever the conversion factor isn't 1:
| Call | With this PR | Correct | master |
|---|---|---|---|
np.exp(1*pq.s/pq.ms) |
2.718… |
inf (e¹⁰⁰⁰) |
ValueError |
np.log10(500*pq.ms/pq.s) |
2.699 |
-0.301 |
ValueError |
np.arcsin(500*pq.ms/pq.s) |
nan |
0.5236 |
ValueError |
np.exp(2*pq.J/pq.cal) |
7.389 |
1.613 |
ValueError |
The tests don't catch this because J/(N*m) has a conversion factor of exactly 1.
Could you accept a compound dimensionless input only when its conversion factor is 1 (for example, when Quantity(1.0, dim).simplified is dimensionless with a magnitude of 1, allowing for rounding), and keep raising ValueError otherwise, perhaps with a message suggesting .simplified or the new umath functions? The example in #217 has a factor of exactly 1, so it would still work. Please also add tests with scaled units such as s/ms and J/cal: they should raise for the np.* functions, and give the correct values with umath. Handling these properly in the ufuncs themselves needs __array_ufunc__, which is planned for 0.18.0.
Summary
exp,exp2,expm1,log,log2,log10, andlog1ptoquantities.umath(and exported byquantities), matching existing trigonometric and hyperbolic functions likesinhandsin, with automatic rescaling to dimensionless quantities.quantities.dimensionality._d_dimensionless, checks whether dimensionality simplifies to dimensionless (dim.simplified != Dimensionality()), allowing expressions whose compound units cancel out (such as2*pi*Z_0 / sqrt(mu0/epsilon)orJ / (N*m))._d_dimensionless(*args)so binary ufuncs likelogaddexpandlogaddexp2properly validate the second argument as well.quantities/tests/test_umath.py.Tests