Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make broadcast and concat work with the Array API #7387

Merged
merged 2 commits into from
Jan 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion xarray/core/duck_array_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
import pandas as pd
from numpy import all as array_all # noqa
from numpy import any as array_any # noqa
from numpy import around # noqa
from numpy import zeros_like # noqa
from numpy import around, broadcast_to # noqa
from numpy import concatenate as _concatenate
from numpy import ( # noqa
einsum,
Expand Down Expand Up @@ -207,6 +207,11 @@ def as_shared_dtype(scalars_or_arrays, xp=np):
return [astype(x, out_type, copy=False) for x in arrays]


def broadcast_to(array, shape):
xp = get_array_namespace(array)
return xp.broadcast_to(array, shape)


def lazy_array_equiv(arr1, arr2):
"""Like array_equal, but doesn't actually compare values.
Returns True when arr1, arr2 identical or their dask tokens are equal.
Expand Down Expand Up @@ -311,6 +316,9 @@ def fillna(data, other):

def concatenate(arrays, axis=0):
"""concatenate() with better dtype promotion rules."""
if hasattr(arrays[0], "__array_namespace__"):
xp = get_array_namespace(arrays[0])
return xp.concat(as_shared_dtype(arrays, xp=xp), axis=axis)
return _concatenate(as_shared_dtype(arrays), axis=axis)


Expand Down
21 changes: 21 additions & 0 deletions xarray/tests/test_array_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,27 @@ def test_astype(arrays) -> None:
assert_equal(actual, expected)


def test_broadcast(arrays: tuple[xr.DataArray, xr.DataArray]) -> None:
np_arr, xp_arr = arrays
np_arr2 = xr.DataArray(np.array([1.0, 2.0]), dims="x")
xp_arr2 = xr.DataArray(xp.asarray([1.0, 2.0]), dims="x")

expected = xr.broadcast(np_arr, np_arr2)
actual = xr.broadcast(xp_arr, xp_arr2)
assert len(actual) == len(expected)
for a, e in zip(actual, expected):
assert isinstance(a.data, Array)
assert_equal(a, e)


def test_concat(arrays: tuple[xr.DataArray, xr.DataArray]) -> None:
np_arr, xp_arr = arrays
expected = xr.concat((np_arr, np_arr), dim="x")
actual = xr.concat((xp_arr, xp_arr), dim="x")
assert isinstance(actual.data, Array)
assert_equal(actual, expected)


def test_indexing(arrays: tuple[xr.DataArray, xr.DataArray]) -> None:
np_arr, xp_arr = arrays
expected = np_arr[:, 0]
Expand Down