xarray-safeguards 0.1.0__py3-none-any.whl
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.
|
@@ -0,0 +1,1027 @@
|
|
|
1
|
+
"""
|
|
2
|
+
# Safe, Trusted, and Fearless (chunked) lossy compression with `xarray-safeguards`
|
|
3
|
+
|
|
4
|
+
Lossy compression can be *scary* as valuable information or features of the
|
|
5
|
+
data may be lost.
|
|
6
|
+
|
|
7
|
+
By using [`Safeguards`][compression_safeguards.api.Safeguards] to **guarantee**
|
|
8
|
+
your safety requirements, lossy compression can be applied safely and
|
|
9
|
+
*without fear*.
|
|
10
|
+
|
|
11
|
+
## Overview
|
|
12
|
+
|
|
13
|
+
This package provides functionality to use safeguards with (chunked)
|
|
14
|
+
[`xarray.DataArray`][xarray.DataArray]s and cross-chunk boundary conditions.
|
|
15
|
+
Since applying safeguards to chunked data by yourself is very difficult and
|
|
16
|
+
error-prone, this package handles all of the complexity for you with a simple
|
|
17
|
+
and safe API.
|
|
18
|
+
|
|
19
|
+
In particular, `xarray-safeguards` provides the
|
|
20
|
+
[`produce_data_array_correction`][.produce_data_array_correction]
|
|
21
|
+
function to produce a correction such that certain properties of the original
|
|
22
|
+
data are preserved after compression, which can be stored in the same or a
|
|
23
|
+
different dataset (or file).
|
|
24
|
+
|
|
25
|
+
This correction can be applied to the decompressed data using the
|
|
26
|
+
[`apply_data_array_correction`][.apply_data_array_correction] function or the
|
|
27
|
+
[`.safeguarded`][.DatasetSafeguardedAccessor] accessor on datasets.
|
|
28
|
+
|
|
29
|
+
This package also provides the [`.safeguards`][.DataArraySafeguardsAccessor]
|
|
30
|
+
accessor on correction or corrected data arrays to inspect the safeguards that
|
|
31
|
+
were applied.
|
|
32
|
+
|
|
33
|
+
By applying the corrections produced by `produce_data_array_correction`, data
|
|
34
|
+
that was compressed with badly-behaving lossy compressors can be safely used,
|
|
35
|
+
at the cost of potentially less efficient compression, and lossy compression
|
|
36
|
+
can be applied *without fear*.
|
|
37
|
+
|
|
38
|
+
## Example
|
|
39
|
+
|
|
40
|
+
You can produce and apply the corrections to uphold an absolute error bound of
|
|
41
|
+
$eb_{abs} = 0.1$ for an already-compressed data array as follows:
|
|
42
|
+
|
|
43
|
+
```py
|
|
44
|
+
import numpy as np
|
|
45
|
+
import xarray as xr
|
|
46
|
+
from xarray_safeguards import apply_data_array_correction, produce_data_array_correction
|
|
47
|
+
|
|
48
|
+
# some (chunked) n-dimensional data array
|
|
49
|
+
da = xr.DataArray(np.linspace(-10, 10, 21), name="da").chunk(10)
|
|
50
|
+
# lossy-compressed approximation of the data, here all zeros
|
|
51
|
+
da_approximation = xr.DataArray(np.zeros_like(da.values), name="da").chunk(10)
|
|
52
|
+
|
|
53
|
+
da_correction = produce_data_array_correction(
|
|
54
|
+
data=da,
|
|
55
|
+
approximation=da_approximation,
|
|
56
|
+
# guarantee an absolute error bound of 0.1:
|
|
57
|
+
# |x - x'| <= 0.1
|
|
58
|
+
safeguards=[dict(kind="eb", type="abs", eb=0.1)],
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
## (a) manual correction ##
|
|
62
|
+
|
|
63
|
+
da_corrected = apply_data_array_correction(da_approximation, da_correction)
|
|
64
|
+
np.testing.assert_allclose(da_corrected.values, da.values, rtol=0, atol=0.1)
|
|
65
|
+
|
|
66
|
+
## (b) automatic correction with xarray accessors ##
|
|
67
|
+
|
|
68
|
+
# combine the lossy approximation and the correction into one dataset
|
|
69
|
+
# e.g. by loading them from different files using `xarray.open_mfdataset`
|
|
70
|
+
ds = xr.Dataset({
|
|
71
|
+
da_approximation.name: da_approximation,
|
|
72
|
+
da_correction.name: da_correction,
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
# access the safeguarded dataset that applies all corrections
|
|
76
|
+
ds_safeguarded: xr.Dataset = ds.safeguarded
|
|
77
|
+
np.testing.assert_allclose(ds_safeguarded["da"].values, da.values, rtol=0, atol=0.1)
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Please refer to the
|
|
81
|
+
[`compression_safeguards.SafeguardKind`][compression_safeguards.safeguards.SafeguardKind]
|
|
82
|
+
for an enumeration of all supported safeguards.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
__all__ = [
|
|
86
|
+
"produce_data_array_correction",
|
|
87
|
+
"apply_data_array_correction",
|
|
88
|
+
"DataValue",
|
|
89
|
+
"DatasetSafeguardedAccessor",
|
|
90
|
+
"DataArraySafeguardsAccessor",
|
|
91
|
+
]
|
|
92
|
+
|
|
93
|
+
import json
|
|
94
|
+
import warnings
|
|
95
|
+
from collections.abc import Collection, Mapping
|
|
96
|
+
from types import MappingProxyType
|
|
97
|
+
from typing import Literal, TypeAlias, assert_never
|
|
98
|
+
|
|
99
|
+
import dask
|
|
100
|
+
import dask.array
|
|
101
|
+
import numpy as np
|
|
102
|
+
import xarray as xr
|
|
103
|
+
from compression_safeguards.api import Safeguards
|
|
104
|
+
from compression_safeguards.safeguards.abc import Safeguard
|
|
105
|
+
from compression_safeguards.safeguards.stencil import (
|
|
106
|
+
BoundaryCondition,
|
|
107
|
+
NeighbourhoodAxis,
|
|
108
|
+
)
|
|
109
|
+
from compression_safeguards.utils._compat import _ensure_array
|
|
110
|
+
from compression_safeguards.utils.bindings import Parameter, Value
|
|
111
|
+
from compression_safeguards.utils.error import (
|
|
112
|
+
LateBoundParameterResolutionError,
|
|
113
|
+
TypeCheckError,
|
|
114
|
+
TypeSetError,
|
|
115
|
+
ctx,
|
|
116
|
+
)
|
|
117
|
+
from compression_safeguards.utils.typing import JSON, S, T
|
|
118
|
+
from xarray.namedarray.parallelcompat import get_chunked_array_type
|
|
119
|
+
|
|
120
|
+
DataValue: TypeAlias = int | float | np.number | xr.DataArray
|
|
121
|
+
"""
|
|
122
|
+
Parameter value type that includes scalar numbers and data arrays thereof.
|
|
123
|
+
"""
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def produce_data_array_correction(
|
|
127
|
+
data: xr.DataArray,
|
|
128
|
+
approximation: xr.DataArray,
|
|
129
|
+
*,
|
|
130
|
+
safeguards: Collection[dict[str, JSON] | Safeguard],
|
|
131
|
+
late_bound: Mapping[str, DataValue] = MappingProxyType(dict()),
|
|
132
|
+
check_chunks_first: bool = True,
|
|
133
|
+
allow_unsafe_safeguards_override: bool = False,
|
|
134
|
+
) -> xr.DataArray:
|
|
135
|
+
"""
|
|
136
|
+
Produce the correction required to make the `approximation` data array satisfy the `safeguards` relative to the `data` array.
|
|
137
|
+
|
|
138
|
+
The `data` array may be chunked[^1] and the `approximation` array must use the
|
|
139
|
+
same chunking. Importantly, the `data` array must contain the complete data,
|
|
140
|
+
i.e. not just a sub-chunk of the data, so that non-pointwise safeguards are
|
|
141
|
+
correctly applied.
|
|
142
|
+
|
|
143
|
+
If the the `data` array is chunked, the correction is produced lazily,
|
|
144
|
+
otherwise it is computed eagerly.
|
|
145
|
+
|
|
146
|
+
The `data` array must have a name and the `approximation` array must use the
|
|
147
|
+
same name.
|
|
148
|
+
|
|
149
|
+
[^1]: At the moment, only chunking with `dask` is supported.
|
|
150
|
+
|
|
151
|
+
Parameters
|
|
152
|
+
----------
|
|
153
|
+
data : xr.DataArray
|
|
154
|
+
The data array, relative to which the safeguards are enforced.
|
|
155
|
+
approximation : xr.DataArray
|
|
156
|
+
The approximation array for which the correction is produced.
|
|
157
|
+
safeguards : Collection[dict[str, JSON] | Safeguard]
|
|
158
|
+
The safeguards that will be applied relative to the `data` array.
|
|
159
|
+
|
|
160
|
+
They can either be
|
|
161
|
+
passed as a safeguard configuration [`dict`][dict] or an already
|
|
162
|
+
initialized
|
|
163
|
+
[`Safeguard`][compression_safeguards.safeguards.abc.Safeguard].
|
|
164
|
+
|
|
165
|
+
Please refer to the
|
|
166
|
+
[`SafeguardKind`][compression_safeguards.safeguards.SafeguardKind]
|
|
167
|
+
for an enumeration of all supported safeguards.
|
|
168
|
+
late_bound : Mapping[str, DataValue]
|
|
169
|
+
The bindings for all late-bound parameters of the `safeguards`.
|
|
170
|
+
|
|
171
|
+
The bindings must resolve all late-bound parameters and include no
|
|
172
|
+
extraneous parameters.
|
|
173
|
+
|
|
174
|
+
If a binding resolves to a [`xr.DataArray`][xarray.DataArray], its
|
|
175
|
+
dimensions must be a subset of `data.dims` and the shape must be
|
|
176
|
+
broadcastable to the data shape, i.e. each axis must have either
|
|
177
|
+
size 1 or the same size as the matching dimension in the `data`.
|
|
178
|
+
|
|
179
|
+
This method automatically provides the following built-in constants
|
|
180
|
+
to the safeguards, which must not be included:
|
|
181
|
+
|
|
182
|
+
- `$x` and `$X`: the original `data` as a constant
|
|
183
|
+
- `$x_min` and `$x_max`: the global non-NaN minimum/maximum of the data
|
|
184
|
+
- `$x_finite_min` and `$x_finite_max`: the global finite
|
|
185
|
+
minimum/maximum of the data
|
|
186
|
+
- `$d_DIM` for each dimension `DIM` of the `data` array
|
|
187
|
+
check_chunks_first : bool
|
|
188
|
+
If [`True`][True], all chunks are first checked to determine if no
|
|
189
|
+
corrections are required, which requires eagerly computing the check
|
|
190
|
+
result across all chunks. If [`False`][False], the check is skipped and
|
|
191
|
+
corrections for all chunks are produced, even if no corrections are
|
|
192
|
+
required.
|
|
193
|
+
allow_unsafe_safeguards_override : bool
|
|
194
|
+
**WARNING:** This option is *unsafe* and must only be passed if
|
|
195
|
+
instructed. Do *not* pass this option otherwise.
|
|
196
|
+
|
|
197
|
+
Returns
|
|
198
|
+
-------
|
|
199
|
+
correction : xr.DataArray
|
|
200
|
+
The correction array
|
|
201
|
+
|
|
202
|
+
Raises
|
|
203
|
+
------
|
|
204
|
+
ValueError
|
|
205
|
+
if the `data` has already been corrected by safeguards, i.e. if it is
|
|
206
|
+
not the original uncorrected data, which will create a printer problem.
|
|
207
|
+
ValueError
|
|
208
|
+
if the `approximation` has already been corrected, which may create a
|
|
209
|
+
printer problem.
|
|
210
|
+
TypeSetError
|
|
211
|
+
if the `data` uses an unsupported data type.
|
|
212
|
+
ValueError
|
|
213
|
+
if the `data`'s dimensions, shape, dtype, chunks, or name do not match
|
|
214
|
+
the `approximation`'s, or if the data name is [`None`][None].
|
|
215
|
+
LateBoundParameterResolutionError
|
|
216
|
+
if `late_bound` does not resolve all late-bound parameters of the
|
|
217
|
+
safeguards or includes any extraneous parameters.
|
|
218
|
+
TypeError
|
|
219
|
+
if a late-bound parameter is not a scalar or
|
|
220
|
+
[`xarray.DataArray`][xarray.DataArray].
|
|
221
|
+
ValueError
|
|
222
|
+
if a late-bound parameter's dimensions are not a subset of the `data`
|
|
223
|
+
dimensions, or it is not broadcastable to the `data` shape.
|
|
224
|
+
...
|
|
225
|
+
if instantiating a safeguard, checking a safeguard, or computing the
|
|
226
|
+
correction for a safeguard raises an exception.
|
|
227
|
+
"""
|
|
228
|
+
|
|
229
|
+
# small safeguard against the printer problem
|
|
230
|
+
if "safeguards" in data.attrs:
|
|
231
|
+
with ctx.parameter("data"):
|
|
232
|
+
raise (
|
|
233
|
+
ValueError(
|
|
234
|
+
"computing the safeguards correction relative to a `data` "
|
|
235
|
+
+ "array that has *already* been safeguards-corrected "
|
|
236
|
+
+ "before is unsafe as compression errors can accumulate "
|
|
237
|
+
+ "when the original uncompressed data is not known; this "
|
|
238
|
+
+ "is also known as the printer problem; please pass the "
|
|
239
|
+
+ "original uncompressed and uncorrected `data` to ensure "
|
|
240
|
+
+ "that the safeguards can be applied correctly"
|
|
241
|
+
)
|
|
242
|
+
| ctx
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
if "safeguards" in approximation.attrs:
|
|
246
|
+
if allow_unsafe_safeguards_override:
|
|
247
|
+
warnings.warn("`allow_unsafe_safeguards_override`=True")
|
|
248
|
+
elif "safeguards" in approximation.attrs:
|
|
249
|
+
with ctx.parameter("approximation"):
|
|
250
|
+
raise (
|
|
251
|
+
ValueError(
|
|
252
|
+
"computing the safeguards correction for a "
|
|
253
|
+
+ "`approximation` array that has *already* been "
|
|
254
|
+
+ "safeguards-corrected before is unsafe as the "
|
|
255
|
+
+ "safety guarantees provided by the previously "
|
|
256
|
+
+ "applied safeguards may not be provided by the newly "
|
|
257
|
+
+ "applied safeguards, thus violating the earlier "
|
|
258
|
+
+ "guarantees; this is also known as the printer "
|
|
259
|
+
+ "problem; please manually inspect the `.safeguards` "
|
|
260
|
+
+ "property of the `approximation` array and ensure that "
|
|
261
|
+
+ "they are included in the new `safeguards` and then "
|
|
262
|
+
+ "pass `allow_unsafe_safeguards_override=True` to "
|
|
263
|
+
+ "this function"
|
|
264
|
+
)
|
|
265
|
+
| ctx
|
|
266
|
+
)
|
|
267
|
+
elif allow_unsafe_safeguards_override is not False:
|
|
268
|
+
with ctx.parameter("allow_unsafe_safeguards_override"):
|
|
269
|
+
raise (
|
|
270
|
+
ValueError("unsafe option that must only be passed if instructed") | ctx
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
TypeSetError.check_dtype_or_raise(data.dtype, Safeguards.supported_dtypes())
|
|
274
|
+
|
|
275
|
+
with ctx.parameter("approximation"):
|
|
276
|
+
if approximation.dims != data.dims:
|
|
277
|
+
raise ValueError("approximation.dims must match data.dims") | ctx
|
|
278
|
+
if approximation.shape != data.shape:
|
|
279
|
+
raise ValueError("approximation.shape must match data.shape") | ctx
|
|
280
|
+
if approximation.dtype != data.dtype:
|
|
281
|
+
raise ValueError("approximation.dtype must match data.dtype") | ctx
|
|
282
|
+
if approximation.chunks != data.chunks:
|
|
283
|
+
raise ValueError("approximation.chunks must match data.chunks") | ctx
|
|
284
|
+
if approximation.name != data.name:
|
|
285
|
+
raise ValueError("approximation.name must match data.name") | ctx
|
|
286
|
+
with ctx.parameter("data"):
|
|
287
|
+
if data.name is None:
|
|
288
|
+
raise ValueError("data.name must not be None") | ctx
|
|
289
|
+
|
|
290
|
+
safeguards_: Safeguards = Safeguards(safeguards=safeguards)
|
|
291
|
+
|
|
292
|
+
builtin_late_bound: frozenset[Parameter] = frozenset(
|
|
293
|
+
safeguards_.builtin_late_bound
|
|
294
|
+
) | frozenset(
|
|
295
|
+
[
|
|
296
|
+
Parameter("$x_min"),
|
|
297
|
+
Parameter("$x_max"),
|
|
298
|
+
Parameter("$x_finite_min"),
|
|
299
|
+
Parameter("$x_finite_max"),
|
|
300
|
+
]
|
|
301
|
+
+ [Parameter(f"$d_{d}") for d in data.dims]
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
safeguards_late_bound_reqs = frozenset(safeguards_.late_bound)
|
|
305
|
+
late_bound_reqs = frozenset(safeguards_late_bound_reqs - builtin_late_bound)
|
|
306
|
+
late_bound_keys = frozenset(Parameter(k) for k in late_bound.keys())
|
|
307
|
+
|
|
308
|
+
LateBoundParameterResolutionError.check_or_raise(late_bound_reqs, late_bound_keys)
|
|
309
|
+
|
|
310
|
+
# create the global built-in late-bound bindings with $x_min, $x_max,
|
|
311
|
+
# $x_finite_min, and $x_finite_max,
|
|
312
|
+
# and split-out the late-bound data array bindings that require chunking
|
|
313
|
+
late_bound_global: dict[str, int | float | np.number] = dict()
|
|
314
|
+
late_bound_data_arrays: dict[str, xr.DataArray] = dict()
|
|
315
|
+
if "$x_min" in safeguards_late_bound_reqs:
|
|
316
|
+
da_min = (
|
|
317
|
+
np.nanmin(data)
|
|
318
|
+
if data.size > 0 and not np.all(np.isnan(data))
|
|
319
|
+
else data.dtype.type(0)
|
|
320
|
+
)
|
|
321
|
+
late_bound_global["$x_min"] = da_min
|
|
322
|
+
if "$x_max" in safeguards_late_bound_reqs:
|
|
323
|
+
da_max = (
|
|
324
|
+
np.nanmax(data)
|
|
325
|
+
if data.size > 0 and not np.all(np.isnan(data))
|
|
326
|
+
else data.dtype.type(0)
|
|
327
|
+
)
|
|
328
|
+
late_bound_global["$x_max"] = da_max
|
|
329
|
+
if "$x_finite_min" in safeguards_late_bound_reqs:
|
|
330
|
+
da_finite_min = (
|
|
331
|
+
np.nanmin(data.where(np.isfinite(data)))
|
|
332
|
+
if data.size > 0 and np.any(np.isfinite(data))
|
|
333
|
+
else data.dtype.type(0)
|
|
334
|
+
)
|
|
335
|
+
late_bound_global["$x_finite_min"] = da_finite_min
|
|
336
|
+
if "$x_finite_max" in safeguards_late_bound_reqs:
|
|
337
|
+
da_finite_max = (
|
|
338
|
+
np.nanmax(data.where(np.isfinite(data)))
|
|
339
|
+
if data.size > 0 and np.any(np.isfinite(data))
|
|
340
|
+
else data.dtype.type(0)
|
|
341
|
+
)
|
|
342
|
+
late_bound_global["$x_finite_max"] = da_finite_max
|
|
343
|
+
with ctx.parameter("late_bound"):
|
|
344
|
+
for k, v in late_bound.items():
|
|
345
|
+
with ctx.parameter(k):
|
|
346
|
+
TypeCheckError.check_instance_or_raise(
|
|
347
|
+
v, int | float | np.number | xr.DataArray
|
|
348
|
+
)
|
|
349
|
+
if isinstance(v, int | float | np.number):
|
|
350
|
+
late_bound_global[k] = v
|
|
351
|
+
else:
|
|
352
|
+
if not frozenset(v.dims).issubset(data.dims):
|
|
353
|
+
raise ValueError("dims are not a subset of data dims") | ctx
|
|
354
|
+
for d, ds in v.sizes.items():
|
|
355
|
+
if (ds != 1) and (ds != data.sizes[d]):
|
|
356
|
+
raise (
|
|
357
|
+
ValueError(
|
|
358
|
+
f"dim {d} is not broadcastable to the data shape"
|
|
359
|
+
)
|
|
360
|
+
| ctx
|
|
361
|
+
)
|
|
362
|
+
late_bound_data_arrays[k] = v
|
|
363
|
+
|
|
364
|
+
correction_name = f"{data.name}_sg"
|
|
365
|
+
correction_attrs = dict(
|
|
366
|
+
safeguarded=data.name, safeguards=json.dumps(safeguards_.get_config())
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
da_correction: xr.DataArray
|
|
370
|
+
|
|
371
|
+
# special case for no chunking: just compute eagerly
|
|
372
|
+
if data.chunks is None:
|
|
373
|
+
# provide built-in late-bound bindings $d for the data dimensions
|
|
374
|
+
late_bound_full: dict[str, Value] = dict(**late_bound_global)
|
|
375
|
+
for i, d in enumerate(data.dims):
|
|
376
|
+
if f"$d_{d}" in safeguards_late_bound_reqs:
|
|
377
|
+
shape = [1 for _ in range(len(data.dims))]
|
|
378
|
+
shape[i] = data.shape[i]
|
|
379
|
+
late_bound_full[f"$d_{d}"] = data[d].values.reshape(shape)
|
|
380
|
+
for k, dv in late_bound_data_arrays.items():
|
|
381
|
+
axes = sorted(
|
|
382
|
+
[i for i in range(len(dv.dims))],
|
|
383
|
+
key=lambda i: data.dims.index(dv.dims[i]),
|
|
384
|
+
)
|
|
385
|
+
shape = [1 for _ in range(len(data.dims))]
|
|
386
|
+
for d in dv.dims:
|
|
387
|
+
i = data.dims.index(d)
|
|
388
|
+
shape[i] = data.shape[i]
|
|
389
|
+
late_bound_full[k] = dv.values.transpose(axes).reshape(shape)
|
|
390
|
+
|
|
391
|
+
da_correction = (
|
|
392
|
+
data.copy(
|
|
393
|
+
data=safeguards_.compute_correction(
|
|
394
|
+
data.values,
|
|
395
|
+
approximation.values,
|
|
396
|
+
late_bound=late_bound_full,
|
|
397
|
+
where=True,
|
|
398
|
+
)
|
|
399
|
+
)
|
|
400
|
+
.rename(correction_name)
|
|
401
|
+
.assign_attrs(**correction_attrs)
|
|
402
|
+
)
|
|
403
|
+
|
|
404
|
+
# drop the previous encoding from the variable but not the coords
|
|
405
|
+
return da_correction._replace(variable=da_correction.variable.drop_encoding())
|
|
406
|
+
|
|
407
|
+
# provide built-in late-bound bindings $d for the data dimensions
|
|
408
|
+
chunked_late_bound: dict[str, dask.array.Array] = dict()
|
|
409
|
+
for i, d in enumerate(data.dims):
|
|
410
|
+
if f"$d_{d}" in safeguards_late_bound_reqs:
|
|
411
|
+
shape = [1 for _ in range(len(data.dims))]
|
|
412
|
+
shape[i] = data.shape[i]
|
|
413
|
+
chunked_late_bound[f"$d_{d}"] = dask.array.broadcast_to(
|
|
414
|
+
data[d].data.reshape(shape),
|
|
415
|
+
shape=data.shape,
|
|
416
|
+
meta=np.array((), dtype=data[d].dtype),
|
|
417
|
+
).rechunk(data.chunks)
|
|
418
|
+
for k, v in late_bound_data_arrays.items():
|
|
419
|
+
dims = sorted(v.dims, key=lambda i: data.dims.index(i))
|
|
420
|
+
shape = [1 for _ in range(len(data.dims))]
|
|
421
|
+
for d in v.dims:
|
|
422
|
+
i = data.dims.index(d)
|
|
423
|
+
shape[i] = data.shape[i]
|
|
424
|
+
chunked_late_bound[k] = dask.array.broadcast_to(
|
|
425
|
+
v.transpose(*dims, transpose_coords=False).data.reshape(shape),
|
|
426
|
+
shape=data.shape,
|
|
427
|
+
meta=np.array((), dtype=v.dtype),
|
|
428
|
+
).rechunk(data.chunks)
|
|
429
|
+
|
|
430
|
+
required_stencil = safeguards_.compute_required_stencil_for_chunked_correction(
|
|
431
|
+
data.shape
|
|
432
|
+
)
|
|
433
|
+
correction_dtype: np.dtype[np.unsignedinteger] = (
|
|
434
|
+
safeguards_.correction_dtype_for_data(data.dtype)
|
|
435
|
+
)
|
|
436
|
+
|
|
437
|
+
# special case for no stencil: just apply independently to each chunk
|
|
438
|
+
if all(s.before == 0 and s.after == 0 for b, s in required_stencil):
|
|
439
|
+
|
|
440
|
+
def _compute_independent_chunk_correction(
|
|
441
|
+
data_chunk: np.ndarray[S, np.dtype[T]],
|
|
442
|
+
approximation_chunk: np.ndarray[S, np.dtype[T]],
|
|
443
|
+
*late_bound_chunks: np.ndarray[S, np.dtype[T]],
|
|
444
|
+
late_bound_names: tuple[str, ...],
|
|
445
|
+
late_bound_global: dict[str, int | float | np.number],
|
|
446
|
+
safeguards: Safeguards,
|
|
447
|
+
) -> np.ndarray[S, np.dtype[np.unsignedinteger]]:
|
|
448
|
+
assert len(late_bound_chunks) == len(late_bound_names), (
|
|
449
|
+
"late-bound chunks and names mismatch"
|
|
450
|
+
)
|
|
451
|
+
|
|
452
|
+
# ensure that we pass np.ndarray's to the compression-safeguards
|
|
453
|
+
data_chunk = _ensure_array(data_chunk)
|
|
454
|
+
approximation_chunk = _ensure_array(approximation_chunk)
|
|
455
|
+
late_bound_chunks = tuple(_ensure_array(lb) for lb in late_bound_chunks)
|
|
456
|
+
|
|
457
|
+
late_bound_chunk: dict[str, Value] = dict(
|
|
458
|
+
**late_bound_global,
|
|
459
|
+
**{p: v for p, v in zip(late_bound_names, late_bound_chunks)},
|
|
460
|
+
)
|
|
461
|
+
|
|
462
|
+
return safeguards.compute_correction(
|
|
463
|
+
data_chunk, approximation_chunk, late_bound=late_bound_chunk, where=True
|
|
464
|
+
)
|
|
465
|
+
|
|
466
|
+
da_correction = (
|
|
467
|
+
data.copy(
|
|
468
|
+
data=dask.array.map_blocks(
|
|
469
|
+
_compute_independent_chunk_correction,
|
|
470
|
+
data.data,
|
|
471
|
+
approximation.data,
|
|
472
|
+
*chunked_late_bound.values(),
|
|
473
|
+
dtype=correction_dtype,
|
|
474
|
+
chunks=None, # map_blocks figures out the chunks
|
|
475
|
+
enforce_ndim=True,
|
|
476
|
+
meta=np.array((), dtype=correction_dtype),
|
|
477
|
+
late_bound_names=tuple(chunked_late_bound.keys()),
|
|
478
|
+
late_bound_global=late_bound_global,
|
|
479
|
+
safeguards=safeguards_,
|
|
480
|
+
)
|
|
481
|
+
)
|
|
482
|
+
.rename(correction_name)
|
|
483
|
+
.assign_attrs(**correction_attrs)
|
|
484
|
+
)
|
|
485
|
+
|
|
486
|
+
# drop the previous encoding from the variable but not the coords
|
|
487
|
+
return da_correction._replace(variable=da_correction.variable.drop_encoding())
|
|
488
|
+
|
|
489
|
+
boundary: Literal["none", "periodic"] = "none"
|
|
490
|
+
depth_: list[tuple[int, int]] = []
|
|
491
|
+
for a, (b, s) in zip(data.shape, required_stencil):
|
|
492
|
+
# dask doesn't support depths larger than the axes,
|
|
493
|
+
# so clip that axis and prefer no boundary condition
|
|
494
|
+
# as it will anyways be rechunked to just a single chunk
|
|
495
|
+
if s.before >= a or s.after >= a:
|
|
496
|
+
depth_.append((a, a))
|
|
497
|
+
else:
|
|
498
|
+
depth_.append((s.before, s.after))
|
|
499
|
+
match b:
|
|
500
|
+
case BoundaryCondition.valid:
|
|
501
|
+
pass
|
|
502
|
+
case BoundaryCondition.wrap:
|
|
503
|
+
boundary = "periodic"
|
|
504
|
+
case _:
|
|
505
|
+
assert_never(b)
|
|
506
|
+
|
|
507
|
+
match boundary:
|
|
508
|
+
case "none":
|
|
509
|
+
depth: tuple[int | tuple[int, int], ...] = tuple(
|
|
510
|
+
b if b == a else (a, b) for a, b in depth_
|
|
511
|
+
)
|
|
512
|
+
case "periodic":
|
|
513
|
+
# dask only supports asymmetric depths for the none boundary
|
|
514
|
+
depth = tuple(max(a, b) for a, b in depth_)
|
|
515
|
+
case _:
|
|
516
|
+
assert_never(boundary)
|
|
517
|
+
|
|
518
|
+
def _check_overlapping_stencil_chunk(
|
|
519
|
+
data_chunk: np.ndarray[S, np.dtype[T]],
|
|
520
|
+
approximation_chunk: np.ndarray[S, np.dtype[T]],
|
|
521
|
+
data_indices_chunk: np.ndarray[S, np.dtype[np.intp]],
|
|
522
|
+
*late_bound_chunks: np.ndarray[S, np.dtype[T]],
|
|
523
|
+
late_bound_names: tuple[str, ...],
|
|
524
|
+
late_bound_global: dict[str, int | float | np.number],
|
|
525
|
+
safeguards: Safeguards,
|
|
526
|
+
data_shape: tuple[int, ...],
|
|
527
|
+
depth_: tuple[int | tuple[int, int], ...],
|
|
528
|
+
boundary_: Literal["none", "periodic"],
|
|
529
|
+
block_info=None,
|
|
530
|
+
) -> np.ndarray[tuple[int, ...], np.dtype[np.bool]]:
|
|
531
|
+
assert block_info is not None, "missing block info"
|
|
532
|
+
assert len(late_bound_chunks) == len(late_bound_names), (
|
|
533
|
+
"late-bound chunks and names mismatch"
|
|
534
|
+
)
|
|
535
|
+
assert len(depth_) == data_chunk.ndim, "overlap depth length mismatch"
|
|
536
|
+
|
|
537
|
+
# ensure that we pass np.ndarray's to the compression-safeguards
|
|
538
|
+
data_chunk = _ensure_array(data_chunk)
|
|
539
|
+
approximation_chunk = _ensure_array(approximation_chunk)
|
|
540
|
+
data_indices_chunk = _ensure_array(data_indices_chunk)
|
|
541
|
+
late_bound_chunks = tuple(_ensure_array(lb) for lb in late_bound_chunks)
|
|
542
|
+
|
|
543
|
+
late_bound_chunk: dict[str, Value] = dict(
|
|
544
|
+
**late_bound_global,
|
|
545
|
+
**{p: v for p, v in zip(late_bound_names, late_bound_chunks)},
|
|
546
|
+
)
|
|
547
|
+
|
|
548
|
+
depth: tuple[tuple[int, int], ...] = tuple(
|
|
549
|
+
(d, d) if isinstance(d, int) else d for d in depth_
|
|
550
|
+
)
|
|
551
|
+
|
|
552
|
+
match boundary_:
|
|
553
|
+
case "none":
|
|
554
|
+
# map_overlap passes the incorrect block_info,
|
|
555
|
+
# see https://github.com/dask/dask/issues/11349
|
|
556
|
+
# so we only trust chunk locations (but not array locations)
|
|
557
|
+
chunk_index: tuple[int, ...] = block_info[None]["chunk-location"]
|
|
558
|
+
num_chunks: tuple[int, ...] = block_info[None]["num-chunks"]
|
|
559
|
+
|
|
560
|
+
# the none boundary does not extend beyond the data boundary
|
|
561
|
+
# and so some stencils may be truncated
|
|
562
|
+
# dask guarantees that the chunks are at least as large as the
|
|
563
|
+
# stencil, so only the edge chunks have truncated stencils
|
|
564
|
+
chunk_stencil: tuple[
|
|
565
|
+
tuple[
|
|
566
|
+
Literal[BoundaryCondition.valid, BoundaryCondition.wrap],
|
|
567
|
+
NeighbourhoodAxis,
|
|
568
|
+
],
|
|
569
|
+
...,
|
|
570
|
+
] = tuple(
|
|
571
|
+
(
|
|
572
|
+
BoundaryCondition.valid,
|
|
573
|
+
NeighbourhoodAxis(
|
|
574
|
+
before=b if ci > 0 else 0, after=a if (ci + 1) < cn else 0
|
|
575
|
+
),
|
|
576
|
+
)
|
|
577
|
+
for (b, a), ci, cn in zip(depth, chunk_index, num_chunks)
|
|
578
|
+
)
|
|
579
|
+
case "periodic":
|
|
580
|
+
# the periodic boundary guarantees that we always have the
|
|
581
|
+
# stencil we asked for
|
|
582
|
+
chunk_stencil = tuple(
|
|
583
|
+
(BoundaryCondition.wrap, NeighbourhoodAxis(before=b, after=a))
|
|
584
|
+
for b, a in depth
|
|
585
|
+
)
|
|
586
|
+
case _:
|
|
587
|
+
assert_never(boundary_)
|
|
588
|
+
|
|
589
|
+
# extract the indices of the non-stencil-extended data indices chunk
|
|
590
|
+
data_indices_chunk_: np.ndarray[tuple[int, ...], np.dtype[np.intp]] = (
|
|
591
|
+
data_indices_chunk[
|
|
592
|
+
tuple(
|
|
593
|
+
slice(a.before, None if a.after == 0 else -a.after)
|
|
594
|
+
for b, a in chunk_stencil
|
|
595
|
+
)
|
|
596
|
+
]
|
|
597
|
+
)
|
|
598
|
+
chunk_shape = data_indices_chunk_.shape
|
|
599
|
+
|
|
600
|
+
# extract the offset of the chunk from the data indices chunk
|
|
601
|
+
if data_indices_chunk_.size > 0:
|
|
602
|
+
chunk_offset_index = int(data_indices_chunk_.flatten()[0])
|
|
603
|
+
chunk_offset_: list[int] = []
|
|
604
|
+
for s in data_shape[::-1]:
|
|
605
|
+
chunk_offset_.append(chunk_offset_index % s)
|
|
606
|
+
chunk_offset_index //= s
|
|
607
|
+
chunk_offset: tuple[int, ...] = tuple(chunk_offset_[::-1])
|
|
608
|
+
else:
|
|
609
|
+
chunk_offset = tuple(0 for _ in data_shape)
|
|
610
|
+
|
|
611
|
+
# this is safe because
|
|
612
|
+
# - map_overlap ensures we get chunks including their required stencil
|
|
613
|
+
chunk_is_ok = safeguards.check_chunk(
|
|
614
|
+
data_chunk,
|
|
615
|
+
approximation_chunk,
|
|
616
|
+
data_shape=data_shape,
|
|
617
|
+
chunk_offset=chunk_offset,
|
|
618
|
+
chunk_stencil=chunk_stencil,
|
|
619
|
+
late_bound_chunk=late_bound_chunk,
|
|
620
|
+
where_chunk=True,
|
|
621
|
+
)
|
|
622
|
+
|
|
623
|
+
# broadcast the boolean check scalar to the output chunk shape
|
|
624
|
+
return np.broadcast_to(chunk_is_ok, chunk_shape)
|
|
625
|
+
|
|
626
|
+
data_indices = dask.array.arange(data.size).reshape(data.shape).rechunk(data.chunks)
|
|
627
|
+
|
|
628
|
+
# first check each chunk to find out if any failed the check
|
|
629
|
+
# for stencil safeguards, one chunk failing requires all to be corrected
|
|
630
|
+
# (since incremental corrections could spread)
|
|
631
|
+
# if no chunk check failed, the chunked correction can take a fast path
|
|
632
|
+
all_chunk_checks_succeeded = (
|
|
633
|
+
check_chunks_first
|
|
634
|
+
and dask.array.map_overlap(
|
|
635
|
+
_check_overlapping_stencil_chunk,
|
|
636
|
+
data.data,
|
|
637
|
+
approximation.data,
|
|
638
|
+
data_indices,
|
|
639
|
+
*chunked_late_bound.values(),
|
|
640
|
+
dtype=np.bool,
|
|
641
|
+
# we cannot output 1x...x1 chunks here since we later use the block
|
|
642
|
+
# info to compute the data size and chunk location
|
|
643
|
+
# map_blocks figures out the chunks
|
|
644
|
+
chunks=None,
|
|
645
|
+
enforce_ndim=True,
|
|
646
|
+
meta=np.array((), dtype=np.bool),
|
|
647
|
+
depth=depth,
|
|
648
|
+
boundary=boundary,
|
|
649
|
+
trim=False,
|
|
650
|
+
align_arrays=False,
|
|
651
|
+
# if the stencil is larger than the smallest chunk,
|
|
652
|
+
# temporary rechunking may be necessary
|
|
653
|
+
allow_rechunk=True,
|
|
654
|
+
late_bound_names=tuple(chunked_late_bound.keys()),
|
|
655
|
+
late_bound_global=late_bound_global,
|
|
656
|
+
safeguards=safeguards_,
|
|
657
|
+
data_shape=data.shape,
|
|
658
|
+
depth_=depth,
|
|
659
|
+
boundary_=boundary,
|
|
660
|
+
)
|
|
661
|
+
.all()
|
|
662
|
+
.compute()
|
|
663
|
+
)
|
|
664
|
+
any_chunk_check_failed = not all_chunk_checks_succeeded
|
|
665
|
+
|
|
666
|
+
def _compute_overlapping_stencil_chunk_correction(
|
|
667
|
+
data_chunk: np.ndarray[S, np.dtype[T]],
|
|
668
|
+
approximation_chunk: np.ndarray[S, np.dtype[T]],
|
|
669
|
+
data_indices_chunk: np.ndarray[S, np.dtype[np.intp]],
|
|
670
|
+
*late_bound_chunks: np.ndarray[S, np.dtype[T]],
|
|
671
|
+
late_bound_names: tuple[str, ...],
|
|
672
|
+
late_bound_global: dict[str, int | float | np.number],
|
|
673
|
+
safeguards: Safeguards,
|
|
674
|
+
data_shape: tuple[int, ...],
|
|
675
|
+
depth_: tuple[int | tuple[int, int], ...],
|
|
676
|
+
boundary_: Literal["none", "periodic"],
|
|
677
|
+
any_chunk_check_failed: bool,
|
|
678
|
+
block_info=None,
|
|
679
|
+
) -> np.ndarray[tuple[int, ...], np.dtype[np.unsignedinteger]]:
|
|
680
|
+
assert block_info is not None, "missing block info"
|
|
681
|
+
assert len(late_bound_chunks) == len(late_bound_names), (
|
|
682
|
+
"late-bound chunks and names mismatch"
|
|
683
|
+
)
|
|
684
|
+
assert len(depth_) == data_chunk.ndim, "overlap depth length mismatch"
|
|
685
|
+
|
|
686
|
+
# ensure that we pass np.ndarray's to the compression-safeguards
|
|
687
|
+
data_chunk = _ensure_array(data_chunk)
|
|
688
|
+
approximation_chunk = _ensure_array(approximation_chunk)
|
|
689
|
+
data_indices_chunk = _ensure_array(data_indices_chunk)
|
|
690
|
+
late_bound_chunks = tuple(_ensure_array(lb) for lb in late_bound_chunks)
|
|
691
|
+
|
|
692
|
+
late_bound_chunk: dict[str, Value] = dict(
|
|
693
|
+
**late_bound_global,
|
|
694
|
+
**{p: v for p, v in zip(late_bound_names, late_bound_chunks)},
|
|
695
|
+
)
|
|
696
|
+
|
|
697
|
+
depth: tuple[tuple[int, int], ...] = tuple(
|
|
698
|
+
(d, d) if isinstance(d, int) else d for d in depth_
|
|
699
|
+
)
|
|
700
|
+
|
|
701
|
+
match boundary_:
|
|
702
|
+
case "none":
|
|
703
|
+
# map_overlap passes the wrong block_info,
|
|
704
|
+
# see https://github.com/dask/dask/issues/11349
|
|
705
|
+
# so we only trust it just enough to compute the effective
|
|
706
|
+
# stencil size
|
|
707
|
+
extended_data_shape: tuple[int, ...] = tuple(block_info[None]["shape"])
|
|
708
|
+
extended_chunk_location: tuple[tuple[int, int], ...] = tuple(
|
|
709
|
+
block_info[None]["array-location"]
|
|
710
|
+
)
|
|
711
|
+
|
|
712
|
+
# the none boundary does not extend beyond the data boundary,
|
|
713
|
+
# so we need to check by how much the stencil was cut off
|
|
714
|
+
chunk_stencil: tuple[
|
|
715
|
+
tuple[
|
|
716
|
+
Literal[BoundaryCondition.valid, BoundaryCondition.wrap],
|
|
717
|
+
NeighbourhoodAxis,
|
|
718
|
+
],
|
|
719
|
+
...,
|
|
720
|
+
] = tuple(
|
|
721
|
+
(
|
|
722
|
+
BoundaryCondition.valid,
|
|
723
|
+
NeighbourhoodAxis(
|
|
724
|
+
before=s - max(0, s - b), after=min(e + a, d) - e
|
|
725
|
+
),
|
|
726
|
+
)
|
|
727
|
+
for (b, a), (s, e), d in zip(
|
|
728
|
+
depth, extended_chunk_location, extended_data_shape
|
|
729
|
+
)
|
|
730
|
+
)
|
|
731
|
+
case "periodic":
|
|
732
|
+
# the periodic boundary guarantees that we always have the
|
|
733
|
+
# stencil we asked for
|
|
734
|
+
chunk_stencil = tuple(
|
|
735
|
+
(BoundaryCondition.wrap, NeighbourhoodAxis(before=b, after=a))
|
|
736
|
+
for b, a in depth
|
|
737
|
+
)
|
|
738
|
+
case _:
|
|
739
|
+
assert_never(boundary_)
|
|
740
|
+
|
|
741
|
+
# extract the indices of the non-stencil-extended data indices chunk
|
|
742
|
+
data_indices_chunk_: np.ndarray[tuple[int, ...], np.dtype[np.intp]] = (
|
|
743
|
+
data_indices_chunk[
|
|
744
|
+
tuple(
|
|
745
|
+
slice(a.before, None if a.after == 0 else -a.after)
|
|
746
|
+
for b, a in chunk_stencil
|
|
747
|
+
)
|
|
748
|
+
]
|
|
749
|
+
)
|
|
750
|
+
chunk_shape = data_indices_chunk_.shape
|
|
751
|
+
|
|
752
|
+
# extract the offset of the chunk from the data indices chunk
|
|
753
|
+
if data_indices_chunk_.size > 0:
|
|
754
|
+
chunk_offset_index = int(data_indices_chunk_.flatten()[0])
|
|
755
|
+
chunk_offset_: list[int] = []
|
|
756
|
+
for s in data_shape[::-1]:
|
|
757
|
+
chunk_offset_.append(chunk_offset_index % s)
|
|
758
|
+
chunk_offset_index //= s
|
|
759
|
+
chunk_offset: tuple[int, ...] = tuple(chunk_offset_[::-1])
|
|
760
|
+
else:
|
|
761
|
+
chunk_offset = tuple(0 for _ in data_shape)
|
|
762
|
+
|
|
763
|
+
# this is safe because
|
|
764
|
+
# - map_overlap ensures we get chunks including their required stencil
|
|
765
|
+
# - compute_chunked_correction only returns the correction for the non-
|
|
766
|
+
# overlapping non-stencil parts of the chunk
|
|
767
|
+
correction: np.ndarray[tuple[int, ...], np.dtype[np.unsignedinteger]] = (
|
|
768
|
+
safeguards.compute_chunked_correction(
|
|
769
|
+
data_chunk,
|
|
770
|
+
approximation_chunk,
|
|
771
|
+
data_shape=data_shape,
|
|
772
|
+
chunk_offset=chunk_offset,
|
|
773
|
+
chunk_stencil=chunk_stencil,
|
|
774
|
+
any_chunk_check_failed=any_chunk_check_failed,
|
|
775
|
+
late_bound_chunk=late_bound_chunk,
|
|
776
|
+
where_chunk=True,
|
|
777
|
+
)
|
|
778
|
+
)
|
|
779
|
+
assert correction.shape == chunk_shape, "invalid correction chunk shape"
|
|
780
|
+
|
|
781
|
+
return correction
|
|
782
|
+
|
|
783
|
+
da_correction = (
|
|
784
|
+
data.copy(
|
|
785
|
+
data=dask.array.map_overlap(
|
|
786
|
+
_compute_overlapping_stencil_chunk_correction,
|
|
787
|
+
data.data,
|
|
788
|
+
approximation.data,
|
|
789
|
+
data_indices,
|
|
790
|
+
*chunked_late_bound.values(),
|
|
791
|
+
dtype=correction_dtype,
|
|
792
|
+
# we explicitly exclude `chunks=None` here since map_overlap only
|
|
793
|
+
# figures out the correct chunks if `chunks` is not in the kwargs
|
|
794
|
+
enforce_ndim=True,
|
|
795
|
+
meta=np.array((), dtype=correction_dtype),
|
|
796
|
+
depth=depth,
|
|
797
|
+
boundary=boundary,
|
|
798
|
+
trim=False,
|
|
799
|
+
align_arrays=False,
|
|
800
|
+
# if the stencil is larger than the smallest chunk,
|
|
801
|
+
# temporary rechunking may be necessary
|
|
802
|
+
allow_rechunk=True,
|
|
803
|
+
late_bound_names=tuple(chunked_late_bound.keys()),
|
|
804
|
+
late_bound_global=late_bound_global,
|
|
805
|
+
safeguards=safeguards_,
|
|
806
|
+
data_shape=data.shape,
|
|
807
|
+
depth_=depth,
|
|
808
|
+
boundary_=boundary,
|
|
809
|
+
any_chunk_check_failed=any_chunk_check_failed,
|
|
810
|
+
).rechunk(data.chunks) # undo temporary rechunking
|
|
811
|
+
)
|
|
812
|
+
.rename(correction_name)
|
|
813
|
+
.assign_attrs(**correction_attrs)
|
|
814
|
+
)
|
|
815
|
+
|
|
816
|
+
# drop the previous encoding from the variable but not the coords
|
|
817
|
+
return da_correction._replace(variable=da_correction.variable.drop_encoding())
|
|
818
|
+
|
|
819
|
+
|
|
820
|
+
def apply_data_array_correction(
|
|
821
|
+
approximation: xr.DataArray,
|
|
822
|
+
correction: xr.DataArray,
|
|
823
|
+
) -> xr.DataArray:
|
|
824
|
+
"""
|
|
825
|
+
Apply the `correction` to the `approximation` array to satisfy the safeguards for which the `correction` was produced.
|
|
826
|
+
|
|
827
|
+
The `approximation` must be bitwise equivalent to the `approximation` that
|
|
828
|
+
was used to produce the `correction`.
|
|
829
|
+
|
|
830
|
+
The `approximation` array may be chunked[^2] and the `correction` array must
|
|
831
|
+
use the same chunking, though this chunking may differ from the one that
|
|
832
|
+
was used to produce the `correction`.
|
|
833
|
+
|
|
834
|
+
If the the `approximation` array is chunked, the correction is applied lazily,
|
|
835
|
+
otherwise it its application is computed eagerly.
|
|
836
|
+
|
|
837
|
+
[^2]: Any chunking supported by `xarray` is supported, including but not
|
|
838
|
+
limited to `dask`, please see
|
|
839
|
+
<https://docs.xarray.dev/en/stable/internals/chunked-arrays.html>.
|
|
840
|
+
|
|
841
|
+
Parameters
|
|
842
|
+
----------
|
|
843
|
+
approximation : xr.DataArray
|
|
844
|
+
The approximation array for which the correction has been produced.
|
|
845
|
+
correction : xr.DataArray
|
|
846
|
+
The correction array.
|
|
847
|
+
|
|
848
|
+
Returns
|
|
849
|
+
-------
|
|
850
|
+
corrected : xr.DataArray
|
|
851
|
+
The corrected array, which satisfies the safeguards.
|
|
852
|
+
|
|
853
|
+
Raises
|
|
854
|
+
------
|
|
855
|
+
ValueError
|
|
856
|
+
if the `correction`'s dimensions, shape, or chunks do not match the
|
|
857
|
+
`approximation`'s, or if the `correction`'s dtype does not match the
|
|
858
|
+
correction dtype for the `approximation`'s dtype.
|
|
859
|
+
ValueError
|
|
860
|
+
if the `correction` does not contain metadata about the safeguards that
|
|
861
|
+
it was produced with.
|
|
862
|
+
...
|
|
863
|
+
if re-instantiating the safeguards from their configuration metadata
|
|
864
|
+
raises an exception.
|
|
865
|
+
"""
|
|
866
|
+
|
|
867
|
+
with ctx.parameter("correction"):
|
|
868
|
+
if correction.dims != approximation.dims:
|
|
869
|
+
raise ValueError("correction.dims must match approximation.dims") | ctx
|
|
870
|
+
if correction.shape != approximation.shape:
|
|
871
|
+
raise ValueError("correction.shape must match approximation.shape") | ctx
|
|
872
|
+
if correction.chunks != approximation.chunks:
|
|
873
|
+
raise ValueError("correction.chunks must match approximation.chunks") | ctx
|
|
874
|
+
|
|
875
|
+
if "safeguards" not in correction.attrs:
|
|
876
|
+
raise (
|
|
877
|
+
ValueError(
|
|
878
|
+
"correction must contain metadata about the safeguards "
|
|
879
|
+
+ "that it was produced with"
|
|
880
|
+
)
|
|
881
|
+
| ctx
|
|
882
|
+
)
|
|
883
|
+
safeguards = Safeguards.from_config(json.loads(correction.attrs["safeguards"]))
|
|
884
|
+
|
|
885
|
+
with ctx.parameter("correction"):
|
|
886
|
+
if correction.dtype != safeguards.correction_dtype_for_data(
|
|
887
|
+
approximation.dtype
|
|
888
|
+
):
|
|
889
|
+
raise (
|
|
890
|
+
ValueError(
|
|
891
|
+
"correction.dtype must match the correction dtype for "
|
|
892
|
+
+ "approximation.dtype"
|
|
893
|
+
)
|
|
894
|
+
| ctx
|
|
895
|
+
)
|
|
896
|
+
|
|
897
|
+
if approximation.chunks is None:
|
|
898
|
+
return approximation.copy(
|
|
899
|
+
data=safeguards.apply_correction(approximation.data, correction.data)
|
|
900
|
+
).assign_attrs(safeguards=correction.attrs["safeguards"])
|
|
901
|
+
|
|
902
|
+
with ctx.parameter("correction"):
|
|
903
|
+
chunkmanager = get_chunked_array_type(approximation.data, correction.data)
|
|
904
|
+
|
|
905
|
+
def _apply_independent_chunk_correction(
|
|
906
|
+
approximation_chunk: np.ndarray[S, np.dtype[T]],
|
|
907
|
+
correction_chunk: np.ndarray[S, np.dtype[np.unsignedinteger]],
|
|
908
|
+
safeguards: Safeguards,
|
|
909
|
+
) -> np.ndarray[S, np.dtype[T]]:
|
|
910
|
+
# ensure that we pass np.ndarray's to the compression-safeguards
|
|
911
|
+
approximation_chunk = _ensure_array(approximation_chunk)
|
|
912
|
+
correction_chunk = _ensure_array(correction_chunk)
|
|
913
|
+
|
|
914
|
+
return safeguards.apply_correction(approximation_chunk, correction_chunk)
|
|
915
|
+
|
|
916
|
+
return approximation.copy(
|
|
917
|
+
data=chunkmanager.map_blocks(
|
|
918
|
+
_apply_independent_chunk_correction,
|
|
919
|
+
approximation.data,
|
|
920
|
+
correction.data,
|
|
921
|
+
dtype=approximation.dtype,
|
|
922
|
+
chunks=None, # map_blocks figures out the chunks
|
|
923
|
+
drop_axis=None,
|
|
924
|
+
new_axis=None,
|
|
925
|
+
safeguards=safeguards,
|
|
926
|
+
)
|
|
927
|
+
).assign_attrs(safeguards=correction.attrs["safeguards"])
|
|
928
|
+
|
|
929
|
+
|
|
930
|
+
@xr.register_dataset_accessor("safeguarded")
|
|
931
|
+
class DatasetSafeguardedAccessor:
|
|
932
|
+
"""
|
|
933
|
+
An extension for an [`xarray.Dataset`][xarray.Dataset] that provides the
|
|
934
|
+
`.safeguarded` property that applies safeguards corrections in the dataset
|
|
935
|
+
to their respective variables.
|
|
936
|
+
|
|
937
|
+
The safeguarded variables must be bitwise equivalent to the variables
|
|
938
|
+
for which their corrections were originally produced.
|
|
939
|
+
|
|
940
|
+
For instance, for a dataset `ds` that contains both a variable `ds.foo` and
|
|
941
|
+
its correction, you can access the corrected variable using
|
|
942
|
+
`ds.safeguarded.foo`.
|
|
943
|
+
|
|
944
|
+
Raises
|
|
945
|
+
------
|
|
946
|
+
AttributeError
|
|
947
|
+
if the dataset does not contain not-yet-applied safeguards corrections.
|
|
948
|
+
RuntimeError
|
|
949
|
+
if the attributes of the safeguards correction are invalid.
|
|
950
|
+
ValueError
|
|
951
|
+
if applying a safeguards correction raises an exception.
|
|
952
|
+
...
|
|
953
|
+
if re-instantiating the safeguards from their configuration metadata
|
|
954
|
+
raises an exception.
|
|
955
|
+
"""
|
|
956
|
+
|
|
957
|
+
__slots__: tuple[str, ...] = ()
|
|
958
|
+
|
|
959
|
+
def __new__(cls, ds: xr.Dataset) -> xr.Dataset: # type: ignore
|
|
960
|
+
corrected: dict[str, xr.DataArray] = dict()
|
|
961
|
+
|
|
962
|
+
for vn, v in ds.data_vars.items():
|
|
963
|
+
if "safeguarded" in v.attrs:
|
|
964
|
+
kp = v.attrs["safeguarded"]
|
|
965
|
+
with ctx.parameter(repr(vn)):
|
|
966
|
+
if kp is None:
|
|
967
|
+
raise (
|
|
968
|
+
RuntimeError(
|
|
969
|
+
"data variable is a safeguards correction but "
|
|
970
|
+
+ "its `safeguarded` attribute must not be None"
|
|
971
|
+
)
|
|
972
|
+
| ctx
|
|
973
|
+
)
|
|
974
|
+
if kp not in ds.data_vars:
|
|
975
|
+
raise (
|
|
976
|
+
RuntimeError(
|
|
977
|
+
"data variable is a safeguards correction for "
|
|
978
|
+
+ f"{kp!r} but there is no variable of that "
|
|
979
|
+
+ "name"
|
|
980
|
+
)
|
|
981
|
+
| ctx
|
|
982
|
+
)
|
|
983
|
+
if "safeguards" not in v.attrs:
|
|
984
|
+
raise (
|
|
985
|
+
RuntimeError(
|
|
986
|
+
"data variable is missing the `safeguards` "
|
|
987
|
+
+ "attribute"
|
|
988
|
+
)
|
|
989
|
+
| ctx
|
|
990
|
+
)
|
|
991
|
+
|
|
992
|
+
corrected[kp] = apply_data_array_correction(ds.data_vars[kp], v)
|
|
993
|
+
|
|
994
|
+
if len(corrected) == 0:
|
|
995
|
+
raise (
|
|
996
|
+
AttributeError(
|
|
997
|
+
"not a dataset with not-yet-applied safeguards corrections"
|
|
998
|
+
)
|
|
999
|
+
| ctx
|
|
1000
|
+
)
|
|
1001
|
+
|
|
1002
|
+
return xr.Dataset(corrected, attrs=ds.attrs)
|
|
1003
|
+
|
|
1004
|
+
|
|
1005
|
+
@xr.register_dataarray_accessor("safeguards")
|
|
1006
|
+
class DataArraySafeguardsAccessor:
|
|
1007
|
+
"""
|
|
1008
|
+
An extension for an [`xarray.DataArray`][xarray.DataArray] that provides
|
|
1009
|
+
the `.safeguards` property that exposes the collection of
|
|
1010
|
+
[`Safeguard`][compression_safeguards.safeguards.abc.Safeguard]s for
|
|
1011
|
+
a safeguards correction or corrected array.
|
|
1012
|
+
|
|
1013
|
+
Raises
|
|
1014
|
+
------
|
|
1015
|
+
AttributeError
|
|
1016
|
+
if the data array does not have associated safeguards.
|
|
1017
|
+
...
|
|
1018
|
+
if re-instantiating the safeguards from their configuration metadata
|
|
1019
|
+
raises an exception.
|
|
1020
|
+
"""
|
|
1021
|
+
|
|
1022
|
+
__slots__: tuple[str, ...] = ()
|
|
1023
|
+
|
|
1024
|
+
def __new__(cls, da: xr.DataArray) -> Collection[Safeguard]: # type: ignore
|
|
1025
|
+
if "safeguards" not in da.attrs:
|
|
1026
|
+
raise AttributeError("not a data array with safeguards") | ctx
|
|
1027
|
+
return Safeguards.from_config(json.loads(da.attrs["safeguards"])).safeguards
|