Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
7 changes: 6 additions & 1 deletion src/xarray_regrid/methods/flox_reduce.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,12 @@ def compute_mode(
expected_groups=(pd.Index(values.astype(data)), *bounds),
fill_value=-1,
)
result = result.idxmax(array_name) if not anti_mode else result.idxmin(array_name)
if anti_mode:
# Labels absent from a cell have the fill count (-1): exclude them.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for catching this issue!

absent = np.iinfo(result.dtype).max
result = result.where(result > 0, absent).idxmin(array_name)
else:
result = result.idxmax(array_name)

result = restore_properties(result, data, target_ds, coords, fill_value)
result = result.reindex_like(target_coords, copy=False)
Expand Down
22 changes: 17 additions & 5 deletions tests/test_reduce.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,12 +110,24 @@ def test_most_common(dummy_lc_data, dummy_target_grid):
assert regrid_result.dtype == input_data_int.dtype


def test_least_common(dummy_lc_data, dummy_target_grid):
# Currently just test if the method runs: code is 99% the same as most_common

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Might be nicer to keep this test but with a correct expected outcome rather than a new test that doesn't reuse the old fixtures.

i.e.;

expected_data = np.array(
    [
        [2, 2, 0, 0, 0, 0],
        [0, 2, 2, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [3, 0, 0, 0, 0, 1],
    ],
    dtype="uint8",
)

This expected result will fail on main but is correct for this fixed branch.

dummy_lc_data["lc"].regrid.least_common(
dummy_target_grid,
values=EXP_LABELS,
def test_least_common():
# Each 2x2 block is one target cell: {3,3,3,4}, {1,1,1,2}, {2,2,2,2}, {4,4,4,3}.
# Labels absent from a cell must not be selected.
axis = [0.5, 1.5, 2.5, 3.5]
data = xr.DataArray(
np.array(
[[3, 3, 1, 1], [3, 4, 1, 2], [2, 2, 4, 4], [2, 2, 4, 3]], dtype="uint8"
),
dims=("y", "x"),
coords={"y": axis, "x": axis},
name="lc",
)
target = xr.Dataset(coords={"y": [1.0, 3.0], "x": [1.0, 3.0]})

result = data.regrid.least_common(target, values=np.array([1, 2, 3, 4]))

assert_array_equal(result.values, [[4, 2], [2, 3]])
assert result.dtype == data.dtype


def test_oversized_most_common(dummy_lc_data, oversized_dummy_target_grid):
Expand Down
Loading