rioxarray 0.20.0__tar.gz → 0.22.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. {rioxarray-0.20.0 → rioxarray-0.22.0}/AUTHORS.rst +4 -2
  2. {rioxarray-0.20.0 → rioxarray-0.22.0}/CONTRIBUTING.rst +27 -2
  3. {rioxarray-0.20.0/rioxarray.egg-info → rioxarray-0.22.0}/PKG-INFO +3 -3
  4. {rioxarray-0.20.0 → rioxarray-0.22.0}/README.rst +1 -1
  5. {rioxarray-0.20.0 → rioxarray-0.22.0}/pyproject.toml +30 -2
  6. rioxarray-0.22.0/rioxarray/_convention/__init__.py +4 -0
  7. rioxarray-0.22.0/rioxarray/_convention/_base.py +52 -0
  8. rioxarray-0.22.0/rioxarray/_convention/_core.py +176 -0
  9. rioxarray-0.22.0/rioxarray/_convention/cf.py +247 -0
  10. rioxarray-0.22.0/rioxarray/_convention/zarr.py +336 -0
  11. {rioxarray-0.20.0 → rioxarray-0.22.0}/rioxarray/_io.py +15 -4
  12. {rioxarray-0.20.0 → rioxarray-0.22.0}/rioxarray/_options.py +18 -2
  13. rioxarray-0.22.0/rioxarray/_spatial_utils.py +503 -0
  14. rioxarray-0.22.0/rioxarray/enum.py +49 -0
  15. {rioxarray-0.20.0 → rioxarray-0.22.0}/rioxarray/merge.py +1 -1
  16. {rioxarray-0.20.0 → rioxarray-0.22.0}/rioxarray/raster_array.py +135 -236
  17. {rioxarray-0.20.0 → rioxarray-0.22.0}/rioxarray/raster_writer.py +45 -20
  18. {rioxarray-0.20.0 → rioxarray-0.22.0}/rioxarray/rioxarray.py +149 -403
  19. {rioxarray-0.20.0 → rioxarray-0.22.0/rioxarray.egg-info}/PKG-INFO +3 -3
  20. {rioxarray-0.20.0 → rioxarray-0.22.0}/rioxarray.egg-info/SOURCES.txt +8 -1
  21. {rioxarray-0.20.0 → rioxarray-0.22.0}/rioxarray.egg-info/requires.txt +1 -1
  22. {rioxarray-0.20.0 → rioxarray-0.22.0}/LICENSE +0 -0
  23. {rioxarray-0.20.0 → rioxarray-0.22.0}/LICENSE_datacube +0 -0
  24. {rioxarray-0.20.0 → rioxarray-0.22.0}/LICENSE_xarray +0 -0
  25. {rioxarray-0.20.0 → rioxarray-0.22.0}/MANIFEST.in +0 -0
  26. {rioxarray-0.20.0 → rioxarray-0.22.0}/rioxarray/__init__.py +0 -0
  27. {rioxarray-0.20.0 → rioxarray-0.22.0}/rioxarray/_show_versions.py +0 -0
  28. {rioxarray-0.20.0 → rioxarray-0.22.0}/rioxarray/crs.py +0 -0
  29. {rioxarray-0.20.0 → rioxarray-0.22.0}/rioxarray/exceptions.py +0 -0
  30. {rioxarray-0.20.0 → rioxarray-0.22.0}/rioxarray/py.typed +0 -0
  31. {rioxarray-0.20.0 → rioxarray-0.22.0}/rioxarray/raster_dataset.py +0 -0
  32. {rioxarray-0.20.0 → rioxarray-0.22.0}/rioxarray/xarray_plugin.py +0 -0
  33. {rioxarray-0.20.0 → rioxarray-0.22.0}/rioxarray.egg-info/dependency_links.txt +0 -0
  34. {rioxarray-0.20.0 → rioxarray-0.22.0}/rioxarray.egg-info/entry_points.txt +0 -0
  35. {rioxarray-0.20.0 → rioxarray-0.22.0}/rioxarray.egg-info/top_level.txt +0 -0
  36. {rioxarray-0.20.0 → rioxarray-0.22.0}/setup.cfg +0 -0
  37. {rioxarray-0.20.0 → rioxarray-0.22.0}/setup.py +0 -0
