From ed0397ce0b65b72aaa1d39796a25286eb5a3167f Mon Sep 17 00:00:00 2001 From: Deepak Cherian Date: Wed, 26 Jun 2024 15:51:44 -0400 Subject: [PATCH] Add .cf.crs attribute --- cf_xarray/accessor.py | 20 ++++++++++++++++++++ doc/api.rst | 2 ++ pyproject.toml | 1 + 3 files changed, 23 insertions(+) diff --git a/cf_xarray/accessor.py b/cf_xarray/accessor.py index a915335b8..541150131 100644 --- a/cf_xarray/accessor.py +++ b/cf_xarray/accessor.py @@ -8,6 +8,7 @@ from collections.abc import Hashable, Iterable, Mapping, MutableMapping, Sequence from datetime import datetime from typing import ( + TYPE_CHECKING, Any, Callable, Literal, @@ -57,6 +58,9 @@ parse_cf_standard_name_table, ) +if TYPE_CHECKING: + from pyproj import CRS + FlagParam = namedtuple("FlagParam", ["flag_mask", "flag_value"]) #: Classes wrapped by cf_xarray. @@ -2342,6 +2346,22 @@ def __getitem__(self, key: Hashable | Iterable[Hashable]) -> DataArray | Dataset """ return _getitem(self, key) + @property + def crs(self) -> CRS: + """ + Returns a ``pyproj.CRS`` instance constructed from the grid_mapping variable's attributes. + """ + from pyproj import CRS + + try: + gm = self["grid_mapping"] + except KeyError as e: + raise ValueError( + "CRS is constructed from the 'grid_mapping' variable, but that could not be detected." + ) from e + + return CRS.from_cf(gm.attrs) + @property def formula_terms(self) -> dict[Hashable, dict[str, str]]: # numpydoc ignore=SS06 """ diff --git a/doc/api.rst b/doc/api.rst index 4651f017e..cffd4295b 100644 --- a/doc/api.rst +++ b/doc/api.rst @@ -45,6 +45,7 @@ Attributes DataArray.cf.cell_measures DataArray.cf.cf_roles DataArray.cf.coordinates + DataArray.cf.crs DataArray.cf.formula_terms DataArray.cf.grid_mapping_name DataArray.cf.is_flag_variable @@ -103,6 +104,7 @@ Attributes Dataset.cf.bounds Dataset.cf.cell_measures Dataset.cf.cf_roles + Dataset.cf.crs Dataset.cf.coordinates Dataset.cf.formula_terms Dataset.cf.grid_mapping_names diff --git a/pyproject.toml b/pyproject.toml index 073b97777..f0a86ebbf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -139,6 +139,7 @@ module=[ "pandas", "pooch", "pint", + "pyproj", "matplotlib", "pytest", "shapely",