diff --git a/cordex/accessor.py b/cordex/accessor.py index af306dc..f9f1f5a 100644 --- a/cordex/accessor.py +++ b/cordex/accessor.py @@ -5,6 +5,7 @@ # from .utils import _get_info, _guess_domain from .tables import domains +from .domain import rewrite_coords IDS = ["domain_id", "CORDEX_domain"] @@ -128,7 +129,7 @@ def info(self): def guess(self): """Guess which domain this could be. - Compares the coordinate axis information to known the + Compares the coordinate axis information to known coordinates of known CORDEX domains to guess the ``domain_id``. @@ -209,6 +210,56 @@ def map(self, projection=None): return ax # ax.set_title(CORDEX_domain) + def rewrite_coords( + self, + coords="xy", + bounds=False, + domain_id=None, + mip_era="CMIP5", + method="nearest", + ): + """ + Rewrite coordinates in a dataset. + + This function ensures that the coordinates in a dataset are consistent and can be + compared to other datasets. It can reindex the dataset based on specified coordinates + or domain information while trying to keep the original coordinate attributes. + + Parameters + ---------- + coords : str, optional + Specifies which coordinates to rewrite. Options are: + - "xy": Rewrite only the X and Y coordinates. + - "lonlat": Rewrite only the longitude and latitude coordinates. + - "all": Rewrite both X, Y, longitude, and latitude coordinates. + Default is "xy". If longitude and latitude coordinates are not present in the dataset, they will be added. + Rewriting longitude and latitude coordinates is only possible if the dataset contains a grid mapping variable. + bounds : bool, optional + If True, the function will also handle the bounds of the coordinates. If the dataset already has bounds, + they will be updated while preserving attributes and shape. If not, the bounds will be assigned. + domain_id : str, optional + The domain identifier used to obtain grid information. If not provided, the function will attempt + to use the domain_id attribute from the dataset. + mip_era : str, optional + The MIP era (e.g., "CMIP5", "CMIP6") used to determine coordinate attributes. Default is "CMIP5". + Only used if the dataset does not already contain coordinate attributes. + method : str, optional + The method used for reindexing the X and Y axis. Options include "nearest", "linear", etc. Default is "nearest". + + Returns + ------- + ds : xr.Dataset + The dataset with rewritten coordinates. + """ + return rewrite_coords( + self._obj, + coords=coords, + bounds=bounds, + domain_id=domain_id, + mip_era=mip_era, + method=method, + ) + @xr.register_dataset_accessor("cx") class CordexDatasetAccessor(CordexAccessor): diff --git a/docs/api.rst b/docs/api.rst index 7d41ca0..3207e6c 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -108,3 +108,4 @@ Methods Dataset.cx.info Dataset.cx.guess Dataset.cx.map + Dataset.cx.rewrite_coords