Skip to content

Fix time bounds KeyError for cftime coordinates without a calendar encoding - #859

Open
JOhnsonKC201 wants to merge 2 commits into
xCDAT:mainfrom
JOhnsonKC201:bug/time-bounds-calendar-encoding
Open

JOhnsonKC201 wants to merge 2 commits into
xCDAT:mainfrom
JOhnsonKC201:bug/time-bounds-calendar-encoding

Conversation

@JOhnsonKC201

Copy link
Copy Markdown

Description

Adding time bounds to cftime time coordinates fails with KeyError: 'calendar' when the coordinates have no "calendar" key in their encoding. That is the case for time coordinates built in memory, coordinates returned by Xarray operations like resample() or convert_calendar(), and files without a calendar attribute that plain xr.open_dataset() decodes to cftime. I didn't find an existing issue for this.

import numpy as np
import xarray as xr

import xcdat  # noqa: F401

time = xr.date_range(
    "2000-01-01", periods=24, freq="MS", calendar="noleap", use_cftime=True
)
ds = xr.Dataset(
    {"ts": ("time", np.arange(24.0))},
    coords={"time": ("time", time, {"axis": "T"})},
)

ds = ds.bounds.add_missing_bounds(axes=["T"])
# KeyError: 'calendar'

Since "T" is in the default axes of add_missing_bounds() and only ValueError/TypeError are skipped there, a plain ds.bounds.add_missing_bounds() on such a dataset fails too. add_time_bounds() raises the same error.

The cause is that _create_time_bounds() reads time.encoding["calendar"] to pick the cftime date type, but that key only exists when the times were decoded from a file with a calendar attribute. The cftime objects always carry their own calendar, so I changed it to use time.dt.calendar. That also guarantees the bounds have the same calendar as the coordinates they are compared against.

I added a test that mirrors test_returns_bounds_for_cftime_time_coords_using_freq without setting the encoding. It fails on main with the KeyError and passes with the fix. The rest of the suite and pre-commit run --all-files pass locally. I ran the tests in a pip environment without ESMF, so the 9 xESMF regridding tests could not run there; they fail the same way on main in that environment.

TemporalAccessor handles the same situation by defaulting to the "standard" calendar with a warning, so for example a daily climatology on 360-day data without a calendar encoding raises ValueError: invalid day number. I left that alone here to keep this focused, but I'm happy to follow up if you'd like it to use .dt.calendar as well.

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

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)
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • 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)

`_create_time_bounds()` read the calendar from `time.encoding["calendar"]`,
which is only set when Xarray decodes times from a file that has a calendar
attribute. Time coordinates created in memory, returned by operations such as
`resample()` or `convert_calendar()`, or decoded from a file without a
calendar attribute have no calendar encoding, so `add_time_bounds()` and
`add_missing_bounds()` raised `KeyError: 'calendar'`.

Get the calendar from the `cftime` objects with `.dt.calendar` instead.

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.

1 participant