-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathapply.py
212 lines (179 loc) · 6.73 KB
/
apply.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
from typing import Callable, Optional, Union
import numpy as np
import scipy.ndimage
import xarray as xr
from shapely.geometry import MultiPolygon, Polygon, shape
from shapely.ops import unary_union
from openeo_processes_dask.process_implementations.cubes.mask_polygon import (
mask_polygon,
)
from openeo_processes_dask.process_implementations.data_model import (
RasterCube,
VectorCube,
)
from openeo_processes_dask.process_implementations.exceptions import (
DimensionNotAvailable,
KernelDimensionsUneven,
)
__all__ = ["apply", "apply_dimension", "apply_kernel"]
def apply(
data: RasterCube, process: Callable, context: Optional[dict] = None
) -> RasterCube:
positional_parameters = {"x": 0}
named_parameters = {"context": context}
result = xr.apply_ufunc(
process,
data,
dask="allowed",
kwargs={
"positional_parameters": positional_parameters,
"named_parameters": named_parameters,
},
)
return result
def apply_dimension(
data: RasterCube,
process: Callable,
dimension: str,
target_dimension: Optional[str] = None,
context: Optional[dict] = None,
) -> RasterCube:
if context is None:
context = {}
if dimension not in data.dims:
raise DimensionNotAvailable(
f"Provided dimension ({dimension}) not found in data.dims: {data.dims}"
)
keepdims = False
is_new_dim_added = target_dimension is not None
if is_new_dim_added:
keepdims = True
if target_dimension is None:
target_dimension = dimension
positional_parameters = {"data": 0}
named_parameters = {"context": context}
# This transpose (and back later) is needed because apply_ufunc automatically moves
# input_core_dimensions to the last axes
reordered_data = data.transpose(..., dimension)
result = xr.apply_ufunc(
process,
reordered_data,
input_core_dims=[[dimension]],
output_core_dims=[[dimension]],
dask="allowed",
kwargs={
"positional_parameters": positional_parameters,
"named_parameters": named_parameters,
"axis": reordered_data.get_axis_num(dimension),
"keepdims": keepdims,
"source_transposed_axis": data.get_axis_num(dimension),
"context": context,
},
exclude_dims={dimension},
)
reordered_result = result.transpose(*data.dims, ...)
if dimension in reordered_result.dims:
result_len = len(reordered_result[dimension])
else:
result_len = 1
# Case 1: target_dimension is not defined/ is source dimension
if dimension == target_dimension:
# dimension labels preserved
# if the number of source dimension's values is equal to the number of computed values
if len(reordered_data[dimension]) == result_len:
reordered_result[dimension] == reordered_data[dimension].values
else:
reordered_result[dimension] = np.arange(result_len)
elif target_dimension in reordered_result.dims:
# source dimension is not target dimension
# target dimension exists with a single label only
if len(reordered_result[target_dimension]) == 1:
reordered_result = reordered_result.drop_vars(target_dimension).squeeze(
target_dimension
)
reordered_result = reordered_result.rename({dimension: target_dimension})
reordered_result[dimension] = np.arange(result_len)
else:
raise Exception(
f"Cannot rename dimension {dimension} to {target_dimension} as {target_dimension} already exists in dataset and contains more than one label: {reordered_result[target_dimension]}. See process definition. "
)
else:
# source dimension is not the target dimension and the latter does not exist
reordered_result = reordered_result.rename({dimension: target_dimension})
reordered_result[target_dimension] = np.arange(result_len)
if data.rio.crs is not None:
try:
reordered_result.rio.write_crs(data.rio.crs, inplace=True)
except ValueError:
pass
return reordered_result
def apply_kernel(
data: RasterCube,
kernel: np.ndarray,
factor: Optional[float] = 1,
border: Union[float, str, None] = 0,
replace_invalid: Optional[float] = 0,
) -> RasterCube:
kernel = np.asarray(kernel)
if any(dim % 2 == 0 for dim in kernel.shape):
raise KernelDimensionsUneven(
"Each dimension of the kernel must have an uneven number of elements."
)
def convolve(data, kernel, mode="constant", cval=0, fill_value=0):
dims = data.openeo.spatial_dims
convolved = lambda data: scipy.ndimage.convolve(
data, kernel, mode=mode, cval=cval
)
data_masked = data.fillna(fill_value)
return xr.apply_ufunc(
convolved,
data_masked,
vectorize=True,
dask="parallelized",
input_core_dims=[dims],
output_core_dims=[dims],
output_dtypes=[data.dtype],
dask_gufunc_kwargs={"allow_rechunk": True},
).transpose(*data.dims)
openeo_scipy_modes = {
"replicate": "nearest",
"reflect": "reflect",
"reflect_pixel": "mirror",
"wrap": "wrap",
}
if isinstance(border, int) or isinstance(border, float):
mode = "constant"
cval = border
else:
mode = openeo_scipy_modes[border]
cval = 0
return convolve(data, kernel, mode, cval, replace_invalid) * factor
def apply_polygon(
data: RasterCube,
polygons: Union[VectorCube, dict],
process: Callable,
mask_value: Optional[Union[int, float, str, None]] = None,
context: Optional[dict] = None,
) -> RasterCube:
if isinstance(polygons, dict) and polygons.get("type") == "FeatureCollection":
polygon_geometries = [
shape(feature["geometry"]) for feature in polygons["features"]
]
elif isinstance(polygons, dict) and polygons.get("type") in [
"Polygon",
"MultiPolygon",
]:
polygon_geometries = [shape(polygons)]
else:
raise ValueError(
"Unsupported polygons format. Expected GeoJSON-like FeatureCollection or Polygon."
)
unified_polygon = unary_union(polygon_geometries)
if isinstance(unified_polygon, MultiPolygon) and len(unified_polygon.geoms) < len(
polygon_geometries
):
raise Exception("GeometriesOverlap")
masked_data = mask_polygon(data, polygons, replacement=np.nan)
processed_data = apply(masked_data, process, context=context)
result = mask_polygon(processed_data, polygons, replacement=mask_value)
return result