rioxarray 0.20.0__tar.gz → 0.21.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.
- {rioxarray-0.20.0 → rioxarray-0.21.0}/CONTRIBUTING.rst +1 -2
- {rioxarray-0.20.0/rioxarray.egg-info → rioxarray-0.21.0}/PKG-INFO +2 -2
- {rioxarray-0.20.0 → rioxarray-0.21.0}/pyproject.toml +30 -2
- {rioxarray-0.20.0 → rioxarray-0.21.0}/rioxarray/_io.py +15 -4
- rioxarray-0.21.0/rioxarray/_spatial_utils.py +500 -0
- {rioxarray-0.20.0 → rioxarray-0.21.0}/rioxarray/merge.py +1 -1
- {rioxarray-0.20.0 → rioxarray-0.21.0}/rioxarray/raster_array.py +135 -236
- {rioxarray-0.20.0 → rioxarray-0.21.0}/rioxarray/raster_writer.py +45 -20
- {rioxarray-0.20.0 → rioxarray-0.21.0}/rioxarray/rioxarray.py +82 -278
- {rioxarray-0.20.0 → rioxarray-0.21.0/rioxarray.egg-info}/PKG-INFO +2 -2
- {rioxarray-0.20.0 → rioxarray-0.21.0}/rioxarray.egg-info/SOURCES.txt +1 -0
- {rioxarray-0.20.0 → rioxarray-0.21.0}/rioxarray.egg-info/requires.txt +1 -1
- {rioxarray-0.20.0 → rioxarray-0.21.0}/AUTHORS.rst +0 -0
- {rioxarray-0.20.0 → rioxarray-0.21.0}/LICENSE +0 -0
- {rioxarray-0.20.0 → rioxarray-0.21.0}/LICENSE_datacube +0 -0
- {rioxarray-0.20.0 → rioxarray-0.21.0}/LICENSE_xarray +0 -0
- {rioxarray-0.20.0 → rioxarray-0.21.0}/MANIFEST.in +0 -0
- {rioxarray-0.20.0 → rioxarray-0.21.0}/README.rst +0 -0
- {rioxarray-0.20.0 → rioxarray-0.21.0}/rioxarray/__init__.py +0 -0
- {rioxarray-0.20.0 → rioxarray-0.21.0}/rioxarray/_options.py +0 -0
- {rioxarray-0.20.0 → rioxarray-0.21.0}/rioxarray/_show_versions.py +0 -0
- {rioxarray-0.20.0 → rioxarray-0.21.0}/rioxarray/crs.py +0 -0
- {rioxarray-0.20.0 → rioxarray-0.21.0}/rioxarray/exceptions.py +0 -0
- {rioxarray-0.20.0 → rioxarray-0.21.0}/rioxarray/py.typed +0 -0
- {rioxarray-0.20.0 → rioxarray-0.21.0}/rioxarray/raster_dataset.py +0 -0
- {rioxarray-0.20.0 → rioxarray-0.21.0}/rioxarray/xarray_plugin.py +0 -0
- {rioxarray-0.20.0 → rioxarray-0.21.0}/rioxarray.egg-info/dependency_links.txt +0 -0
- {rioxarray-0.20.0 → rioxarray-0.21.0}/rioxarray.egg-info/entry_points.txt +0 -0
- {rioxarray-0.20.0 → rioxarray-0.21.0}/rioxarray.egg-info/top_level.txt +0 -0
- {rioxarray-0.20.0 → rioxarray-0.21.0}/setup.cfg +0 -0
- {rioxarray-0.20.0 → rioxarray-0.21.0}/setup.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: rioxarray
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.21.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
|
|
33
|
+
Requires-Dist: xarray<2025.12,>=2024.7.0
|
|
34
34
|
Requires-Dist: pyproj>=3.3
|
|
35
35
|
Requires-Dist: numpy>=2
|
|
36
36
|
Provides-Extra: interp
|
|
@@ -4,7 +4,7 @@ requires = ["setuptools", "wheel"]
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "rioxarray"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.21.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
|
-
|
|
38
|
+
# https://github.com/pydata/xarray/issues/11000
|
|
39
|
+
"xarray>=2024.7.0,<2025.12",
|
|
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/"
|
|
@@ -33,11 +33,13 @@ from xarray.core.dtypes import maybe_promote
|
|
|
33
33
|
from xarray.core.utils import is_scalar
|
|
34
34
|
from xarray.core.variable import as_variable
|
|
35
35
|
|
|
36
|
+
from rioxarray._spatial_utils import (
|
|
37
|
+
FILL_VALUE_NAMES,
|
|
38
|
+
UNWANTED_RIO_ATTRS,
|
|
39
|
+
_generate_spatial_coords,
|
|
40
|
+
)
|
|
36
41
|
from rioxarray.exceptions import RioXarrayError
|
|
37
|
-
from rioxarray.rioxarray import _generate_spatial_coords
|
|
38
42
|
|
|
39
|
-
FILL_VALUE_NAMES = ("_FillValue", "missing_value", "fill_value", "nodata")
|
|
40
|
-
UNWANTED_RIO_ATTRS = ("nodatavals", "is_tiled", "res")
|
|
41
43
|
# TODO: should this be GDAL_LOCK instead?
|
|
42
44
|
RASTERIO_LOCK = SerializableLock()
|
|
43
45
|
NO_LOCK = contextlib.nullcontext()
|
|
@@ -931,6 +933,9 @@ def _prepare_dask(
|
|
|
931
933
|
dtype=_rasterio_to_numpy_dtype(riods.dtypes),
|
|
932
934
|
previous_chunks=block_shape,
|
|
933
935
|
)
|
|
936
|
+
# xarray wants chunks as a dict rather than a tuple
|
|
937
|
+
chunks = dict(zip(result.dims, chunks, strict=True)) # type: ignore[arg-type]
|
|
938
|
+
|
|
934
939
|
token_filename = filename
|
|
935
940
|
if bidx is not None:
|
|
936
941
|
token_filename = f"{filename}-{bidx}"
|
|
@@ -1206,8 +1211,12 @@ def open_rasterio(
|
|
|
1206
1211
|
coord_name = "band"
|
|
1207
1212
|
coords[coord_name] = numpy.asarray(riods.indexes)
|
|
1208
1213
|
|
|
1214
|
+
# Handle GCPs and RPCs
|
|
1209
1215
|
has_gcps = riods.gcps[0]
|
|
1210
|
-
|
|
1216
|
+
has_rpcs = riods.rpcs
|
|
1217
|
+
|
|
1218
|
+
# Only parse coordinates in case the array is georeferenced
|
|
1219
|
+
if has_gcps or has_rpcs:
|
|
1211
1220
|
parse_coordinates = False
|
|
1212
1221
|
|
|
1213
1222
|
# Get geospatial coordinates
|
|
@@ -1278,6 +1287,8 @@ def open_rasterio(
|
|
|
1278
1287
|
result.rio.write_crs(rio_crs, inplace=True)
|
|
1279
1288
|
if has_gcps:
|
|
1280
1289
|
result.rio.write_gcps(*riods.gcps, inplace=True)
|
|
1290
|
+
if has_rpcs:
|
|
1291
|
+
result.rio.write_rpcs(riods.rpcs, inplace=True)
|
|
1281
1292
|
|
|
1282
1293
|
if chunks is not None:
|
|
1283
1294
|
result = _prepare_dask(
|
|
@@ -0,0 +1,500 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Helper functions for determining spatial attributes.
|
|
3
|
+
"""
|
|
4
|
+
import copy
|
|
5
|
+
import math
|
|
6
|
+
import warnings
|
|
7
|
+
from collections.abc import Hashable
|
|
8
|
+
from typing import Any, Iterable, Optional, Union
|
|
9
|
+
|
|
10
|
+
import numpy
|
|
11
|
+
import rasterio.mask
|
|
12
|
+
import rasterio.warp
|
|
13
|
+
import rasterio.windows
|
|
14
|
+
import xarray
|
|
15
|
+
from affine import Affine
|
|
16
|
+
from rasterio.control import GroundControlPoint
|
|
17
|
+
from rasterio.features import geometry_mask
|
|
18
|
+
|
|
19
|
+
from rioxarray.exceptions import MissingSpatialDimensionError
|
|
20
|
+
|
|
21
|
+
FILL_VALUE_NAMES = ("_FillValue", "missing_value", "fill_value", "nodata")
|
|
22
|
+
UNWANTED_RIO_ATTRS = ("nodatavals", "is_tiled", "res")
|
|
23
|
+
DEFAULT_GRID_MAP = "spatial_ref"
|
|
24
|
+
|
|
25
|
+
# DTYPE TO NODATA MAP
|
|
26
|
+
# Based on: https://github.com/OSGeo/gdal/blob/v3.12.1/swig/python/gdal-utils/osgeo_utils/gdal_calc.py#L49-L66
|
|
27
|
+
# And: https://github.com/rasterio/rasterio/blob/1.5.0/rasterio/dtypes.py#L91-L103
|
|
28
|
+
_NODATA_DTYPE_MAP = {
|
|
29
|
+
1: 255, # GDT_Byte
|
|
30
|
+
2: 65535, # GDT_UInt16
|
|
31
|
+
3: -32768, # GDT_Int16
|
|
32
|
+
4: 4294967295, # GDT_UInt32
|
|
33
|
+
5: -2147483648, # GDT_Int32
|
|
34
|
+
6: numpy.nan, # GDT_Float32
|
|
35
|
+
7: numpy.nan, # GDT_Float64
|
|
36
|
+
8: None, # GDT_CInt16
|
|
37
|
+
9: None, # GDT_CInt32
|
|
38
|
+
10: numpy.nan, # GDT_CFloat32
|
|
39
|
+
11: numpy.nan, # GDT_CFloat64
|
|
40
|
+
12: 18446744073709551615, # GDT_UInt64
|
|
41
|
+
13: -9223372036854775808, # GDT_Int64
|
|
42
|
+
14: -128, # GDT_Int8
|
|
43
|
+
15: numpy.nan, # GDT_Float16
|
|
44
|
+
16: numpy.nan, # GDT_CFloat16
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _affine_has_rotation(affine: Affine) -> bool:
|
|
49
|
+
"""
|
|
50
|
+
Determine if the affine has rotation.
|
|
51
|
+
|
|
52
|
+
Parameters
|
|
53
|
+
----------
|
|
54
|
+
affine: :obj:`affine.Affine`
|
|
55
|
+
The affine of the grid.
|
|
56
|
+
|
|
57
|
+
Returns
|
|
58
|
+
-------
|
|
59
|
+
bool
|
|
60
|
+
"""
|
|
61
|
+
return affine.b == affine.d != 0
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _resolution(affine: Affine) -> tuple[float, float]:
|
|
65
|
+
"""
|
|
66
|
+
Determine if the resolution of the affine.
|
|
67
|
+
If it has rotation, the sign of the resolution is lost.
|
|
68
|
+
|
|
69
|
+
Based on: https://github.com/mapbox/rasterio/blob/6185a4e4ad72b5669066d2d5004bf46d94a6d298/rasterio/_base.pyx#L943-L951
|
|
70
|
+
|
|
71
|
+
Parameters
|
|
72
|
+
----------
|
|
73
|
+
affine: :obj:`affine.Affine`
|
|
74
|
+
The affine of the grid.
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
Returns
|
|
78
|
+
--------
|
|
79
|
+
x_resolution: float
|
|
80
|
+
The X resolution of the affine.
|
|
81
|
+
y_resolution: float
|
|
82
|
+
The Y resolution of the affine.
|
|
83
|
+
"""
|
|
84
|
+
if not _affine_has_rotation(affine):
|
|
85
|
+
return affine.a, affine.e
|
|
86
|
+
return (
|
|
87
|
+
math.sqrt(affine.a**2 + affine.d**2),
|
|
88
|
+
math.sqrt(affine.b**2 + affine.e**2),
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def affine_to_coords(
|
|
93
|
+
affine: Affine, width: int, height: int, *, x_dim: str = "x", y_dim: str = "y"
|
|
94
|
+
) -> dict[str, numpy.ndarray]:
|
|
95
|
+
"""Generate 1d pixel centered coordinates from affine.
|
|
96
|
+
|
|
97
|
+
Based on code from the xarray rasterio backend.
|
|
98
|
+
|
|
99
|
+
Parameters
|
|
100
|
+
----------
|
|
101
|
+
affine: :obj:`affine.Affine`
|
|
102
|
+
The affine of the grid.
|
|
103
|
+
width: int
|
|
104
|
+
The width of the grid.
|
|
105
|
+
height: int
|
|
106
|
+
The height of the grid.
|
|
107
|
+
x_dim: str, optional
|
|
108
|
+
The name of the X dimension. Default is 'x'.
|
|
109
|
+
y_dim: str, optional
|
|
110
|
+
The name of the Y dimension. Default is 'y'.
|
|
111
|
+
|
|
112
|
+
Returns
|
|
113
|
+
-------
|
|
114
|
+
dict: x and y coordinate arrays.
|
|
115
|
+
|
|
116
|
+
"""
|
|
117
|
+
transform = affine * affine.translation(0.5, 0.5)
|
|
118
|
+
if affine.is_rectilinear and not _affine_has_rotation(affine):
|
|
119
|
+
x_coords, _ = transform * (numpy.arange(width), numpy.zeros(width))
|
|
120
|
+
_, y_coords = transform * (numpy.zeros(height), numpy.arange(height))
|
|
121
|
+
else:
|
|
122
|
+
x_coords, y_coords = transform * numpy.meshgrid(
|
|
123
|
+
numpy.arange(width),
|
|
124
|
+
numpy.arange(height),
|
|
125
|
+
)
|
|
126
|
+
return {y_dim: y_coords, x_dim: x_coords}
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _generate_spatial_coords(
|
|
130
|
+
*, affine: Affine, width: int, height: int
|
|
131
|
+
) -> dict[Hashable, Any]:
|
|
132
|
+
"""get spatial coords in new transform"""
|
|
133
|
+
new_spatial_coords = affine_to_coords(affine, width, height)
|
|
134
|
+
if new_spatial_coords["x"].ndim == 1:
|
|
135
|
+
return {
|
|
136
|
+
"x": xarray.IndexVariable("x", new_spatial_coords["x"]),
|
|
137
|
+
"y": xarray.IndexVariable("y", new_spatial_coords["y"]),
|
|
138
|
+
}
|
|
139
|
+
return {
|
|
140
|
+
"xc": (("y", "x"), new_spatial_coords["x"]),
|
|
141
|
+
"yc": (("y", "x"), new_spatial_coords["y"]),
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _get_nonspatial_coords(
|
|
146
|
+
src_data_array: Union[xarray.DataArray, xarray.Dataset],
|
|
147
|
+
) -> dict[Hashable, Union[xarray.Variable, xarray.IndexVariable]]:
|
|
148
|
+
coords: dict[Hashable, Union[xarray.Variable, xarray.IndexVariable]] = {}
|
|
149
|
+
for coord in set(src_data_array.coords) - {
|
|
150
|
+
src_data_array.rio.x_dim,
|
|
151
|
+
src_data_array.rio.y_dim,
|
|
152
|
+
DEFAULT_GRID_MAP,
|
|
153
|
+
}:
|
|
154
|
+
# skip 2D spatial coords
|
|
155
|
+
if (
|
|
156
|
+
src_data_array.rio.x_dim in src_data_array[coord].dims
|
|
157
|
+
and src_data_array.rio.y_dim in src_data_array[coord].dims
|
|
158
|
+
):
|
|
159
|
+
continue
|
|
160
|
+
if src_data_array[coord].ndim == 1:
|
|
161
|
+
coords[coord] = xarray.IndexVariable(
|
|
162
|
+
src_data_array[coord].dims,
|
|
163
|
+
src_data_array[coord].values,
|
|
164
|
+
src_data_array[coord].attrs,
|
|
165
|
+
)
|
|
166
|
+
else:
|
|
167
|
+
coords[coord] = xarray.Variable(
|
|
168
|
+
src_data_array[coord].dims,
|
|
169
|
+
src_data_array[coord].values,
|
|
170
|
+
src_data_array[coord].attrs,
|
|
171
|
+
)
|
|
172
|
+
return coords
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _make_coords(
|
|
176
|
+
*,
|
|
177
|
+
src_data_array: Union[xarray.DataArray, xarray.Dataset],
|
|
178
|
+
dst_affine: Affine,
|
|
179
|
+
dst_width: int,
|
|
180
|
+
dst_height: int,
|
|
181
|
+
force_generate: bool = False,
|
|
182
|
+
) -> dict[Hashable, Any]:
|
|
183
|
+
"""Generate the coordinates of the new projected `xarray.DataArray`"""
|
|
184
|
+
coords = _get_nonspatial_coords(src_data_array)
|
|
185
|
+
if (
|
|
186
|
+
force_generate
|
|
187
|
+
or (
|
|
188
|
+
src_data_array.rio.x_dim in src_data_array.coords
|
|
189
|
+
and src_data_array.rio.y_dim in src_data_array.coords
|
|
190
|
+
)
|
|
191
|
+
or ("xc" in src_data_array.coords and "yc" in src_data_array.coords)
|
|
192
|
+
):
|
|
193
|
+
new_coords = _generate_spatial_coords(
|
|
194
|
+
affine=dst_affine, width=dst_width, height=dst_height
|
|
195
|
+
)
|
|
196
|
+
new_coords.update(coords)
|
|
197
|
+
return new_coords
|
|
198
|
+
return coords
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _get_data_var_message(obj: Union[xarray.DataArray, xarray.Dataset]) -> str:
|
|
202
|
+
"""
|
|
203
|
+
Get message for named data variables.
|
|
204
|
+
"""
|
|
205
|
+
try:
|
|
206
|
+
return f" Data variable: {obj.name}" if obj.name else ""
|
|
207
|
+
except AttributeError:
|
|
208
|
+
return ""
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _get_spatial_dims(
|
|
212
|
+
obj: Union[xarray.Dataset, xarray.DataArray], *, var: Union[Any, Hashable]
|
|
213
|
+
) -> tuple[str, str]:
|
|
214
|
+
"""
|
|
215
|
+
Retrieve the spatial dimensions of the dataset
|
|
216
|
+
"""
|
|
217
|
+
try:
|
|
218
|
+
return obj[var].rio.x_dim, obj[var].rio.y_dim
|
|
219
|
+
except MissingSpatialDimensionError as err:
|
|
220
|
+
try:
|
|
221
|
+
obj[var].rio.set_spatial_dims(
|
|
222
|
+
x_dim=obj.rio.x_dim, y_dim=obj.rio.y_dim, inplace=True
|
|
223
|
+
)
|
|
224
|
+
return obj.rio.x_dim, obj.rio.y_dim
|
|
225
|
+
except MissingSpatialDimensionError:
|
|
226
|
+
raise err from None
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _has_spatial_dims(
|
|
230
|
+
obj: Union[xarray.Dataset, xarray.DataArray], *, var: Union[Any, Hashable]
|
|
231
|
+
) -> bool:
|
|
232
|
+
"""
|
|
233
|
+
Check to see if the variable in the Dataset has spatial dimensions
|
|
234
|
+
"""
|
|
235
|
+
try:
|
|
236
|
+
# pylint: disable=pointless-statement
|
|
237
|
+
_get_spatial_dims(obj, var=var)
|
|
238
|
+
except MissingSpatialDimensionError:
|
|
239
|
+
return False
|
|
240
|
+
return True
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _order_bounds(
|
|
244
|
+
*,
|
|
245
|
+
minx: float,
|
|
246
|
+
miny: float,
|
|
247
|
+
maxx: float,
|
|
248
|
+
maxy: float,
|
|
249
|
+
resolution_x: float,
|
|
250
|
+
resolution_y: float,
|
|
251
|
+
) -> tuple[float, float, float, float]:
|
|
252
|
+
"""
|
|
253
|
+
Make sure that the bounds are in the correct order
|
|
254
|
+
"""
|
|
255
|
+
if resolution_y < 0:
|
|
256
|
+
top = maxy
|
|
257
|
+
bottom = miny
|
|
258
|
+
else:
|
|
259
|
+
top = miny
|
|
260
|
+
bottom = maxy
|
|
261
|
+
if resolution_x < 0:
|
|
262
|
+
left = maxx
|
|
263
|
+
right = minx
|
|
264
|
+
else:
|
|
265
|
+
left = minx
|
|
266
|
+
right = maxx
|
|
267
|
+
|
|
268
|
+
return left, bottom, right, top
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _convert_gcps_to_geojson(
|
|
272
|
+
gcps: Iterable[GroundControlPoint],
|
|
273
|
+
) -> dict:
|
|
274
|
+
"""
|
|
275
|
+
Convert GCPs to geojson.
|
|
276
|
+
|
|
277
|
+
Parameters
|
|
278
|
+
----------
|
|
279
|
+
gcps: The list of GroundControlPoint instances.
|
|
280
|
+
|
|
281
|
+
Returns
|
|
282
|
+
-------
|
|
283
|
+
A FeatureCollection dict.
|
|
284
|
+
"""
|
|
285
|
+
|
|
286
|
+
def _gcp_coordinates(gcp):
|
|
287
|
+
if gcp.z is None:
|
|
288
|
+
return [gcp.x, gcp.y]
|
|
289
|
+
return [gcp.x, gcp.y, gcp.z]
|
|
290
|
+
|
|
291
|
+
features = [
|
|
292
|
+
{
|
|
293
|
+
"type": "Feature",
|
|
294
|
+
"properties": {
|
|
295
|
+
"id": gcp.id,
|
|
296
|
+
"info": gcp.info,
|
|
297
|
+
"row": gcp.row,
|
|
298
|
+
"col": gcp.col,
|
|
299
|
+
},
|
|
300
|
+
"geometry": {"type": "Point", "coordinates": _gcp_coordinates(gcp)},
|
|
301
|
+
}
|
|
302
|
+
for gcp in gcps
|
|
303
|
+
]
|
|
304
|
+
return {"type": "FeatureCollection", "features": features}
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _convert_str_to_resampling(name: str) -> rasterio.warp.Resampling:
|
|
308
|
+
"""
|
|
309
|
+
Convert from string to rasterio.warp.Resampling enum, raises ValueError on bad input.
|
|
310
|
+
|
|
311
|
+
Parameters
|
|
312
|
+
----------
|
|
313
|
+
name: str
|
|
314
|
+
The string to convert.
|
|
315
|
+
|
|
316
|
+
Returns
|
|
317
|
+
-------
|
|
318
|
+
:obj:`rasterio.warp.Resampling`
|
|
319
|
+
"""
|
|
320
|
+
try:
|
|
321
|
+
return getattr(rasterio.warp.Resampling, name.lower())
|
|
322
|
+
except AttributeError:
|
|
323
|
+
raise ValueError(f"Bad resampling parameter: {name}") from None
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _generate_attrs(
|
|
327
|
+
*, src_data_array: xarray.DataArray, dst_nodata: Optional[float]
|
|
328
|
+
) -> dict[str, Any]:
|
|
329
|
+
# add original attributes
|
|
330
|
+
new_attrs = copy.deepcopy(src_data_array.attrs)
|
|
331
|
+
# remove all nodata information
|
|
332
|
+
for unwanted_attr in FILL_VALUE_NAMES + UNWANTED_RIO_ATTRS:
|
|
333
|
+
new_attrs.pop(unwanted_attr, None)
|
|
334
|
+
|
|
335
|
+
# add nodata information
|
|
336
|
+
fill_value = (
|
|
337
|
+
src_data_array.rio.nodata
|
|
338
|
+
if src_data_array.rio.nodata is not None
|
|
339
|
+
else dst_nodata
|
|
340
|
+
)
|
|
341
|
+
if src_data_array.rio.encoded_nodata is None and fill_value is not None:
|
|
342
|
+
new_attrs["_FillValue"] = fill_value
|
|
343
|
+
|
|
344
|
+
return new_attrs
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _add_attrs_proj(
|
|
348
|
+
*, new_data_array: xarray.DataArray, src_data_array: xarray.DataArray
|
|
349
|
+
) -> xarray.DataArray:
|
|
350
|
+
"""Make sure attributes and projection correct"""
|
|
351
|
+
# make sure dimension information is preserved
|
|
352
|
+
if new_data_array.rio._x_dim is None:
|
|
353
|
+
new_data_array.rio._x_dim = src_data_array.rio.x_dim
|
|
354
|
+
if new_data_array.rio._y_dim is None:
|
|
355
|
+
new_data_array.rio._y_dim = src_data_array.rio.y_dim
|
|
356
|
+
|
|
357
|
+
# make sure attributes preserved
|
|
358
|
+
new_attrs = _generate_attrs(src_data_array=src_data_array, dst_nodata=None)
|
|
359
|
+
# remove fill value if it already exists in the encoding
|
|
360
|
+
# this is for data arrays pulling the encoding from a
|
|
361
|
+
# source data array instead of being generated anew.
|
|
362
|
+
if "_FillValue" in new_data_array.encoding:
|
|
363
|
+
new_attrs.pop("_FillValue", None)
|
|
364
|
+
|
|
365
|
+
new_data_array.rio.set_attrs(new_attrs, inplace=True)
|
|
366
|
+
|
|
367
|
+
# make sure projection added
|
|
368
|
+
new_data_array.rio.write_grid_mapping(src_data_array.rio.grid_mapping, inplace=True)
|
|
369
|
+
new_data_array.rio.write_crs(src_data_array.rio.crs, inplace=True)
|
|
370
|
+
new_data_array.rio.write_coordinate_system(inplace=True)
|
|
371
|
+
new_data_array.rio.write_transform(inplace=True)
|
|
372
|
+
# make sure encoding added
|
|
373
|
+
new_data_array.encoding = src_data_array.encoding.copy()
|
|
374
|
+
return new_data_array
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def _make_dst_affine(
|
|
378
|
+
*,
|
|
379
|
+
src_data_array: xarray.DataArray,
|
|
380
|
+
src_crs: rasterio.crs.CRS,
|
|
381
|
+
dst_crs: rasterio.crs.CRS,
|
|
382
|
+
dst_resolution: Optional[Union[float, tuple[float, float]]] = None,
|
|
383
|
+
dst_shape: Optional[tuple[float, float]] = None,
|
|
384
|
+
**kwargs,
|
|
385
|
+
):
|
|
386
|
+
"""Determine the affine of the new projected `xarray.DataArray`"""
|
|
387
|
+
src_bounds = ()
|
|
388
|
+
if (
|
|
389
|
+
"gcps" not in kwargs
|
|
390
|
+
and "rpcs" not in kwargs
|
|
391
|
+
and "src_geoloc_array" not in kwargs
|
|
392
|
+
):
|
|
393
|
+
src_bounds = src_data_array.rio.bounds()
|
|
394
|
+
src_height, src_width = src_data_array.rio.shape
|
|
395
|
+
dst_height, dst_width = dst_shape if dst_shape is not None else (None, None)
|
|
396
|
+
# pylint: disable=isinstance-second-argument-not-valid-type
|
|
397
|
+
if isinstance(dst_resolution, Iterable):
|
|
398
|
+
dst_resolution = tuple(abs(res_val) for res_val in dst_resolution) # type: ignore
|
|
399
|
+
elif dst_resolution is not None:
|
|
400
|
+
dst_resolution = abs(dst_resolution) # type: ignore
|
|
401
|
+
|
|
402
|
+
for key, value in (
|
|
403
|
+
("resolution", dst_resolution),
|
|
404
|
+
("dst_height", dst_height),
|
|
405
|
+
("dst_width", dst_width),
|
|
406
|
+
):
|
|
407
|
+
if value is not None:
|
|
408
|
+
kwargs[key] = value
|
|
409
|
+
dst_affine, dst_width, dst_height = rasterio.warp.calculate_default_transform(
|
|
410
|
+
src_crs,
|
|
411
|
+
dst_crs,
|
|
412
|
+
src_width,
|
|
413
|
+
src_height,
|
|
414
|
+
*src_bounds,
|
|
415
|
+
**kwargs,
|
|
416
|
+
)
|
|
417
|
+
return dst_affine, dst_width, dst_height
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def _clip_from_disk(
|
|
421
|
+
xds: xarray.DataArray,
|
|
422
|
+
*,
|
|
423
|
+
geometries: Iterable,
|
|
424
|
+
all_touched: bool,
|
|
425
|
+
drop: bool,
|
|
426
|
+
invert: bool,
|
|
427
|
+
) -> Optional[xarray.DataArray]:
|
|
428
|
+
"""
|
|
429
|
+
clip from disk if the file object is available
|
|
430
|
+
"""
|
|
431
|
+
try:
|
|
432
|
+
rio_dataset = xds.rio._manager.acquire()
|
|
433
|
+
except AttributeError:
|
|
434
|
+
warnings.warn("File object not available, clipping in-memory.")
|
|
435
|
+
return None
|
|
436
|
+
|
|
437
|
+
out_image, out_transform = rasterio.mask.mask(
|
|
438
|
+
rio_dataset,
|
|
439
|
+
geometries,
|
|
440
|
+
all_touched=all_touched,
|
|
441
|
+
invert=invert,
|
|
442
|
+
crop=drop,
|
|
443
|
+
)
|
|
444
|
+
if xds.rio.encoded_nodata is not None and not numpy.isnan(xds.rio.encoded_nodata):
|
|
445
|
+
out_image = out_image.astype(numpy.float64)
|
|
446
|
+
out_image[out_image == xds.rio.encoded_nodata] = numpy.nan
|
|
447
|
+
|
|
448
|
+
height, width = out_image.shape[-2:]
|
|
449
|
+
cropped_ds = xarray.DataArray(
|
|
450
|
+
name=xds.name,
|
|
451
|
+
data=out_image,
|
|
452
|
+
coords=_make_coords(
|
|
453
|
+
src_data_array=xds,
|
|
454
|
+
dst_affine=out_transform,
|
|
455
|
+
dst_width=width,
|
|
456
|
+
dst_height=height,
|
|
457
|
+
),
|
|
458
|
+
dims=xds.dims,
|
|
459
|
+
attrs=xds.attrs,
|
|
460
|
+
)
|
|
461
|
+
cropped_ds.encoding = xds.encoding
|
|
462
|
+
return cropped_ds
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def _clip_xarray(
|
|
466
|
+
xds: xarray.DataArray,
|
|
467
|
+
*,
|
|
468
|
+
geometries: Iterable,
|
|
469
|
+
all_touched: bool,
|
|
470
|
+
drop: bool,
|
|
471
|
+
invert: bool,
|
|
472
|
+
) -> xarray.DataArray:
|
|
473
|
+
"""
|
|
474
|
+
clip the xarray DataArray
|
|
475
|
+
"""
|
|
476
|
+
clip_mask_arr = geometry_mask(
|
|
477
|
+
geometries=geometries,
|
|
478
|
+
out_shape=(int(xds.rio.height), int(xds.rio.width)),
|
|
479
|
+
transform=xds.rio.transform(recalc=True),
|
|
480
|
+
invert=not invert,
|
|
481
|
+
all_touched=all_touched,
|
|
482
|
+
)
|
|
483
|
+
clip_mask_xray = xarray.DataArray(
|
|
484
|
+
clip_mask_arr,
|
|
485
|
+
dims=(xds.rio.y_dim, xds.rio.x_dim),
|
|
486
|
+
)
|
|
487
|
+
cropped_ds = xds.where(clip_mask_xray)
|
|
488
|
+
if drop:
|
|
489
|
+
cropped_ds.rio.set_spatial_dims(
|
|
490
|
+
x_dim=xds.rio.x_dim, y_dim=xds.rio.y_dim, inplace=True
|
|
491
|
+
)
|
|
492
|
+
cropped_ds = cropped_ds.rio.isel_window(
|
|
493
|
+
rasterio.windows.get_data_window(
|
|
494
|
+
numpy.ma.masked_array(clip_mask_arr, ~clip_mask_arr)
|
|
495
|
+
)
|
|
496
|
+
)
|
|
497
|
+
if xds.rio.nodata is not None and not numpy.isnan(xds.rio.nodata):
|
|
498
|
+
cropped_ds = cropped_ds.fillna(xds.rio.nodata)
|
|
499
|
+
|
|
500
|
+
return cropped_ds.astype(xds.dtype)
|
|
@@ -11,7 +11,7 @@ from rasterio.crs import CRS
|
|
|
11
11
|
from rasterio.merge import merge as _rio_merge
|
|
12
12
|
from xarray import DataArray, Dataset, IndexVariable
|
|
13
13
|
|
|
14
|
-
from rioxarray.
|
|
14
|
+
from rioxarray._spatial_utils import _get_nonspatial_coords, _make_coords
|
|
15
15
|
|
|
16
16
|
|
|
17
17
|
class RasterioDatasetDuck:
|