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