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

flox: don't set fill_value where possible #9433

Merged
merged 10 commits into from
Sep 18, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
2 changes: 2 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ Bug fixes
- Fix deprecation warning that was raised when calling ``np.array`` on an ``xr.DataArray``
in NumPy 2.0 (:issue:`9312`, :pull:`9393`)
By `Andrew Scherer <https://github.com/andrew-s28>`_.
- Fix a few bugs affecting groupby reductions with `flox`. (:issue:`8090`, :issue:`9398`).
By `Deepak Cherian <https://github.com/dcherian>`_.

Performance
~~~~~~~~~~~
Expand Down
4 changes: 2 additions & 2 deletions xarray/core/dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -6785,8 +6785,8 @@ def groupby(

>>> da.groupby("letters").sum()
<xarray.DataArray (letters: 2, y: 3)> Size: 48B
array([[ 9., 11., 13.],
[ 9., 11., 13.]])
array([[ 9, 11, 13],
[ 9, 11, 13]])
Coordinates:
* letters (letters) object 16B 'a' 'b'
Dimensions without coordinates: y
Expand Down
2 changes: 1 addition & 1 deletion xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -10387,7 +10387,7 @@ def groupby(
* letters (letters) object 16B 'a' 'b'
Dimensions without coordinates: y
Data variables:
foo (letters, y) float64 48B 9.0 11.0 13.0 9.0 11.0 13.0
foo (letters, y) int64 48B 9 11 13 9 11 13
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an improvement, since dtype is preserved now


Grouping by multiple variables

Expand Down
30 changes: 12 additions & 18 deletions xarray/core/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -787,14 +787,12 @@ def _maybe_restore_empty_groups(self, combined):
"""Our index contained empty groups (e.g., from a resampling or binning). If we
reduced on that dimension, we want to restore the full index.
"""
from xarray.groupers import BinGrouper, TimeResampler

has_missing_groups = (
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice generalization.

self.encoded.unique_coord.size != self.encoded.full_index.size
)
indexers = {}
for grouper in self.groupers:
if (
isinstance(grouper.grouper, BinGrouper | TimeResampler)
and grouper.name in combined.dims
):
if has_missing_groups and grouper.name in combined._indexes:
Copy link
Contributor Author

@dcherian dcherian Sep 5, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The switch from .dims to ._indexes is a bugfix. It was caught by existing multiple grouper tests

indexers[grouper.name] = grouper.full_index
if indexers:
combined = combined.reindex(**indexers)
Expand Down Expand Up @@ -849,10 +847,6 @@ def _flox_reduce(
else obj._coords
)

any_isbin = any(
isinstance(grouper.grouper, BinGrouper) for grouper in self.groupers
)

if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=True)

Expand Down Expand Up @@ -926,14 +920,14 @@ def _flox_reduce(
):
raise ValueError(f"cannot reduce over dimensions {dim}.")

if kwargs["func"] not in ["all", "any", "count"]:
kwargs.setdefault("fill_value", np.nan)
if any_isbin and kwargs["func"] == "count":
# This is an annoying hack. Xarray returns np.nan
# when there are no observations in a bin, instead of 0.
# We can fake that here by forcing min_count=1.
# note min_count makes no sense in the xarray world
# as a kwarg for count, so this should be OK
has_missing_groups = (
self.encoded.unique_coord.size != self.encoded.full_index.size
)
if has_missing_groups or kwargs.get("min_count", 0) > 0:
# Xarray *always* returns np.nan when there are no observations in a group,
# We can fake that here by forcing min_count=1 when it is not set.
# This handles boolean reductions, and count
# See GH8090, GH9398
kwargs.setdefault("fill_value", np.nan)
kwargs.setdefault("min_count", 1)

Expand Down
52 changes: 52 additions & 0 deletions xarray/tests/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -2784,6 +2784,58 @@
# ------


@pytest.mark.parametrize(
"reduction", ["max", "min", "nanmax", "nanmin", "sum", "nansum", "prod", "nanprod"]
)
def test_groupby_preserve_dtype(reduction):
# all groups are present, we should follow numpy exactly
ds = xr.Dataset(
{
"test": (
["x", "y"],
np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype="int16"),
)
},
coords={"idx": ("x", [1, 2, 1])},
)

kwargs = {}
if "nan" in reduction:
kwargs["skipna"] = True
# TODO: fix dtype with numbagg/bottleneck and use_flox=False
with xr.set_options(use_numbagg=False, use_bottleneck=False):
actual = getattr(ds.groupby("idx"), reduction.removeprefix("nan"))(
**kwargs
).test.dtype
expected = getattr(np, reduction)(ds.test.data, axis=0).dtype

assert actual == expected

Check failure on line 2812 in xarray/tests/test_groupby.py

View workflow job for this annotation

GitHub Actions / ubuntu-latest py3.10 min-all-deps

test_groupby_preserve_dtype[sum] AssertionError: assert dtype('int16') == dtype('int64')

Check failure on line 2812 in xarray/tests/test_groupby.py

View workflow job for this annotation

GitHub Actions / ubuntu-latest py3.10 min-all-deps

test_groupby_preserve_dtype[nansum] AssertionError: assert dtype('int16') == dtype('int64')

Check failure on line 2812 in xarray/tests/test_groupby.py

View workflow job for this annotation

GitHub Actions / ubuntu-latest py3.10 min-all-deps

test_groupby_preserve_dtype[prod] AssertionError: assert dtype('int16') == dtype('int64')

Check failure on line 2812 in xarray/tests/test_groupby.py

View workflow job for this annotation

GitHub Actions / ubuntu-latest py3.10 min-all-deps

test_groupby_preserve_dtype[nanprod] AssertionError: assert dtype('int16') == dtype('int64')


@requires_flox
@pytest.mark.parametrize("reduction", ["any", "all", "count"])
def test_gappy_resample_reductions(reduction):
# GH8090
dates = (("1988-12-01", "1990-11-30"), ("2000-12-01", "2001-11-30"))
times = [xr.date_range(*d, freq="D") for d in dates]

da = xr.concat(
[
xr.DataArray(np.random.rand(len(t)), coords={"time": t}, dims="time")
for t in times
],
dim="time",
).chunk(time=100)

Check failure on line 2828 in xarray/tests/test_groupby.py

View workflow job for this annotation

GitHub Actions / ubuntu-latest py3.11 all-but-dask

test_gappy_resample_reductions[any] ValueError: unrecognized chunk manager dask - must be one of: []

Check failure on line 2828 in xarray/tests/test_groupby.py

View workflow job for this annotation

GitHub Actions / ubuntu-latest py3.11 all-but-dask

test_gappy_resample_reductions[all] ValueError: unrecognized chunk manager dask - must be one of: []

Check failure on line 2828 in xarray/tests/test_groupby.py

View workflow job for this annotation

GitHub Actions / ubuntu-latest py3.11 all-but-dask

test_gappy_resample_reductions[count] ValueError: unrecognized chunk manager dask - must be one of: []

rs = (da > 0.5).resample(time="YS-DEC")
method = getattr(rs, reduction)
with xr.set_options(use_flox=True):
actual = method(dim="time")
with xr.set_options(use_flox=False):
expected = method(dim="time")
assert_identical(expected, actual)


# Possible property tests
# 1. lambda x: x
# 2. grouped-reduce on unique coords is identical to array
Expand Down
Loading