Skip to content

Commit 79b3cdd

Browse files
max-sixtydcherian
authored andcommitted
change ALL_DIMS to equal ellipsis (pydata#3418)
* change ALL_DIMS to equal ... * changed references & added whatsnew * Update xarray/core/groupby.py Co-Authored-By: Deepak Cherian <dcherian@users.noreply.github.com> * Update xarray/core/groupby.py Co-Authored-By: Deepak Cherian <dcherian@users.noreply.github.com> * note in readme
1 parent bb0a5a2 commit 79b3cdd

File tree

13 files changed

+55
-46
lines changed

13 files changed

+55
-46
lines changed

doc/examples/multidimensional-coords.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ function to specify the output coordinates of the group.
107107
lat_center = np.arange(1, 90, 2)
108108
# group according to those bins and take the mean
109109
Tair_lat_mean = (ds.Tair.groupby_bins('xc', lat_bins, labels=lat_center)
110-
.mean(xr.ALL_DIMS))
110+
.mean(...))
111111
# plot the result
112112
@savefig xarray_multidimensional_coords_14_1.png width=5in
113113
Tair_lat_mean.plot();

doc/groupby.rst

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,13 @@ dimensions *other than* the provided one:
116116

117117
.. ipython:: python
118118
119-
ds.groupby('x').std(xr.ALL_DIMS)
119+
ds.groupby('x').std(...)
120+
121+
.. note::
122+
123+
We use an ellipsis (`...`) here to indicate we want to reduce over all
124+
other dimensions
125+
120126

121127
First and last
122128
~~~~~~~~~~~~~~
@@ -127,7 +133,7 @@ values for group along the grouped dimension:
127133

128134
.. ipython:: python
129135
130-
ds.groupby('letters').first(xr.ALL_DIMS)
136+
ds.groupby('letters').first(...)
131137
132138
By default, they skip missing values (control this with ``skipna``).
133139

@@ -142,7 +148,7 @@ coordinates. For example:
142148

143149
.. ipython:: python
144150
145-
alt = arr.groupby('letters').mean(xr.ALL_DIMS)
151+
alt = arr.groupby('letters').mean(...)
146152
alt
147153
ds.groupby('letters') - alt
148154
@@ -195,7 +201,7 @@ __ http://cfconventions.org/cf-conventions/v1.6.0/cf-conventions.html#_two_dimen
195201
'lat': (['ny','nx'], [[10,10],[20,20]] ),},
196202
dims=['ny','nx'])
197203
da
198-
da.groupby('lon').sum(xr.ALL_DIMS)
204+
da.groupby('lon').sum(...)
199205
da.groupby('lon').apply(lambda x: x - x.mean(), shortcut=False)
200206
201207
Because multidimensional groups have the ability to generate a very large
@@ -213,4 +219,4 @@ applying your function, and then unstacking the result:
213219
.. ipython:: python
214220
215221
stacked = da.stack(gridcell=['ny', 'nx'])
216-
stacked.groupby('gridcell').sum(xr.ALL_DIMS).unstack('gridcell')
222+
stacked.groupby('gridcell').sum(...).unstack('gridcell')

doc/whats-new.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@ Breaking changes
2525

2626
New Features
2727
~~~~~~~~~~~~
28+
- Changed `xr.ALL_DIMS` to equal python's `Ellipsis` (`...`), and changed internal usages to use
29+
`...` directly. As before, you can use this to instruct a `groupby` operation
30+
to reduce over all dimensions. While we have no plans to remove `xr.ALL_DIMS`, we suggest
31+
using `...`.
32+
By `Maximilian Roos <https://github.com/max-sixty>`_
2833
- Added integration tests against `pint <https://pint.readthedocs.io/>`_.
2934
(:pull:`3238`) by `Justus Magin <https://github.com/keewis>`_.
3035

