Skip to content

Check shapes of coordinates and data during DataArray construction #2533

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

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
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
18 changes: 12 additions & 6 deletions xarray/core/dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,16 @@ def _infer_coords_and_dims(
var.dims = (dim,)
new_coords[dim] = var.to_index_variable()

_check_shape_consistency(shape, new_coords, dims)
assert_unique_multiindex_level_names(new_coords)

return new_coords, dims


def _check_shape_consistency(shape, coords, dims):
# moved from _infer_coords_and_dims
sizes = dict(zip(dims, shape))
for k, v in new_coords.items():
for k, v in coords.items():
if any(d not in dims for d in v.dims):
raise ValueError(
f"coordinate {k} has dimensions {v.dims}, but these "
Expand All @@ -167,10 +175,6 @@ def _infer_coords_and_dims(
"matching the dimension size"
)

assert_unique_multiindex_level_names(new_coords)

return new_coords, dims


def _check_data_shape(data, coords, dims):
if data is dtypes.NA:
Expand Down Expand Up @@ -2977,6 +2981,8 @@ def _result_name(self, other: Any = None) -> Optional[Hashable]:

def __array_wrap__(self, obj, context=None) -> "DataArray":
new_var = self.variable.__array_wrap__(obj, context)
if context is None:
_check_shape_consistency(new_var.shape, self._coords, new_var.dims)
return self._replace(new_var)

def __matmul__(self, obj):
Expand All @@ -2997,7 +3003,7 @@ def _unary_op(self, f: Callable, *args, **kwargs):
"ignore", r"Mean of empty slice", category=RuntimeWarning
)
with np.errstate(all="ignore"):
da = self.__array_wrap__(f(self.variable.data, *args, **kwargs))
da = self.__array_wrap__(f(self.variable.data, *args, **kwargs), -1)
if keep_attrs:
da.attrs = self.attrs
return da
Expand Down
3 changes: 3 additions & 0 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,9 @@ def test_constructor_from_self_described(self):
actual = DataArray(IndexVariable("foo", ["a", "b"]))
assert_identical(expected, actual)

with pytest.raises(ValueError, match="conflicting sizes for dimension"):
np.insert(expected, 0, 0, axis=0)

def test_constructor_from_0d(self):
expected = Dataset({None: ([], 0)})[None]
actual = DataArray(0)
Expand Down