Skip to content

Commit

Permalink
Preserve order of variables in combine_by_coords (#9070)
Browse files Browse the repository at this point in the history
* FIX: do not sort datasets in combine_by_coords

* add test

* add whats-new.rst entry

* use groupby_defaultdict

* Apply suggestions from code review

Co-authored-by: Michael Niklas  <[email protected]>

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix typing

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update xarray/core/combine.py

* fix typing, replace other occurrence

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix groupby

* fix groupby

---------

Co-authored-by: Michael Niklas <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Deepak Cherian <[email protected]>
  • Loading branch information
4 people authored Jan 30, 2025
1 parent 97a4a71 commit 5b3f127
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 9 deletions.
2 changes: 2 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@ Bug fixes
By `Kai Mühlbauer <https://github.com/kmuehlbauer>`_.
- Fix weighted ``polyfit`` for arrays with more than two dimensions (:issue:`9972`, :pull:`9974`).
By `Mattia Almansi <https://github.com/malmans2>`_.
- Preserve order of variables in :py:func:`xarray.combine_by_coords` (:issue:`8828`, :pull:`9070`).
By `Kai Mühlbauer <https://github.com/kmuehlbauer>`_.
- Cast ``numpy`` scalars to arrays in :py:meth:`NamedArray.from_arrays` (:issue:`10005`, :pull:`10008`)
By `Justus Magin <https://github.com/keewis>`_.

Expand Down
28 changes: 19 additions & 9 deletions xarray/core/combine.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
from __future__ import annotations

import itertools
from collections import Counter
from collections.abc import Iterable, Iterator, Sequence
from collections import Counter, defaultdict
from collections.abc import Callable, Hashable, Iterable, Iterator, Sequence
from typing import TYPE_CHECKING, Literal, TypeVar, Union, cast

import pandas as pd
Expand Down Expand Up @@ -269,10 +268,7 @@ def _combine_all_along_first_dim(
combine_attrs: CombineAttrsOptions = "drop",
):
# Group into lines of datasets which must be combined along dim
# need to sort by _new_tile_id first for groupby to work
# TODO: is the sorted need?
combined_ids = dict(sorted(combined_ids.items(), key=_new_tile_id))
grouped = itertools.groupby(combined_ids.items(), key=_new_tile_id)
grouped = groupby_defaultdict(list(combined_ids.items()), key=_new_tile_id)

# Combine all of these datasets along dim
new_combined_ids = {}
Expand Down Expand Up @@ -606,6 +602,21 @@ def vars_as_keys(ds):
return tuple(sorted(ds))


K = TypeVar("K", bound=Hashable)


def groupby_defaultdict(
iter: list[T],
key: Callable[[T], K],
) -> Iterator[tuple[K, Iterator[T]]]:
"""replacement for itertools.groupby"""
idx = defaultdict(list)
for i, obj in enumerate(iter):
idx[key(obj)].append(i)
for k, ix in idx.items():
yield k, (iter[i] for i in ix)


def _combine_single_variable_hypercube(
datasets,
fill_value=dtypes.NA,
Expand Down Expand Up @@ -965,8 +976,7 @@ def combine_by_coords(
]

# Group by data vars
sorted_datasets = sorted(data_objects, key=vars_as_keys)
grouped_by_vars = itertools.groupby(sorted_datasets, key=vars_as_keys)
grouped_by_vars = groupby_defaultdict(data_objects, key=vars_as_keys)

# Perform the multidimensional combine on each group of data variables
# before merging back together
Expand Down
14 changes: 14 additions & 0 deletions xarray/tests/test_combine.py
Original file line number Diff line number Diff line change
Expand Up @@ -1043,6 +1043,20 @@ def test_combine_by_coords_incomplete_hypercube(self):
with pytest.raises(ValueError):
combine_by_coords([x1, x2, x3], fill_value=None)

def test_combine_by_coords_override_order(self) -> None:
# regression test for https://github.com/pydata/xarray/issues/8828
x1 = Dataset({"a": (("y", "x"), [[1]])}, coords={"y": [0], "x": [0]})
x2 = Dataset(
{"a": (("y", "x"), [[2]]), "b": (("y", "x"), [[1]])},
coords={"y": [0], "x": [0]},
)
actual = combine_by_coords([x1, x2], compat="override")
assert_equal(actual["a"], actual["b"])
assert_equal(actual["a"], x1["a"])

actual = combine_by_coords([x2, x1], compat="override")
assert_equal(actual["a"], x2["a"])


class TestCombineMixedObjectsbyCoords:
def test_combine_by_coords_mixed_unnamed_dataarrays(self):
Expand Down

0 comments on commit 5b3f127

Please sign in to comment.