Skip to content

Commit 55fbd41

Browse files
TomNicholasshoyer
authored andcommitted
Hotfix for #2662 (#2678)
* Hotfix for #2662 * Separate keyfunc * Added a test, and made others slightly stricter * Comment explaining test better
1 parent 8d37dc3 commit 55fbd41

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

xarray/core/combine.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -493,16 +493,21 @@ def _auto_combine_all_along_first_dim(combined_ids, dim, data_vars,
493493
return new_combined_ids
494494

495495

496+
def vars_as_keys(ds):
497+
return tuple(sorted(ds))
498+
499+
496500
def _auto_combine_1d(datasets, concat_dim=_CONCAT_DIM_DEFAULT,
497501
compat='no_conflicts',
498502
data_vars='all', coords='different'):
499503
# This is just the old auto_combine function (which only worked along 1D)
500504
if concat_dim is not None:
501505
dim = None if concat_dim is _CONCAT_DIM_DEFAULT else concat_dim
502-
grouped = itertools.groupby(datasets, key=lambda ds: tuple(sorted(ds)))
506+
sorted_datasets = sorted(datasets, key=vars_as_keys)
507+
grouped_by_vars = itertools.groupby(sorted_datasets, key=vars_as_keys)
503508
concatenated = [_auto_concat(list(ds_group), dim=dim,
504509
data_vars=data_vars, coords=coords)
505-
for id, ds_group in grouped]
510+
for id, ds_group in grouped_by_vars]
506511
else:
507512
concatenated = datasets
508513
merged = merge(concatenated, compat=compat)

xarray/tests/test_combine.py

+14-2
Original file line numberDiff line numberDiff line change
@@ -650,7 +650,7 @@ def test_merge_one_dim_concat_another(self):
650650
expected = Dataset({'foo': ('x', [0, 1, 2, 3]),
651651
'bar': ('x', [10, 20, 30, 40])})
652652

653-
actual = auto_combine(objs, concat_dim=['x', None])
653+
actual = auto_combine(objs, concat_dim=['x', None], compat='equals')
654654
assert_identical(expected, actual)
655655

656656
actual = auto_combine(objs)
@@ -661,7 +661,19 @@ def test_merge_one_dim_concat_another(self):
661661
Dataset({'foo': ('x', [2, 3])})],
662662
[Dataset({'bar': ('x', [10, 20])}),
663663
Dataset({'bar': ('x', [30, 40])})]]
664-
actual = auto_combine(objs, concat_dim=[None, 'x'])
664+
actual = auto_combine(objs, concat_dim=[None, 'x'], compat='equals')
665+
assert_identical(expected, actual)
666+
667+
def test_internal_ordering(self):
668+
# This gives a MergeError if _auto_combine_1d is not sorting by
669+
# data_vars correctly, see GH #2662
670+
objs = [Dataset({'foo': ('x', [0, 1])}),
671+
Dataset({'bar': ('x', [10, 20])}),
672+
Dataset({'foo': ('x', [2, 3])}),
673+
Dataset({'bar': ('x', [30, 40])})]
674+
actual = auto_combine(objs, concat_dim='x', compat='equals')
675+
expected = Dataset({'foo': ('x', [0, 1, 2, 3]),
676+
'bar': ('x', [10, 20, 30, 40])})
665677
assert_identical(expected, actual)
666678

667679
def test_combine_concat_over_redundant_nesting(self):

0 commit comments

Comments
 (0)