Skip to content

Commit e4c5014

Browse files
committed
Add attribute tracking functionality
1 parent 16d8c39 commit e4c5014

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

cf_xarray/__init__.py

+2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
from . import tracking # noqa
12
from .accessor import CFAccessor # noqa
23
from .helpers import bounds_to_vertices, vertices_to_bounds # noqa
34
from .options import set_options # noqa
5+
from .tracking import track_cf_attributes # noqa
46
from .utils import _get_version
57

68
__version__ = _get_version()

cf_xarray/tracking.py

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# This module provides functions for adding CF attribtues
2+
# and tracking history, provenance using xarray's keep_attrs
3+
# functionality
4+
5+
import copy
6+
import functools
7+
8+
CELL_METHODS = {
9+
"sum": "sum",
10+
"max": "maximum",
11+
"min": "minimum",
12+
"median": "median",
13+
"mean": "mean",
14+
"std": "standard_deviation",
15+
"var": "variance",
16+
}
17+
18+
19+
def add_cell_methods(attrs, context):
20+
"""Add appropriate cell_methods attribute."""
21+
assert len(attrs) == 1
22+
cell_methods = attrs[0].get("cell_methods", "")
23+
# TODO: get dim_name from context
24+
return {"cell_methods": f"dim_name: {CELL_METHODS[context.func]} {cell_methods}"}
25+
26+
27+
def add_history(attrs, context):
28+
return {"history": None}
29+
30+
31+
def _tracker(
32+
attrs,
33+
context,
34+
strict: bool = False,
35+
cell_methods: bool = True,
36+
history: bool = True,
37+
):
38+
39+
# can only handle single variable attrs for now
40+
assert len(attrs) == 1
41+
attrs_out = copy.deepcopy(attrs[0])
42+
43+
if cell_methods and context.func in CELL_METHODS:
44+
attrs_out.update(add_cell_methods(attrs, context))
45+
if history:
46+
attrs_out.update(add_history(attrs, context))
47+
pass
48+
return attrs_out
49+
50+
51+
def track_cf_attributes(
52+
*, strict: bool = False, cell_methods: bool = True, history: bool = True
53+
):
54+
"""Top-level user-facing function.
55+
56+
Parameters
57+
----------
58+
strict: bool
59+
Controls if an error is raised when an appropriate attribute cannot
60+
be added because of lack of information.
61+
cell_methods: bool
62+
Add cell_methods attribute when possible
63+
history: bool
64+
Adds a history attribute like NCO and follows the NUG convention.
65+
"""
66+
return functools.partial(
67+
_tracker, strict=strict, cell_methods=cell_methods, history=history
68+
)

0 commit comments

Comments
 (0)