Skip to content

Fix spatial weights for bounds stored with the bounds dimension first - #857

Open
maoji-y wants to merge 1 commit into
xCDAT:mainfrom
maoji-y:fix/750-spatial-bounds-dim-order
Open

maoji-y wants to merge 1 commit into
xCDAT:mainfrom
maoji-y:fix/750-spatial-bounds-dim-order

Conversation

@maoji-y

@maoji-y maoji-y commented Nov 26, 2026

Copy link
Copy Markdown

Description

SpatialAccessor.get_weights() computes the axis weights from positional slices of the bounds (domain_bounds[:, 0], domain_bounds[:, 1]), so it only works when the bounds are stored as (lat, bnds) / (lon, bnds). With bounds stored as (bnds, lat) / (bnds, lon) (valid CF, and what a transpose() produces), get_weights() silently returns weights along the bnds dimension and average() fails:

import xcdat  # noqa: F401
from tests.fixtures import generate_dataset

ds = generate_dataset(decode_times=True, cf_compliant=False, has_bounds=True)
ds["lat_bnds"] = ds.lat_bnds.transpose("bnds", "lat")
ds["lon_bnds"] = ds.lon_bnds.transpose("bnds", "lon")

ds.spatial.average("ts")
# AlignmentError: cannot reindex or align along dimension 'bnds' because of
# conflicting dimension sizes: {1, 2}

Without a longitude cell that spans the prime meridian, the same data fails with KeyError: 'The weights DataArray does not include an X axis, or the dimension names are not the same.' instead.

As discussed in #750, the bounds dimension is now identified by name instead of by position: get_weights() finds it with the existing bounds._get_bounds_dim() helper (already used for the temporal weights) and moves it last before the per-axis weight methods run. The weight methods themselves are unchanged, so bounds already stored as (lat, bnds) give the same results as before.

Bounds with extra dimensions, such as time-varying (time, lat, bnds) bounds (see #797), are still not supported. They now raise the helper's ValueError ("Bounds variable must have exactly one more dimension than the coordinate variable ...") instead of get_weights() returning weights on the wrong dimensions and average() failing with the KeyError above.

Tests:

  • New: TestGetWeights::test_dataset_weights_for_bounds_with_bounds_dim_first, TestGetWeights::test_raises_error_if_bounds_have_extra_dims and TestAverage::test_spatial_average_for_bounds_with_bounds_dim_first. All three fail on main and pass with this change.
  • Windows, Python 3.13, xarray 2026.9.0, NumPy 2.5.5, pandas 3.1.1, cf_xarray 0.11.3: full suite 485 passed. The 9 xESMF regridder tests in tests/test_regrid.py fail the same way on main, because ESMF/esmpy has no Windows build (esmpy was stubbed locally so that the test modules import).
  • Python 3.11, xarray 2024.6.0, NumPy 2.0.2, pandas 2.2.2, cf_xarray 0.10.7: tests/test_spatial.py and tests/test_bounds.py 97 passed (94 on main, where the 3 new tests fail).
  • Weights and averages for bounds stored as (lat, bnds), an nv bounds dimension, non-index lat/lon coordinates on y/x dimensions, Dask-backed bounds and data_var= are the same as on main; the transposed variants of the Dask-backed and data_var= cases now work too.
  • pre-commit run --all-files (ruff, ruff-format, mypy) passes.

AI assistance: the fix, the tests and this description were prepared with Claude Code.

Checklist

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • My changes generate no new warnings
  • Any dependent changes have been merged and published in downstream modules (N/A, no dependent changes)

If applicable:

  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass with my changes (locally and CI/CD build) (locally yes, except the xESMF tests that cannot run on Windows; CI pending)
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation (N/A, no API or documentation change)
  • I have noted that this is a breaking change for a major release (fix or feature that would cause existing functionality to not work as expected) (N/A, not a breaking change)

🤖 Generated with Claude Code

SpatialAccessor.get_weights() indexes the lower and upper bounds by
position (e.g. domain_bounds[:, 0]), which assumes the bounds are stored
as (lat, bnds). Bounds stored as (bnds, lat), which is valid CF and what
a transpose produces, made get_weights() return meaningless weights along
the bounds dimension. average() then failed with a misleading KeyError,
or with an AlignmentError when a longitude cell spans the prime meridian.

Identify the bounds dimension with the existing _get_bounds_dim() helper
and move it last before computing the weights. Bounds with extra
dimensions, such as time-varying bounds, now raise a clear ValueError
instead of returning wrong weights.

Fixes xCDAT#750

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Todo

Development

Successfully merging this pull request may close these issues.

[Bug]: Fixed order and number of dimensions assumed by spatial averager API

1 participant