Skip to content

Commit 6dc0664

Browse files
Resolve "Add cmethods attributes to output files"
1 parent fc6716c commit 6dc0664

File tree

2 files changed

+47
-2
lines changed

2 files changed

+47
-2
lines changed

cmethods/core.py

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525

2626
from __future__ import annotations
2727

28+
from datetime import datetime, timezone
2829
from typing import TYPE_CHECKING, Callable, Dict, Optional
2930

3031
import xarray as xr
@@ -49,6 +50,46 @@
4950
}
5051

5152

53+
def _add_cmethods_metadata(
54+
result: xr.Dataset | xr.DataArray,
55+
method: str,
56+
**kwargs,
57+
) -> xr.Dataset | xr.DataArray:
58+
"""
59+
Add metadata to the result indicating it was processed by python-cmethods.
60+
61+
:param result: The bias-corrected dataset or dataarray
62+
:param method: The method used for bias correction
63+
:param kwargs: Additional method parameters
64+
:return: Result with added metadata
65+
"""
66+
try:
67+
from importlib.metadata import version # noqa: PLC0415
68+
69+
pkg_version = version("python-cmethods")
70+
except Exception: # noqa: BLE001
71+
pkg_version = "unknown"
72+
73+
attrs_to_add = {
74+
"cmethods_version": pkg_version,
75+
"cmethods_method": method,
76+
"cmethods_timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC"),
77+
"cmethods_source": "https://github.com/btschwertfeger/python-cmethods",
78+
}
79+
80+
if kind := kwargs.get("kind"):
81+
attrs_to_add["cmethods_kind"] = kind
82+
if n_quantiles := kwargs.get("n_quantiles"):
83+
attrs_to_add["cmethods_n_quantiles"] = str(n_quantiles)
84+
if group := kwargs.get("group"):
85+
attrs_to_add["cmethods_group"] = str(group)
86+
87+
if isinstance(result, (xr.Dataset, xr.DataArray)):
88+
result.attrs.update(attrs_to_add)
89+
90+
return result
91+
92+
5293
def apply_ufunc(
5394
method: str,
5495
obs: xr.xarray.core.dataarray.DataArray,
@@ -144,6 +185,8 @@ def adjust(
144185
:return: The bias corrected/adjusted data set
145186
:rtype: xr.xarray.core.dataarray.DataArray | xr.xarray.core.dataarray.Dataset
146187
"""
188+
metadata_kwargs = {k: v for k, v in kwargs.items() if k in {"kind", "n_quantiles", "group"}}
189+
147190
kwargs["adjust_called"] = True
148191
ensure_xr_dataarray(obs=obs, simh=simh, simp=simp)
149192

@@ -159,7 +202,8 @@ def adjust(
159202
# mock this function or apply ``CMethods.__apply_ufunc` directly
160203
# on your data sets.
161204
if kwargs.get("group") is None:
162-
return apply_ufunc(method, obs, simh, simp, **kwargs).to_dataset()
205+
result = apply_ufunc(method, obs, simh, simp, **kwargs).to_dataset()
206+
return _add_cmethods_metadata(result, method, **metadata_kwargs)
163207

164208
if method not in SCALING_METHODS:
165209
raise ValueError(
@@ -204,7 +248,7 @@ def adjust(
204248

205249
result = monthly_result if result is None else xr.merge([result, monthly_result])
206250

207-
return result
251+
return _add_cmethods_metadata(result, method, **metadata_kwargs)
208252

209253

210254
__all__ = ["adjust"]

requirements-dev.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
dask[distributed]
2+
matplotlib
23
pytest
34
pytest-cov
45
pytest-retry

0 commit comments

Comments
 (0)