xarray/core/common.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,10 @@
2525
from .options import OPTIONS, _get_keep_attrs
2626
from .pycompat import dask_array_type
2727
from .rolling_exp import RollingExp
28-
from .utils import Frozen, ReprObject, either_dict_or_kwargs
28+
from .utils import Frozen, either_dict_or_kwargs
2929

3030
# Used as a sentinel value to indicate a all dimensions
31-
ALL_DIMS = ReprObject("<all-dims>")
31+
ALL_DIMS = ...
3232

3333

3434
C = TypeVar("C")

xarray/core/dataset.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,6 @@
4949
)
5050
from .alignment import _broadcast_helper, _get_broadcast_dims_map_common_coords, align
5151
from .common import (
52-
ALL_DIMS,
5352
DataWithCoords,
5453
ImplementsDatasetReduce,
5554
_contains_datetime_like_objects,
@@ -4037,7 +4036,7 @@ def reduce(
40374036
Dataset with this object's DataArrays replaced with new DataArrays
40384037
of summarized data and the indicated dimension(s) removed.
40394038
"""
4040-
if dim is None or dim is ALL_DIMS:
4039+
if dim is None or dim is ...:
40414040
dims = set(self.dims)
40424041
elif isinstance(dim, str) or not isinstance(dim, Iterable):
40434042
dims = {dim}
@@ -5002,7 +5001,7 @@ def quantile(
50025001

50035002
if isinstance(dim, str):
50045003
dims = {dim}
5005-
elif dim is None or dim is ALL_DIMS:
5004+
elif dim in [None, ...]:
50065005
dims = set(self.dims)
50075006
else:
50085007
dims = set(dim)

xarray/core/groupby.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
from . import dtypes, duck_array_ops, nputils, ops
99
from .arithmetic import SupportsArithmetic
10-
from .common import ALL_DIMS, ImplementsArrayReduce, ImplementsDatasetReduce
10+
from .common import ImplementsArrayReduce, ImplementsDatasetReduce
1111
from .concat import concat
1212
from .formatting import format_array_flat
1313
from .options import _get_keep_attrs
@@ -712,7 +712,7 @@ def quantile(self, q, dim=None, interpolation="linear", keep_attrs=None):
712712
q : float in range of [0,1] (or sequence of floats)
713713
Quantile to compute, which must be between 0 and 1
714714
inclusive.
715-
dim : xarray.ALL_DIMS, str or sequence of str, optional
715+
dim : `...`, str or sequence of str, optional
716716
Dimension(s) over which to apply quantile.
717717
Defaults to the grouped dimension.
718718
interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}
@@ -769,7 +769,7 @@ def reduce(
769769
Function which can be called in the form
770770
`func(x, axis=axis, **kwargs)` to return the result of collapsing
771771
an np.ndarray over an integer valued axis.
772-
dim : xarray.ALL_DIMS, str or sequence of str, optional
772+
dim : `...`, str or sequence of str, optional
773773
Dimension(s) over which to apply `func`.
774774
axis : int or sequence of int, optional
775775
Axis(es) over which to apply `func`. Only one of the 'dimension'
@@ -794,9 +794,9 @@ def reduce(
794794
if keep_attrs is None:
795795
keep_attrs = _get_keep_attrs(default=False)
796796

797-
if dim is not ALL_DIMS and dim not in self.dims:
797+
if dim is not ... and dim not in self.dims:
798798
raise ValueError(
799-
"cannot reduce over dimension %r. expected either xarray.ALL_DIMS to reduce over all dimensions or one or more of %r."
799+
"cannot reduce over dimension %r. expected either '...' to reduce over all dimensions or one or more of %r."
800800
% (dim, self.dims)
801801
)
802802

@@ -867,7 +867,7 @@ def reduce(self, func, dim=None, keep_attrs=None, **kwargs):
867867
Function which can be called in the form
868868
`func(x, axis=axis, **kwargs)` to return the result of collapsing
869869
an np.ndarray over an integer valued axis.
870-
dim : xarray.ALL_DIMS, str or sequence of str, optional
870+
dim : `...`, str or sequence of str, optional
871871
Dimension(s) over which to apply `func`.
872872
axis : int or sequence of int, optional
873873
Axis(es) over which to apply `func`. Only one of the 'dimension'
@@ -895,9 +895,9 @@ def reduce(self, func, dim=None, keep_attrs=None, **kwargs):
895895
def reduce_dataset(ds):
896896
return ds.reduce(func, dim, keep_attrs, **kwargs)
897897

898-
if dim is not ALL_DIMS and dim not in self.dims:
898+
if dim is not ... and dim not in self.dims:
899899
raise ValueError(
900-
"cannot reduce over dimension %r. expected either xarray.ALL_DIMS to reduce over all dimensions or one or more of %r."
900+
"cannot reduce over dimension %r. expected either '...' to reduce over all dimensions or one or more of %r."
901901
% (dim, self.dims)
902902
)
903903

xarray/core/variable.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1450,7 +1450,7 @@ def reduce(
14501450
Array with summarized data and the indicated dimension(s)
14511451
removed.
14521452
"""
1453-
if dim is common.ALL_DIMS:
1453+
if dim == ...:
14541454
dim = None
14551455
if dim is not None and axis is not None:
14561456
raise ValueError("cannot supply both 'axis' and 'dim' arguments")

xarray/tests/test_dask.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -435,8 +435,8 @@ def test_groupby(self):
435435
u = self.eager_array
436436
v = self.lazy_array
437437

438-
expected = u.groupby("x").mean(xr.ALL_DIMS)
439-
actual = v.groupby("x").mean(xr.ALL_DIMS)
438+
expected = u.groupby("x").mean(...)
439+
actual = v.groupby("x").mean(...)
440440
self.assertLazyAndAllClose(expected, actual)
441441

442442
def test_groupby_first(self):

xarray/tests/test_dataarray.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
from xarray.coding.times import CFDatetimeCoder
1414
from xarray.convert import from_cdms2
1515
from xarray.core import dtypes
16-
from xarray.core.common import ALL_DIMS, full_like
16+
from xarray.core.common import full_like
1717
from xarray.tests import (
1818
LooseVersion,
1919
ReturnItem,
@@ -2443,8 +2443,8 @@ def test_groupby_sum(self):
24432443
"abc": Variable(["abc"], np.array(["a", "b", "c"])),
24442444
}
24452445
)["foo"]
2446-
assert_allclose(expected_sum_all, grouped.reduce(np.sum, dim=ALL_DIMS))
2447-
assert_allclose(expected_sum_all, grouped.sum(ALL_DIMS))
2446+
assert_allclose(expected_sum_all, grouped.reduce(np.sum, dim=...))
2447+
assert_allclose(expected_sum_all, grouped.sum(...))
24482448

24492449
expected = DataArray(
24502450
[
@@ -2456,7 +2456,7 @@ def test_groupby_sum(self):
24562456
)
24572457
actual = array["y"].groupby("abc").apply(np.sum)
24582458
assert_allclose(expected, actual)
2459-
actual = array["y"].groupby("abc").sum(ALL_DIMS)
2459+
actual = array["y"].groupby("abc").sum(...)
24602460
assert_allclose(expected, actual)
24612461

24622462
expected_sum_axis1 = Dataset(
@@ -2590,9 +2590,9 @@ def test_groupby_math(self):
25902590
assert_identical(expected, actual)
25912591

25922592
grouped = array.groupby("abc")
2593-
expected_agg = (grouped.mean(ALL_DIMS) - np.arange(3)).rename(None)
2593+
expected_agg = (grouped.mean(...) - np.arange(3)).rename(None)
25942594
actual = grouped - DataArray(range(3), [("abc", ["a", "b", "c"])])
2595-
actual_agg = actual.groupby("abc").mean(ALL_DIMS)
2595+
actual_agg = actual.groupby("abc").mean(...)
25962596
assert_allclose(expected_agg, actual_agg)
25972597

25982598
with raises_regex(TypeError, "only support binary ops"):
@@ -2698,7 +2698,7 @@ def test_groupby_multidim(self):
26982698
("lon", DataArray([5, 28, 23], coords=[("lon", [30.0, 40.0, 50.0])])),
26992699
("lat", DataArray([16, 40], coords=[("lat", [10.0, 20.0])])),
27002700
]:
2701-
actual_sum = array.groupby(dim).sum(ALL_DIMS)
2701+
actual_sum = array.groupby(dim).sum(...)
27022702
assert_identical(expected_sum, actual_sum)
27032703

27042704
def test_groupby_multidim_apply(self):

xarray/tests/test_dataset.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111

1212
import xarray as xr
1313
from xarray import (
14-
ALL_DIMS,
1514
DataArray,
1615
Dataset,
1716
IndexVariable,
@@ -3327,7 +3326,7 @@ def test_groupby_reduce(self):
33273326

33283327
expected = data.mean("y")
33293328
expected["yonly"] = expected["yonly"].variable.set_dims({"x": 3})
3330-
actual = data.groupby("x").mean(ALL_DIMS)
3329+
actual = data.groupby("x").mean(...)
33313330
assert_allclose(expected, actual)
33323331

33333332
actual = data.groupby("x").mean("y")
@@ -3336,12 +3335,12 @@ def test_groupby_reduce(self):
33363335
letters = data["letters"]
33373336
expected = Dataset(
33383337
{
3339-
"xy": data["xy"].groupby(letters).mean(ALL_DIMS),
3338+
"xy": data["xy"].groupby(letters).mean(...),
33403339
"xonly": (data["xonly"].mean().variable.set_dims({"letters": 2})),
33413340
"yonly": data["yonly"].groupby(letters).mean(),
33423341
}
33433342
)
3344-
actual = data.groupby("letters").mean(ALL_DIMS)
3343+
actual = data.groupby("letters").mean(...)
33453344
assert_allclose(expected, actual)
33463345

33473346
def test_groupby_math(self):
@@ -3404,14 +3403,14 @@ def test_groupby_math_virtual(self):
34043403
{"x": ("t", [1, 2, 3])}, {"t": pd.date_range("20100101", periods=3)}
34053404
)
34063405
grouped = ds.groupby("t.day")
3407-
actual = grouped - grouped.mean(ALL_DIMS)
3406+
actual = grouped - grouped.mean(...)
34083407
expected = Dataset({"x": ("t", [0, 0, 0])}, ds[["t", "t.day"]])
34093408
assert_identical(actual, expected)
34103409

34113410
def test_groupby_nan(self):
34123411
# nan should be excluded from groupby
34133412
ds = Dataset({"foo": ("x", [1, 2, 3, 4])}, {"bar": ("x", [1, 1, 2, np.nan])})
3414-
actual = ds.groupby("bar").mean(ALL_DIMS)
3413+
actual = ds.groupby("bar").mean(...)
34153414
expected = Dataset({"foo": ("bar", [1.5, 3]), "bar": [1, 2]})
34163415
assert_identical(actual, expected)
34173416

@@ -3421,7 +3420,7 @@ def test_groupby_order(self):
34213420
for vn in ["a", "b", "c"]:
34223421
ds[vn] = DataArray(np.arange(10), dims=["t"])
34233422
data_vars_ref = list(ds.data_vars.keys())
3424-
ds = ds.groupby("t").mean(ALL_DIMS)
3423+
ds = ds.groupby("t").mean(...)
34253424
data_vars = list(ds.data_vars.keys())
34263425
assert data_vars == data_vars_ref
34273426
# coords are now at the end of the list, so the test below fails

0 commit comments

Comments
 (0)