File: groupby.py

package info (click to toggle)
python-xarray 2025.08.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 11,796 kB
  • sloc: python: 115,416; makefile: 258; sh: 47
file content (191 lines) | stat: -rw-r--r-- 6,419 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# import flox to avoid the cost of first import
import cftime
import flox.xarray  # noqa: F401
import numpy as np
import pandas as pd

import xarray as xr

from . import _skip_slow, parameterized, requires_dask


class GroupBy:
    def setup(self, *args, **kwargs):
        self.n = 100
        self.ds1d = xr.Dataset(
            {
                "a": xr.DataArray(np.r_[np.repeat(1, self.n), np.repeat(2, self.n)]),
                "b": xr.DataArray(np.arange(2 * self.n)),
                "c": xr.DataArray(np.arange(2 * self.n)),
            }
        )
        self.ds2d = self.ds1d.expand_dims(z=10).copy()
        self.ds1d_mean = self.ds1d.groupby("b").mean()
        self.ds2d_mean = self.ds2d.groupby("b").mean()

    @parameterized(["ndim"], [(1, 2)])
    def time_init(self, ndim):
        getattr(self, f"ds{ndim}d").groupby("b")

    @parameterized(
        ["method", "ndim", "use_flox"], [("sum", "mean"), (1, 2), (True, False)]
    )
    def time_agg_small_num_groups(self, method, ndim, use_flox):
        ds = getattr(self, f"ds{ndim}d")
        with xr.set_options(use_flox=use_flox):
            getattr(ds.groupby("a"), method)().compute()

    @parameterized(
        ["method", "ndim", "use_flox"], [("sum", "mean"), (1, 2), (True, False)]
    )
    def time_agg_large_num_groups(self, method, ndim, use_flox):
        ds = getattr(self, f"ds{ndim}d")
        with xr.set_options(use_flox=use_flox):
            getattr(ds.groupby("b"), method)().compute()

    def time_binary_op_1d(self):
        (self.ds1d.groupby("b") - self.ds1d_mean).compute()

    def time_binary_op_2d(self):
        (self.ds2d.groupby("b") - self.ds2d_mean).compute()

    def peakmem_binary_op_1d(self):
        (self.ds1d.groupby("b") - self.ds1d_mean).compute()

    def peakmem_binary_op_2d(self):
        (self.ds2d.groupby("b") - self.ds2d_mean).compute()


class GroupByDask(GroupBy):
    def setup(self, *args, **kwargs):
        requires_dask()
        super().setup(**kwargs)

        self.ds1d = self.ds1d.sel(dim_0=slice(None, None, 2))
        self.ds1d["c"] = self.ds1d["c"].chunk({"dim_0": 50})
        self.ds2d = self.ds2d.sel(dim_0=slice(None, None, 2))
        self.ds2d["c"] = self.ds2d["c"].chunk({"dim_0": 50, "z": 5})
        self.ds1d_mean = self.ds1d.groupby("b").mean().compute()
        self.ds2d_mean = self.ds2d.groupby("b").mean().compute()


# TODO: These don't work now because we are calling `.compute` explicitly.
class GroupByPandasDataFrame(GroupBy):
    """Run groupby tests using pandas DataFrame."""

    def setup(self, *args, **kwargs):
        # Skip testing in CI as it won't ever change in a commit:
        _skip_slow()

        super().setup(**kwargs)
        self.ds1d = self.ds1d.to_dataframe()
        self.ds1d_mean = self.ds1d.groupby("b").mean()

    def time_binary_op_2d(self):
        raise NotImplementedError

    def peakmem_binary_op_2d(self):
        raise NotImplementedError


class GroupByDaskDataFrame(GroupBy):
    """Run groupby tests using dask DataFrame."""

    def setup(self, *args, **kwargs):
        # Skip testing in CI as it won't ever change in a commit:
        _skip_slow()

        requires_dask()
        super().setup(**kwargs)
        self.ds1d = self.ds1d.chunk({"dim_0": 50}).to_dask_dataframe()
        self.ds1d_mean = self.ds1d.groupby("b").mean().compute()

    def time_binary_op_2d(self):
        raise NotImplementedError

    def peakmem_binary_op_2d(self):
        raise NotImplementedError


class Resample:
    def setup(self, *args, **kwargs):
        self.ds1d = xr.Dataset(
            {
                "b": ("time", np.arange(365.0 * 24)),
            },
            coords={"time": pd.date_range("2001-01-01", freq="h", periods=365 * 24)},
        )
        self.ds2d = self.ds1d.expand_dims(z=10)
        self.ds1d_mean = self.ds1d.resample(time="48h").mean()
        self.ds2d_mean = self.ds2d.resample(time="48h").mean()

    @parameterized(["ndim"], [(1, 2)])
    def time_init(self, ndim):
        getattr(self, f"ds{ndim}d").resample(time="D")

    @parameterized(
        ["method", "ndim", "use_flox"], [("sum", "mean"), (1, 2), (True, False)]
    )
    def time_agg_small_num_groups(self, method, ndim, use_flox):
        ds = getattr(self, f"ds{ndim}d")
        with xr.set_options(use_flox=use_flox):
            getattr(ds.resample(time="3ME"), method)().compute()

    @parameterized(
        ["method", "ndim", "use_flox"], [("sum", "mean"), (1, 2), (True, False)]
    )
    def time_agg_large_num_groups(self, method, ndim, use_flox):
        ds = getattr(self, f"ds{ndim}d")
        with xr.set_options(use_flox=use_flox):
            getattr(ds.resample(time="48h"), method)().compute()


class ResampleDask(Resample):
    def setup(self, *args, **kwargs):
        requires_dask()
        super().setup(**kwargs)
        self.ds1d = self.ds1d.chunk({"time": 50})
        self.ds2d = self.ds2d.chunk({"time": 50, "z": 4})


class ResampleCFTime(Resample):
    def setup(self, *args, **kwargs):
        self.ds1d = xr.Dataset(
            {
                "b": ("time", np.arange(365.0 * 24)),
            },
            coords={
                "time": xr.date_range(
                    "2001-01-01", freq="h", periods=365 * 24, calendar="noleap"
                )
            },
        )
        self.ds2d = self.ds1d.expand_dims(z=10)
        self.ds1d_mean = self.ds1d.resample(time="48h").mean()
        self.ds2d_mean = self.ds2d.resample(time="48h").mean()


@parameterized(["use_cftime", "use_flox"], [[True, False], [True, False]])
class GroupByLongTime:
    def setup(self, use_cftime, use_flox):
        arr = np.random.randn(10, 10, 365 * 30)
        time = xr.date_range("2000", periods=30 * 365, use_cftime=use_cftime)

        # GH9426 - deep-copying CFTime object arrays is weirdly slow
        asda = xr.DataArray(time)
        labeled_time = []
        for year, month in zip(asda.dt.year, asda.dt.month, strict=True):
            labeled_time.append(cftime.datetime(year, month, 1))

        self.da = xr.DataArray(
            arr,
            dims=("y", "x", "time"),
            coords={"time": time, "time2": ("time", labeled_time)},
        )

    def time_setup(self, use_cftime, use_flox):
        self.da.groupby("time.month")

    def time_mean(self, use_cftime, use_flox):
        with xr.set_options(use_flox=use_flox):
            self.da.groupby("time.year").mean()