Repository navigation
Let Quantity accept Array-API compatible objects - #15752
Conversation
|
Thank you for your contribution to Astropy! 🌌 This checklist is meant to remind the package maintainers who will review this pull request of some common things to look for.
|
pllim
left a comment
There was a problem hiding this comment.
Thanks! Left a general review.
I think this also needs a change log fragment but I cannot tell if it is feature or api, so I'll let units maintainers decide.
|
Also the failure looks related: |
mhvk
left a comment
There was a problem hiding this comment.
Thanks for the PR! Rather than checking for array API, I think it is better to avoid the failure that currently occurs, which can be done by replacing
if isiterable(value) and len(value) > 1
with
if isinstance(value, (list, tuple)) and len(value) > 1
I think this is actually a bit better than isiterable anyway, though it is an API change so will need a corresponding changelog entry...
| # To ensure array remains fast, we short-circuit it. | ||
| value_unit = None | ||
| if not isinstance(value, np.ndarray): | ||
| from astropy.utils.compat.optional_deps import HAS_ARRAY_API_COMPAT |
There was a problem hiding this comment.
I don't think we need this explicit test - this branch just tests for string and sequences of Quantity, and otherwise falls through to an np.array call which will already do the right thing. See main comment.
|
Thanks for the reviews! Now I just avoid the iterable check as suggested, this should fix #15071 but we would need |
If any iterable such as a list of tuple was input to ``Quantity``, a check was done to see if they contained only quantities, and, if so, the quantities were concatenated. This makes sense for list and tuple, but is not necessarily logical for all iterables and indeed was broken for those that do not have a length (such as ``array_api`` array instances). Hence, the check will now be done only for values where it makes sense, i.e., instances of list and tuple.
f676f24 to
def12c5
Compare
mhvk
left a comment
There was a problem hiding this comment.
OK, looks good! I rephrased the API changelog entry a bit, hopefully making it (even) clearer, and also squashed the commits. Approving now and setting up for auto-merge...
This is a hack to make the code block in #15071 work and I just wanted to test this out and see how things need to work/refactor inside
Quantityto work. The changes here are minimal and it just casts any array-api compatible object to numpy array (as suggested in #15071 (comment)), like atorchtensor orcupyarray will be able to use astropy to create aQuantityobject.The following code would work with this change.
The quantity value in the above case loses the torch tensor as it's wrapped by a numpy ndarray.
Would there be interest in refactoring
Quantityand making it work natively with array-api compatible types?