Skip to content

Commit c212475

Browse files
committed
Add function to add CF axis attr to Z axis if missing for downstream xCDAT operations (#865)
1 parent c113c87 commit c212475

File tree

1 file changed

+35
-1
lines changed

1 file changed

+35
-1
lines changed

e3sm_diags/driver/utils/dataset_xr.py

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,11 @@ def _get_climo_dataset(self, season: str) -> xr.Dataset:
393393
filepath = self._get_climo_filepath(season)
394394
ds = self._open_climo_dataset(filepath)
395395

396+
# Add CF attributes to Z axes if they are missing.
397+
# NOTE: This is a temporary workaround for xCDAT.
398+
# Refer to https://github.com/xCDAT/xcdat/pull/708
399+
ds = self._add_cf_attrs_to_z_axes(ds)
400+
396401
if self.var in self.derived_vars_map:
397402
ds = self._get_dataset_with_derived_climo_var(ds)
398403
elif self.var in ds.data_vars.keys():
@@ -408,6 +413,35 @@ def _get_climo_dataset(self, season: str) -> xr.Dataset:
408413

409414
return ds
410415

416+
def _add_cf_attrs_to_z_axes(self, ds: xr.Dataset) -> xr.Dataset:
417+
"""Add CF attributes to the Z axis of the dataset if the Z axis exists.
418+
419+
This method is a temporary solution to enable xCDAT to properly
420+
retrieve bounds for Z axes that do not have CF attributes, which
421+
is required for downstream regridding operations.
422+
423+
Parameters
424+
----------
425+
ds : xr.Dataset
426+
The dataset.
427+
428+
Returns
429+
-------
430+
xr.Dataset
431+
The dataset with CF attributes added to the Z axes.
432+
"""
433+
try:
434+
dim = xc.get_dim_keys(ds, axis="Z")
435+
except KeyError:
436+
pass
437+
else:
438+
axis_attr = ds[dim].attrs.get("axis")
439+
440+
if axis_attr is None:
441+
ds[dim].attrs["axis"] = "Z"
442+
443+
return ds
444+
411445
def _open_climo_dataset(self, filepath: str) -> xr.Dataset:
412446
"""Open a climatology dataset.
413447
@@ -449,7 +483,7 @@ def _open_climo_dataset(self, filepath: str) -> xr.Dataset:
449483
args = {
450484
"paths": filepath,
451485
"decode_times": True,
452-
"add_bounds": ["X", "Y"],
486+
"add_bounds": ["X", "Y", "Z"],
453487
"coords": "minimal",
454488
"compat": "override",
455489
}

0 commit comments

Comments
 (0)