@@ -10,7 +10,7 @@ Thanks goes to these wonderful people (`emoji key <https://allcontributors.org/d
10
10
  <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
11
11
  <!-- prettier-ignore-start -->
12
12
  <!-- markdownlint-disable -->
13
- <table>
13
+ <table>
14
14
  <tbody>
15
15
  <tr>
16
16
  <td align="center" valign="top" width="14.28%"><a href="https://www.linkedin.com/in/alan-snow-55bb8726/"><img src="https://avatars3.githubusercontent.com/u/8699967?v=4?s=100" width="100px;" alt="Alan D. Snow"/><br /><sub><b>Alan D. Snow</b></sub></a><br /><a href="https://github.com/corteva/rioxarray/commits?author=snowman2" title="Code">💻</a> <a href="#ideas-snowman2" title="Ideas, Planning, & Feedback">🤔</a> <a href="#question-snowman2" title="Answering Questions">💬</a> <a href="https://github.com/corteva/rioxarray/issues?q=author%3Asnowman2" title="Bug reports">🐛</a> <a href="https://github.com/corteva/rioxarray/commits?author=snowman2" title="Documentation">📖</a> <a href="#example-snowman2" title="Examples">💡</a> <a href="#maintenance-snowman2" title="Maintenance">🚧</a> <a href="https://github.com/corteva/rioxarray/pulls?q=is%3Apr+reviewed-by%3Asnowman2" title="Reviewed Pull Requests">👀</a> <a href="https://github.com/corteva/rioxarray/commits?author=snowman2" title="Tests">⚠️</a></td>
@@ -31,7 +31,7 @@ Thanks goes to these wonderful people (`emoji key <https://allcontributors.org/d
31
31
  <td align="center" valign="top" width="14.28%"><a href="https://bopen.eu/"><img src="https://avatars.githubusercontent.com/u/226037?v=4?s=100" width="100px;" alt="Alessandro Amici"/><br /><sub><b>Alessandro Amici</b></sub></a><br /><a href="https://github.com/corteva/rioxarray/commits?author=alexamici" title="Code">💻</a> <a href="https://github.com/corteva/rioxarray/commits?author=alexamici" title="Documentation">📖</a> <a href="https://github.com/corteva/rioxarray/commits?author=alexamici" title="Tests">⚠️</a></td>
32
32
  </tr>
33
33
  <tr>
34
- <td align="center" valign="top" width="14.28%"><a href="https://github.com/remi-braun"><img src="https://avatars.githubusercontent.com/u/67311115?v=4?s=100" width="100px;" alt="remi-braun"/><br /><sub><b>remi-braun</b></sub></a><br /><a href="https://github.com/corteva/rioxarray/commits?author=remi-braun" title="Documentation">📖</a></td>
34
+ <td align="center" valign="top" width="14.28%"><a href="https://github.com/remi-braun"><img src="https://avatars.githubusercontent.com/u/67311115?v=4?s=100" width="100px;" alt="remi-braun"/><br /><sub><b>remi-braun</b></sub></a><br /><a href="https://github.com/corteva/rioxarray/commits?author=remi-braun" title="Documentation">📖</a> <a href="https://github.com/corteva/rioxarray/commits?author=remi-braun" title="Code">💻</a></td>
35
35
  <td align="center" valign="top" width="14.28%"><a href="http://scottyhq.github.io/"><img src="https://avatars.githubusercontent.com/u/3924836?v=4?s=100" width="100px;" alt="Scott Henderson"/><br /><sub><b>Scott Henderson</b></sub></a><br /><a href="https://github.com/corteva/rioxarray/issues?q=author%3Ascottyhq" title="Bug reports">🐛</a> <a href="https://github.com/corteva/rioxarray/commits?author=scottyhq" title="Code">💻</a> <a href="https://github.com/corteva/rioxarray/commits?author=scottyhq" title="Tests">⚠️</a></td>
36
36
  <td align="center" valign="top" width="14.28%"><a href="http://andrewannex.com/"><img src="https://avatars.githubusercontent.com/u/2126916?v=4?s=100" width="100px;" alt="Andrew Annex"/><br /><sub><b>Andrew Annex</b></sub></a><br /><a href="https://github.com/corteva/rioxarray/commits?author=AndrewAnnex" title="Code">💻</a> <a href="https://github.com/corteva/rioxarray/commits?author=AndrewAnnex" title="Documentation">📖</a> <a href="https://github.com/corteva/rioxarray/commits?author=AndrewAnnex" title="Tests">⚠️</a></td>
37
37
  <td align="center" valign="top" width="14.28%"><a href="https://github.com/fbunt"><img src="https://avatars.githubusercontent.com/u/7178572?v=4?s=100" width="100px;" alt="Fred Bunt"/><br /><sub><b>Fred Bunt</b></sub></a><br /><a href="https://github.com/corteva/rioxarray/issues?q=author%3Afbunt" title="Bug reports">🐛</a> <a href="https://github.com/corteva/rioxarray/commits?author=fbunt" title="Tests">⚠️</a> <a href="https://github.com/corteva/rioxarray/commits?author=fbunt" title="Code">💻</a></td>
@@ -68,6 +68,8 @@ Thanks goes to these wonderful people (`emoji key <https://allcontributors.org/d
68
68
  </tr>
69
69
  <tr>
70
70
  <td align="center" valign="top" width="14.28%"><a href="https://github.com/trchudley"><img src="https://avatars.githubusercontent.com/u/24896931?v=4?s=100" width="100px;" alt="Tom Chudley"/><br /><sub><b>Tom Chudley</b></sub></a><br /><a href="https://github.com/corteva/rioxarray/commits?author=trchudley" title="Code">💻</a></td>
71
+ <td align="center" valign="top" width="14.28%"><a href="https://github.com/acoque"><img src="https://avatars.githubusercontent.com/u/35691279?v=4?s=100" width="100px;" alt="acoque"/><br /><sub><b>acoque</b></sub></a><br /><a href="https://github.com/corteva/rioxarray/commits?author=acoque" title="Documentation">📖</a></td>
72
+ <td align="center" valign="top" width="14.28%"><a href="https://github.com/martijnvandermarel"><img src="https://avatars.githubusercontent.com/u/23376251?v=4?s=100" width="100px;" alt="Martijn van der Marel"/><br /><sub><b>Martijn van der Marel</b></sub></a><br /><a href="https://github.com/corteva/rioxarray/issues?q=author%3Amartijnvandermarel" title="Bug reports">🐛</a></td>
71
73
  </tr>
72
74
  </tbody>
73
75
  </table>
@@ -80,8 +80,7 @@ Using python::
80
80
 
81
81
  4. Install your local copy into a virtualenv::
82
82
 
83
- $ python -m pip install -e ".[all]"
84
- $ python -m pip install -r requirements/dev.txt
83
+ $ python -m pip install -e . --group dev
85
84
 
86
85
  5. Setup pre-commit hooks::
87
86
 
@@ -127,6 +126,32 @@ This assumes you have cloned the rioxarray repository and are in the base folder
127
126
  'source /venv/bin/activate && python -m pytest'
128
127
 
129
128
 
129
+ Build documentation
130
+ -------------------
131
+
132
+ This assumes you have cloned the rioxarray repository, installed rioxarray conda environment and are in the base folder.
133
+
134
+ 1. Install documentation libraries
135
+
136
+ .. code-block:: bash
137
+
138
+ conda activate rioxarray
139
+ conda install -c conda-forge pandoc
140
+ pip install -e . --group doc
141
+
142
+ 2. Build the documentation
143
+
144
+ .. code-block:: bash
145
+
146
+ make docs
147
+
148
+ If you are on Windows or don't have ``make`` installed:
149
+
150
+ .. code-block:: bash
151
+
152
+ sphinx-build -b html docs/ docs/_build/
153
+
154
+
130
155
  Pull Request Guidelines
131
156
  -----------------------
132
157
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rioxarray
3
- Version: 0.20.0
3
+ Version: 0.22.0
4
4
  Summary: geospatial xarray extension powered by rasterio
5
5
  Maintainer: rioxarray Contributors
6
6
  License: Apache
@@ -30,7 +30,7 @@ License-File: LICENSE_xarray
30
30
  License-File: AUTHORS.rst
31
31
  Requires-Dist: packaging
32
32
  Requires-Dist: rasterio>=1.4.3
33
- Requires-Dist: xarray>=2024.7.0
33
+ Requires-Dist: xarray>=2026.2
34
34
  Requires-Dist: pyproj>=3.3
35
35
  Requires-Dist: numpy>=2
36
36
  Provides-Extra: interp
@@ -50,7 +50,7 @@ rasterio xarray extension.
50
50
  :alt: Join the chat at https://gitter.im/rioxarray/community
51
51
  :target: https://gitter.im/rioxarray/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge
52
52
 
53
- .. image:: https://img.shields.io/badge/all_contributors-43-orange.svg?style=flat-square
53
+ .. image:: https://img.shields.io/badge/all_contributors-45-orange.svg?style=flat-square
54
54
  :alt: All Contributors
55
55
  :target: https://github.com/corteva/rioxarray/blob/master/AUTHORS.rst
56
56
 
@@ -9,7 +9,7 @@ rasterio xarray extension.
9
9
  :alt: Join the chat at https://gitter.im/rioxarray/community
10
10
  :target: https://gitter.im/rioxarray/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge
11
11
 
12
- .. image:: https://img.shields.io/badge/all_contributors-43-orange.svg?style=flat-square
12
+ .. image:: https://img.shields.io/badge/all_contributors-45-orange.svg?style=flat-square
13
13
  :alt: All Contributors
14
14
  :target: https://github.com/corteva/rioxarray/blob/master/AUTHORS.rst
15
15
 
@@ -4,7 +4,7 @@ requires = ["setuptools", "wheel"]
4
4
 
5
5
  [project]
6
6
  name = "rioxarray"
7
- version = "0.20.0"
7
+ version = "0.22.0"
8
8
  description = "geospatial xarray extension powered by rasterio"
9
9
  maintainers = [
10
10
  {name = "rioxarray Contributors"},
@@ -35,11 +35,39 @@ requires-python = ">=3.12"
35
35
  dependencies = [
36
36
  "packaging",
37
37
  "rasterio>=1.4.3",
38
- "xarray>=2024.7.0",
38
+ # https://github.com/pydata/xarray/issues/11000
39
+ "xarray>=2026.2",
39
40
  "pyproj>=3.3",
40
41
  "numpy>=2",
41
42
  ]
42
43
 
44
+ [dependency-groups]
45
+ doc = [
46
+ "sphinx-click",
47
+ "nbsphinx",
48
+ "sphinx_rtd_theme",
49
+ ]
50
+ test = [
51
+ "pytest>=3.6",
52
+ "pytest-cov",
53
+ "pytest-timeout",
54
+ "dask",
55
+ "netcdf4",
56
+ ]
57
+ type = [
58
+ "mypy",
59
+ ]
60
+ lint = [
61
+ "pylint"
62
+ ]
63
+ dev = [
64
+ "pre-commit",
65
+ {include-group = "doc"},
66
+ {include-group = "test"},
67
+ {include-group = "type"},
68
+ {include-group = "lint"}
69
+ ]
70
+
43
71
  [project.urls]
44
72
  homepage = "https://corteva.github.io/rioxarray/"
45
73
  documentation = "https://corteva.github.io/rioxarray/"
@@ -0,0 +1,4 @@
1
+ """
2
+ Convention modules for rioxarray.
3
+ Each convention module implements the ConventionProtocol interface.
4
+ """
@@ -0,0 +1,52 @@
1
+ """This module defines the common interface for convention implementations
2
+ and provides helpers for selecting conventions.
3
+ """
4
+
5
+ from typing import Optional, Protocol, Union
6
+
7
+ import rasterio.crs
8
+ import xarray
9
+ from affine import Affine
10
+
11
+
12
+ class ConventionProtocol(Protocol):
13
+ """Protocol defining the interface for convention modules."""
14
+
15
+ @classmethod
16
+ def read_crs(
17
+ cls, obj: Union[xarray.Dataset, xarray.DataArray]
18
+ ) -> Optional[rasterio.crs.CRS]:
19
+ """Read CRS from the object using this convention."""
20
+
21
+ @classmethod
22
+ def read_transform(
23
+ cls, obj: Union[xarray.Dataset, xarray.DataArray]
24
+ ) -> Optional[Affine]:
25
+ """Read transform from the object using this convention."""
26
+
27
+ @classmethod
28
+ def read_spatial_dimensions(
29
+ cls,
30
+ obj: Union[xarray.Dataset, xarray.DataArray],
31
+ ) -> Optional[tuple[str, str]]:
32
+ """Read spatial dimensions (y_dim, x_dim) from the object using this convention."""
33
+
34
+ @classmethod
35
+ def write_crs(
36
+ cls,
37
+ obj: Union[xarray.Dataset, xarray.DataArray],
38
+ *,
39
+ crs: rasterio.crs.CRS,
40
+ **kwargs,
41
+ ) -> Union[xarray.Dataset, xarray.DataArray]:
42
+ """Write CRS to the object using this convention."""
43
+
44
+ @classmethod
45
+ def write_transform(
46
+ cls,
47
+ obj: Union[xarray.Dataset, xarray.DataArray],
48
+ *,
49
+ transform: Affine,
50
+ **kwargs,
51
+ ) -> Union[xarray.Dataset, xarray.DataArray]:
52
+ """Write transform to the object using this convention."""
@@ -0,0 +1,176 @@
1
+ """
2
+ Core convention methods for rioxarray.
3
+ """
4
+
5
+ from typing import Optional, Union
6
+
7
+ import rasterio.crs
8
+ import xarray
9
+ from affine import Affine
10
+
11
+ from rioxarray._convention._base import ConventionProtocol
12
+ from rioxarray._convention.cf import CFConvention
13
+ from rioxarray._convention.zarr import ZarrConvention
14
+ from rioxarray._options import CONVENTION, get_option
15
+ from rioxarray.crs import crs_from_user_input
16
+ from rioxarray.enum import Convention
17
+
18
+ # Convention classes mapped by Convention enum
19
+ _CONVENTION_MODULES: dict[Convention, ConventionProtocol] = {
20
+ Convention.CF: CFConvention, # type: ignore[dict-item]
21
+ Convention.ZARR: ZarrConvention, # type: ignore[dict-item]
22
+ }
23
+
24
+
25
+ def _get_convention(convention: Convention | None) -> ConventionProtocol:
26
+ """
27
+ Get the convention module for writing.
28
+
29
+ Parameters
30
+ ----------
31
+ convention : Convention enum value or None
32
+ The convention to use. If None, uses the global default.
33
+
34
+ Returns
35
+ -------
36
+ ConventionProtocol
37
+ The module implementing the convention
38
+ """
39
+ if convention is None:
40
+ convention = get_option(CONVENTION) or Convention.CF
41
+ convention = Convention(convention)
42
+ return _CONVENTION_MODULES[convention]
43
+
44
+
45
+ def read_crs_auto(
46
+ obj: Union[xarray.Dataset, xarray.DataArray],
47
+ **kwargs,
48
+ ) -> Optional[rasterio.crs.CRS]:
49
+ """
50
+ Auto-detect and read CRS by trying convention readers.
51
+
52
+ If a convention is set globally via set_options(), that convention
53
+ is tried first for better performance. Then other conventions are
54
+ tried as fallback.
55
+
56
+ Parameters
57
+ ----------
58
+ obj : xarray.Dataset or xarray.DataArray
59
+ Object to read CRS from
60
+ **kwargs
61
+ Convention-specific parameters (e.g., grid_mapping for CF)
62
+
63
+ Returns
64
+ -------
65
+ rasterio.crs.CRS or None
66
+ CRS object, or None if not found in any convention
67
+ """
68
+ # Try the configured convention first (if set)
69
+ configured_convention = get_option(CONVENTION)
70
+ if configured_convention is not None:
71
+ result = _CONVENTION_MODULES[configured_convention].read_crs(obj, **kwargs)
72
+ if result is not None:
73
+ return result
74
+
75
+ # Try all other conventions
76
+ for conv_enum, convention in _CONVENTION_MODULES.items():
77
+ if conv_enum == configured_convention:
78
+ continue # Already tried this one
79
+ result = convention.read_crs(obj, **kwargs)
80
+ if result is not None:
81
+ return result
82
+
83
+ # Legacy fallback: look in attrs for 'crs' (not part of any convention)
84
+ try:
85
+ return crs_from_user_input(obj.attrs["crs"])
86
+ except KeyError:
87
+ pass
88
+
89
+ return None
90
+
91
+
92
+ def read_transform_auto(
93
+ obj: Union[xarray.Dataset, xarray.DataArray],
94
+ **kwargs,
95
+ ) -> Optional[Affine]:
96
+ """
97
+ Auto-detect and read transform by trying convention readers.
98
+
99
+ If a convention is set globally via set_options(), that convention
100
+ is tried first for better performance. Then other conventions are
101
+ tried as fallback.
102
+
103
+ Parameters
104
+ ----------
105
+ obj : xarray.Dataset or xarray.DataArray
106
+ Object to read transform from
107
+ **kwargs
108
+ Convention-specific parameters (e.g., grid_mapping for CF)
109
+
110
+ Returns
111
+ -------
112
+ affine.Affine or None
113
+ Transform object, or None if not found in any convention
114
+ """
115
+ # Try the configured convention first (if set)
116
+ configured_convention = get_option(CONVENTION)
117
+ if configured_convention is not None:
118
+ result = _CONVENTION_MODULES[configured_convention].read_transform(
119
+ obj, **kwargs
120
+ )
121
+ if result is not None:
122
+ return result
123
+
124
+ # Try all other conventions
125
+ for conv_enum, convention in _CONVENTION_MODULES.items():
126
+ if conv_enum == configured_convention:
127
+ continue # Already tried this one
128
+ result = convention.read_transform(obj, **kwargs)
129
+ if result is not None:
130
+ return result
131
+
132
+ # Legacy fallback: look in attrs for 'transform' (not part of any convention)
133
+ try:
134
+ return Affine(*obj.attrs["transform"][:6])
135
+ except KeyError:
136
+ pass
137
+
138
+ return None
139
+
140
+
141
+ def read_spatial_dimensions_auto(
142
+ obj: Union[xarray.Dataset, xarray.DataArray],
143
+ ) -> Optional[tuple[str, str]]:
144
+ """
145
+ Auto-detect and read spatial dimensions by trying convention readers.
146
+
147
+ If a convention is set globally via set_options(), that convention
148
+ is tried first for better performance. Then other conventions are
149
+ tried as fallback.
150
+
151
+ Parameters
152
+ ----------
153
+ obj : xarray.Dataset or xarray.DataArray
154
+ Object to read spatial dimensions from
155
+
156
+ Returns
157
+ -------
158
+ tuple of (y_dim, x_dim) or None
159
+ Tuple of dimension names, or None if not found in any convention
160
+ """
161
+ # Try the configured convention first (if set)
162
+ configured_convention = get_option(CONVENTION)
163
+ if configured_convention is not None:
164
+ result = _CONVENTION_MODULES[configured_convention].read_spatial_dimensions(obj)
165
+ if result is not None:
166
+ return result
167
+
168
+ # Try all other conventions
169
+ for conv_enum, convention in _CONVENTION_MODULES.items():
170
+ if conv_enum == configured_convention:
171
+ continue # Already tried this one
172
+ result = convention.read_spatial_dimensions(obj)
173
+ if result is not None:
174
+ return result
175
+
176
+ return None
@@ -0,0 +1,247 @@
1
+ """
2
+ CF (Climate and Forecasts) convention support for rioxarray.
3
+
4
+ This module provides functions for reading and writing geospatial metadata according to
5
+ the CF conventions: https://github.com/cf-convention/cf-conventions
6
+ """
7
+ from typing import Optional, Tuple, Union
8
+
9
+ import numpy
10
+ import pyproj
11
+ import rasterio.crs
12
+ import xarray
13
+ from affine import Affine
14
+
15
+ from rioxarray._options import EXPORT_GRID_MAPPING, get_option
16
+ from rioxarray.crs import crs_from_user_input
17
+
18
+
19
+ class CFConvention:
20
+ """CF convention class implementing ConventionProtocol."""
21
+
22
+ @classmethod
23
+ def read_crs(
24
+ cls, obj: Union[xarray.Dataset, xarray.DataArray]
25
+ ) -> Optional[rasterio.crs.CRS]:
26
+ """
27
+ Read CRS from CF conventions.
28
+
29
+ Parameters
30
+ ----------
31
+ obj : xarray.Dataset or xarray.DataArray
32
+ Object to read CRS from
33
+
34
+ Returns
35
+ -------
36
+ rasterio.crs.CRS or None
37
+ CRS object, or None if not found
38
+ """
39
+ try:
40
+ grid_mapping_coord = obj.coords[obj.rio.grid_mapping]
41
+
42
+ # Look in wkt attributes first for performance
43
+ for crs_attr in ("spatial_ref", "crs_wkt"):
44
+ try:
45
+ return crs_from_user_input(grid_mapping_coord.attrs[crs_attr])
46
+ except KeyError:
47
+ pass
48
+
49
+ # Look in grid_mapping CF attributes
50
+ try:
51
+ return pyproj.CRS.from_cf(grid_mapping_coord.attrs)
52
+ except (KeyError, pyproj.exceptions.CRSError):
53
+ pass
54
+ except KeyError:
55
+ # grid_mapping coordinate doesn't exist
56
+ pass
57
+ return None
58
+
59
+ @classmethod
60
+ def read_transform(
61
+ cls, obj: Union[xarray.Dataset, xarray.DataArray]
62
+ ) -> Optional[Affine]:
63
+ """
64
+ Read transform from CF conventions (GeoTransform attribute).
65
+
66
+ Parameters
67
+ ----------
68
+ obj : xarray.Dataset or xarray.DataArray
69
+ Object to read transform from
70
+
71
+ Returns
72
+ -------
73
+ affine.Affine or None
74
+ Transform object, or None if not found
75
+ """
76
+ try:
77
+ transform = numpy.fromstring(
78
+ obj.coords[obj.rio.grid_mapping].attrs["GeoTransform"], sep=" "
79
+ )
80
+ # Calling .tolist() to assure the arguments are Python float and JSON serializable
81
+ return Affine.from_gdal(*transform.tolist())
82
+ except KeyError:
83
+ pass
84
+
85
+ return None
86
+
87
+ @classmethod
88
+ def read_spatial_dimensions(
89
+ cls,
90
+ obj: Union[xarray.Dataset, xarray.DataArray],
91
+ ) -> Optional[Tuple[str, str]]:
92
+ """
93
+ Read spatial dimensions from CF conventions.
94
+
95
+ This function detects spatial dimensions based on:
96
+ 1. Standard dimension names ('x'/'y', 'longitude'/'latitude')
97
+ 2. CF coordinate attributes ('axis', 'standard_name')
98
+
99
+ Parameters
100
+ ----------
101
+ obj : xarray.Dataset or xarray.DataArray
102
+ Object to read spatial dimensions from
103
+
104
+ Returns
105
+ -------
106
+ tuple of (y_dim, x_dim) or None
107
+ Tuple of dimension names, or None if not found
108
+ """
109
+ x_dim = None
110
+ y_dim = None
111
+
112
+ # Check standard dimension names
113
+ if "x" in obj.dims and "y" in obj.dims:
114
+ return "y", "x"
115
+ if "longitude" in obj.dims and "latitude" in obj.dims:
116
+ return "latitude", "longitude"
117
+
118
+ # Look for coordinates with CF attributes
119
+ for coord in obj.coords:
120
+ # Make sure to only look in 1D coordinates
121
+ # that has the same dimension name as the coordinate
122
+ if obj.coords[coord].dims != (coord,):
123
+ continue
124
+ if (obj.coords[coord].attrs.get("axis", "").upper() == "X") or (
125
+ obj.coords[coord].attrs.get("standard_name", "").lower()
126
+ in ("longitude", "projection_x_coordinate")
127
+ ):
128
+ x_dim = coord
129
+ elif (obj.coords[coord].attrs.get("axis", "").upper() == "Y") or (
130
+ obj.coords[coord].attrs.get("standard_name", "").lower()
131
+ in ("latitude", "projection_y_coordinate")
132
+ ):
133
+ y_dim = coord
134
+
135
+ if x_dim is not None and y_dim is not None:
136
+ return str(y_dim), str(x_dim)
137
+ return None
138
+
139
+ @classmethod
140
+ def write_crs(
141
+ cls,
142
+ obj: Union[xarray.Dataset, xarray.DataArray],
143
+ crs: rasterio.crs.CRS,
144
+ *,
145
+ grid_mapping_name: Optional[str] = None,
146
+ **kwargs, # pylint: disable=unused-argument
147
+ ) -> Union[xarray.Dataset, xarray.DataArray]:
148
+ """
149
+ Write CRS using CF conventions.
150
+
151
+ This also writes the grid_mapping attribute to encoding for CF compliance.
152
+
153
+ Parameters
154
+ ----------
155
+ obj : xarray.Dataset or xarray.DataArray
156
+ Object to write CRS to
157
+ crs : rasterio.crs.CRS
158
+ CRS to write
159
+ grid_mapping_name : str
160
+ Name of the grid_mapping coordinate
161
+ **kwargs
162
+ Additional convention-specific parameters
163
+
164
+ Returns
165
+ -------
166
+ xarray.Dataset or xarray.DataArray
167
+ Object with CRS written
168
+ """
169
+ # get original transform
170
+ transform = obj.rio._cached_transform()
171
+ # remove old grid mapping coordinate if exists
172
+ grid_mapping_name = (
173
+ obj.rio.grid_mapping if grid_mapping_name is None else grid_mapping_name
174
+ )
175
+ try:
176
+ del obj.coords[grid_mapping_name]
177
+ except KeyError:
178
+ pass
179
+
180
+ # add grid mapping coordinate
181
+ obj.coords[grid_mapping_name] = xarray.Variable((), 0)
182
+ grid_map_attrs = {}
183
+ if get_option(EXPORT_GRID_MAPPING):
184
+ try:
185
+ grid_map_attrs = pyproj.CRS.from_user_input(crs).to_cf()
186
+ except KeyError:
187
+ pass
188
+ # spatial_ref is for compatibility with GDAL
189
+ crs_wkt = crs.to_wkt()
190
+ grid_map_attrs["spatial_ref"] = crs_wkt
191
+ grid_map_attrs["crs_wkt"] = crs_wkt
192
+ if transform is not None:
193
+ grid_map_attrs["GeoTransform"] = " ".join(
194
+ [str(item) for item in transform.to_gdal()]
195
+ )
196
+ obj.coords[grid_mapping_name].rio.set_attrs(grid_map_attrs, inplace=True)
197
+
198
+ return obj.rio.write_grid_mapping(
199
+ grid_mapping_name=grid_mapping_name, inplace=True
200
+ )
201
+
202
+ @classmethod
203
+ def write_transform(
204
+ cls,
205
+ obj: Union[xarray.Dataset, xarray.DataArray],
206
+ *,
207
+ transform: Affine,
208
+ grid_mapping_name: Optional[str] = None,
209
+ **kwargs, # pylint: disable=unused-argument
210
+ ) -> Union[xarray.Dataset, xarray.DataArray]:
211
+ """
212
+ Write transform using CF conventions (GeoTransform attribute).
213
+
214
+ This also writes the grid_mapping attribute to encoding for CF compliance.
215
+
216
+ Parameters
217
+ ----------
218
+ obj : xarray.Dataset or xarray.DataArray
219
+ Object to write transform to
220
+ transform : affine.Affine
221
+ Transform to write
222
+ grid_mapping_name : Optional[str]
223
+ Name of the grid_mapping coordinate
224
+ **kwargs
225
+ Additional convention-specific parameters
226
+
227
+ Returns
228
+ -------
229
+ xarray.Dataset or xarray.DataArray
230
+ Object with transform written
231
+ """
232
+ transform = transform or obj.rio.transform(recalc=True)
233
+ grid_mapping_name = (
234
+ obj.rio.grid_mapping if grid_mapping_name is None else grid_mapping_name
235
+ )
236
+ try:
237
+ grid_map_attrs = obj.coords[grid_mapping_name].attrs.copy()
238
+ except KeyError:
239
+ obj.coords[grid_mapping_name] = xarray.Variable((), 0)
240
+ grid_map_attrs = obj.coords[grid_mapping_name].attrs.copy()
241
+ grid_map_attrs["GeoTransform"] = " ".join(
242
+ [str(item) for item in transform.to_gdal()]
243
+ )
244
+ obj.coords[grid_mapping_name].rio.set_attrs(grid_map_attrs, inplace=True)
245
+ return obj.rio.write_grid_mapping(
246
+ grid_mapping_name=grid_mapping_name, inplace=True
247
+ )