Skip to content

Commit

Permalink
Added reset_encoding utility for Xarray datasets
Browse files Browse the repository at this point in the history
  • Loading branch information
jkrasting committed Dec 11, 2024
1 parent 7ca7ba7 commit 0e9c9f4
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/momlevel/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"geolocate_points",
"linear_detrend",
"monthly_average",
"reset_encoding",
"tile_nominal_coords",
"validate_areacello",
"validate_dataset",
Expand Down Expand Up @@ -491,6 +492,40 @@ def monthly_average(xobj, tcoord="time"):
return result


def reset_encoding(xobj, attrs=None):
"""Function to reset encoding attributes on an xarray object
Parameters
----------
xobj : xarray.core.dataset.Dataset or xarray.core.dataarray.DataArray
Input xarray object
attrs : list, optional
Attributes to reset, by default None
Returns
-------
xarray.core.dataset.Dataset or xarray.core.dataarray.DataArray
Xarray object without encoding attributes
"""

attrs = ["chunks", "preferred_chunks"] if attrs is None else attrs

if isinstance(xobj, xr.DataArray):
for attr in attrs:
xobj.encoding.pop(attr, None)

elif isinstance(xobj, xr.Dataset):
for attr in attrs:
xobj.encoding.pop(attr, None)
for var in xobj.variables:
xobj[var].encoding.pop(attr, None)

else:
raise ValueError("xobj must be an xarray Dataset or DataArray")

return xobj


def tile_nominal_coords(xcoord, ycoord, warn=True):
"""Function to convert 1-D dimensions to 2-D coordinate variables
Expand Down

0 comments on commit 0e9c9f4

Please sign in to comment.