Skip to content

Keep units in np.ptp with NumPy 2 - #281

Open
syahra712 wants to merge 1 commit into
python-quantities:masterfrom
syahra712:fix/np-ptp-numpy2
Open

syahra712 wants to merge 1 commit into
python-quantities:masterfrom
syahra712:fix/np-ptp-numpy2

Conversation

@syahra712

Copy link
Copy Markdown

With NumPy 2, np.ptp drops the units of a Quantity:

>>> import numpy as np, quantities as pq
>>> q = [1., 5., 3.] * pq.m
>>> np.ptp(q)
array(4.) * dimensionless     # expected array(4.) * m
>>> q.ptp()
array(4.) * m

On NumPy 1.26 this returned m, because np.ptp called a.ptp(). NumPy 2 removed ndarray.ptp, so np.ptp now runs maximum.reduce/minimum.reduce directly. Those reductions reach __array_wrap__ with context=None, so the result comes back dimensionless.

Fix: add a small __array_function__ that sends np.ptp to the existing Quantity.ptp when the first argument is a Quantity. Every other function still goes through ndarray.__array_function__. Quantity.ptp now also accepts keepdims, so np.ptp(q, axis=..., keepdims=True) works.

Tests: I added test_np_ptp to test_methods.py. It covers the whole array, axis given as a keyword and positionally, and keepdims.

  • With NumPy 2.5 it fails without the fix and passes with it.
  • The full suite passes with NumPy 2.5.4 and with NumPy 1.26.4: 190 passed, 3 xfailed.

I also added an entry to CHANGES.txt.

Separately, np.maximum.reduce(q), np.add.reduce(q) and np.add.accumulate(q) return dimensionless results on both NumPy 1 and 2. This PR doesn't change them. Fixing them would need ufunc-method-aware handling, for example in __array_ufunc__. I'm happy to look at that in a follow-up if it's wanted.

AI-assisted (Claude): I used it to help read the code and draft the test. I reviewed and ran everything myself.

NumPy 2 removed ndarray.ptp, so np.ptp no longer calls Quantity.ptp
and returned a dimensionless result. Route np.ptp to Quantity.ptp via
__array_function__ and accept keepdims there.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant