Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adapt to CF conventions 1.9 - remove gregorian calendar #935

Merged
merged 7 commits into from
Nov 25, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 4 additions & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ New features and enhancements
* Added an optimized pathway for ``xclim.indices.run_length`` functions when ``window=1``. (:pull:`911`, :issue:`910`).
* The data input frequency expected by ``Indicator``s is now in the ``src_freq`` attribute and is thus controlable by subclassing existing indicators. (:issue:`898`, :pull:`927`).

Breaking changes
~~~~~~~~~~~~~~~~
* Following version 1.9 of the CF Conventions, publised in September 2021, the calendar name "gregorian" is deprecated. ``core.calendar.get_calendar`` will return "standard", even if the underlying cftime objects still use "gregorian" (cftime <= 1.5.1). (:pull:`935`).

Internal changes
~~~~~~~~~~~~~~~~
* Removed some logging configurations in ``dataflags`` that were polluting python's main logging configuration. (:pull:`909`).
Expand Down
16 changes: 11 additions & 5 deletions xclim/core/calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,19 +70,23 @@ def get_calendar(obj: Any, dim: str = "time") -> str:
-------
str
The cftime calendar name or "default" when the data is using numpy's or python's datetime types.
Will always return "standard" instead of "gregorian", following CF conventions 1.9.
"""
if isinstance(obj, (xr.DataArray, xr.Dataset)):
if obj[dim].dtype == "O":
obj = obj[dim].where(obj[dim].notnull(), drop=True)[0].item()
elif "datetime64" in obj[dim].dtype.name:
return "default"

obj = np.take(
obj, 0
) # Take zeroth element, overcome cases when arrays or lists are passed.
elif isinstance(obj, xr.CFTimeIndex):
obj = obj.values[0]
else:
obj = np.take(obj, 0)
# Take zeroth element, overcome cases when arrays or lists are passed.
if isinstance(obj, pydt.datetime): # Also covers pandas Timestamp
return "default"
if isinstance(obj, cftime.datetime):
if obj.calendar == "gregorian":
return "standard"
Comment on lines +88 to +89
Copy link
Collaborator

Choose a reason for hiding this comment

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

Perhaps this comment is out of scope, but would we want to emit a warning here about this change of calendar? I don't think we specify any output Conventions to our datasets. Should we be appending this information to our output Datasets?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I think we do not add this attribute, simply because we don't output Datasets. If we ever do, than I guess we could append the info. And if we do, we'll have to be even more careful about this kind of change.

It's a good question. But I believe that this change doesn't need a warning :

  1. CF conventions have always accepted "standard" as equivalent to "gregorian", they just dropped the latter recently.
  2. Code might "break", but only with cftime <= 1.5.1. For people using the forthcoming cftime 1.5.2, this break will be generalized and we will be able to shift responsability to them ;).

Copy link
Collaborator

@Zeitsperre Zeitsperre Nov 25, 2021

Choose a reason for hiding this comment

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

If that's the case, is this an event where we should bump the required version of CFtime within xclim?

EDIT: the new CFtime isn't released yet. Never mind for now.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

It's not released yet! That bug was found because of our smart tox builds using the master!

return obj.calendar

raise ValueError(f"Calendar could not be inferred from object of type {type(obj)}.")
Expand Down Expand Up @@ -450,14 +454,16 @@ def ensure_cftime_array(
) -> Union[CFTimeIndex, np.ndarray]:
"""Convert an input 1D array to an array of cftime objects.

Python's datetime are converted to cftime.DatetimeGregorian.
Python's datetime are converted to cftime.DatetimeGregorian ("standard" calendar).

Raises ValueError when unable to cast the input.
"""
if isinstance(time, xr.DataArray):
time = time.indexes["time"]
elif isinstance(time, np.ndarray):
time = pd.DatetimeIndex(time)
if isinstance(time, xr.CFTimeIndex):
return time.values
if isinstance(time[0], cftime.datetime):
return time
if isinstance(time[0], pydt.datetime):
Expand Down
14 changes: 7 additions & 7 deletions xclim/testing/tests/test_calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ def test_convert_calendar_missing(source, target, freq):
("standard", "noleap"),
("noleap", "default"),
("standard", "360_day"),
("360_day", "gregorian"),
("360_day", "standard"),
("noleap", "all_leap"),
("360_day", "noleap"),
],
Expand Down Expand Up @@ -368,20 +368,20 @@ def test_interp_calendar(source, target):
dims=("time",),
name="time",
),
"gregorian",
"standard",
),
(date_range("2004-01-01", "2004-01-10", freq="D"), "gregorian"),
(date_range("2004-01-01", "2004-01-10", freq="D"), "standard"),
(
xr.DataArray(date_range("2004-01-01", "2004-01-10", freq="D")).values,
"gregorian",
"standard",
),
(date_range("2004-01-01", "2004-01-10", freq="D"), "gregorian"),
(date_range("2004-01-01", "2004-01-10", freq="D"), "standard"),
(date_range("2004-01-01", "2004-01-10", freq="D", calendar="julian"), "julian"),
],
)
def test_ensure_cftime_array(inp, calout):
out = ensure_cftime_array(inp)
assert out[0].calendar == calout
assert get_calendar(out) == calout


@pytest.mark.parametrize(
Expand All @@ -391,7 +391,7 @@ def test_ensure_cftime_array(inp, calout):
(2004, "noleap", 365),
(2004, "all_leap", 366),
(1500, "default", 365),
(1500, "gregorian", 366),
(1500, "standard", 366),
(1500, "proleptic_gregorian", 365),
(2030, "360_day", 360),
],
Expand Down