numcodecs-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,855 @@
1
+ r"""
2
+ # Safe, Trusted, and Fearless lossy compression with `numcodecs-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 the [`SafeguardedCodec`][.SafeguardedCodec] adapter /
14
+ meta-compressor that can be wrapped around *any* existing (lossy)
15
+ [`numcodecs.abc.Codec`][numcodecs.abc.Codec] to *guarantee* that certain
16
+ properties of the original data are preserved by compression.
17
+
18
+ The `SafeguardedCodec` treats the wrapped inner codec as a blackbox. To
19
+ guarantee the user's safety requirements, it post-processes the decompressed
20
+ data, if necessary. If no correction is needed, the `SafeguardedCodec` only has
21
+ a three-byte overhead for the compressed data and a computational overhead at
22
+ compression time (at decompression time, only the checksum is verified).
23
+
24
+ By using the `SafeguardedCodec` adapter, badly behaving lossy codecs become safe
25
+ to use, at the cost of potentially less efficient compression, and lossy
26
+ compression can be applied *without fear*.
27
+
28
+ The `SafeguardedCodec` must only be used to encode the complete data, i.e. not
29
+ just a chunk of data, so that non-pointwise safeguards are correctly applied.
30
+ Please refer to the [`xarray-safeguards`][xarray_safeguards] frontend for
31
+ applying safeguards to chunked data.
32
+
33
+ ## Example
34
+
35
+ You can wrap an existing codec with e.g. a relative error bound of
36
+ $eb_{rel} = 1\%$ and preserve data signs as follows:
37
+
38
+ ```py
39
+ import numpy as np
40
+ from numcodecs.fixedscaleoffset import FixedScaleOffset
41
+ from numcodecs_safeguards import SafeguardedCodec
42
+
43
+ # use any numcodecs-compatible codec
44
+ # here we quantize data >= -10 with one decimal digit
45
+ lossy_codec = FixedScaleOffset(
46
+ offset=-10, scale=10, dtype="float64", astype="uint8",
47
+ )
48
+
49
+ # wrap the codec in the `SafeguardedCodec` and specify the safeguards to apply
50
+ sg_codec = SafeguardedCodec(codec=lossy_codec, safeguards=[
51
+ # guarantee a relative error bound of 1%:
52
+ # |x - x'| <= |x| * 0.01
53
+ dict(kind="eb", type="rel", eb=0.01),
54
+ # guarantee that the sign is preserved:
55
+ # sign(x) = sign(x')
56
+ dict(kind="sign"),
57
+ ])
58
+
59
+ # some n-dimensional data
60
+ data = np.linspace(-10, 10, 21)
61
+
62
+ # encode and decode the data
63
+ encoded = sg_codec.encode(data)
64
+ decoded = sg_codec.decode(encoded)
65
+
66
+ # the safeguard properties are guaranteed to hold
67
+ assert np.all(np.abs(data - decoded) <= np.abs(data) * 0.01)
68
+ assert np.all(np.sign(data) == np.sign(decoded))
69
+ ```
70
+
71
+ Please refer to the
72
+ [`compression_safeguards.SafeguardKind`][compression_safeguards.safeguards.SafeguardKind]
73
+ for an enumeration of all supported safeguards.
74
+ """
75
+
76
+ __all__ = ["SafeguardedCodec"]
77
+
78
+ from collections.abc import Callable, Collection, Mapping, Set
79
+ from io import BytesIO
80
+ from typing import ClassVar, Self
81
+
82
+ import leb128
83
+ import numcodecs
84
+ import numcodecs.compat
85
+ import numcodecs.registry
86
+ import numcodecs_combinators
87
+ import numpy as np
88
+ from compression_safeguards.api import Safeguards
89
+ from compression_safeguards.safeguards.abc import Safeguard
90
+ from compression_safeguards.safeguards.pointwise.lossless import LosslessSafeguard
91
+ from compression_safeguards.utils.bindings import Bindings, Parameter, Value
92
+ from compression_safeguards.utils.cast import as_bits
93
+ from compression_safeguards.utils.error import (
94
+ LateBoundParameterResolutionError,
95
+ TypeSetError,
96
+ ctx,
97
+ )
98
+ from compression_safeguards.utils.typing import JSON
99
+ from numcodecs.abc import Codec
100
+ from numcodecs_combinators.abc import CodecCombinatorMixin
101
+ from semver.version import Version
102
+ from typing_extensions import (
103
+ Buffer, # MSPV 3.12
104
+ override, # MSPV 3.12
105
+ )
106
+
107
+ from .checksum import checksum
108
+ from .compute import Compute, _refine_correction_iteratively
109
+ from .lossless import Lossless
110
+
111
+
112
+ class SafeguardedCodec(Codec, CodecCombinatorMixin):
113
+ """
114
+ An adaptor codec that uses
115
+ [`Safeguards`][compression_safeguards.api.Safeguards] to guarantee certain
116
+ properties / safety requirements are upheld by the wrapped codec.
117
+
118
+ Parameters
119
+ ----------
120
+ codec : dict[str, JSON] | Codec
121
+ The codec that will be wrapped with safeguards. It can either be passed
122
+ as a codec configuration [`dict`][dict], which is passed to
123
+ [`numcodecs.registry.get_codec(config)`][numcodecs.registry.get_codec],
124
+ or an already initialized [`Codec`][numcodecs.abc.Codec]. If you want to
125
+ wrap a sequence or stack of codecs, you can use the
126
+ [`numcodecs_combinators.stack.CodecStack`][numcodecs_combinators.stack.CodecStack]
127
+ combinator, e.g. to first replace codec-unsupported values with the
128
+ [`numcodecs_replace.ReplaceFilterCodec`][numcodecs_replace.ReplaceFilterCodec]
129
+ and later restore them using the
130
+ [`EquivalentValueSafeguard`][compression_safeguards.safeguards.pointwise.same.EquivalentValueSafeguard].
131
+
132
+ The codec must be deterministic during decoding (but can be
133
+ non-deterministic during encoding) such that decoding the same bytes
134
+ always produces the same bitwise equivalent decoded result.
135
+
136
+ It is desirable to perform lossless compression after applying the
137
+ safeguards (rather than before), e.g. by customising the
138
+ [`Lossless.for_codec`][..lossless.Lossless.for_codec] field of the
139
+ `lossless` parameter.
140
+
141
+ The `codec` combined with its `lossless` encoding must encode to a 1D
142
+ buffer of bytes. It is also recommended that the `codec` can
143
+ [`decode`][numcodecs.abc.Codec.decode]
144
+ without receiving the output data type and shape via the `out`
145
+ parameter. If the `codec` does not fulfil these requirements, it can be
146
+ wrapped inside the
147
+ [`numcodecs_combinators.framed.FramedCodecStack`][numcodecs_combinators.framed.FramedCodecStack]
148
+ combinator.
149
+
150
+ It is also possible to compress the data with *just* the safeguards
151
+ (i.e. without a `codec` that provides proper lossy compression) by
152
+ passing [`numcodecs_zero.ZeroCodec()`][numcodecs_zero.ZeroCodec] or
153
+ `dict(id="zero")` to `codec`. The zero codec only encodes the data
154
+ type and shape, not the data values themselves, and decodes to all-
155
+ zero values, forcing the safeguards to correct (almost) all values.
156
+ With this configuration, the safeguards thus act as a safe lossy
157
+ compressor in their own right, as any size reduction comes from the
158
+ `lossless` compression of the safeguards corrections (which the
159
+ safeguards produce to be highly-compressible, if possible).
160
+ safeguards : Collection[dict[str, JSON] | Safeguard]
161
+ The safeguards that will be applied to the codec. They can either be
162
+ passed as a safeguard configuration [`dict`][dict] or an already
163
+ initialized
164
+ [`Safeguard`][compression_safeguards.safeguards.abc.Safeguard].
165
+
166
+ Please refer to the
167
+ [`SafeguardKind`][compression_safeguards.safeguards.SafeguardKind]
168
+ for an enumeration of all supported safeguards.
169
+
170
+ The `SafeguardedCodec` supports safeguards with late-bound parameters,
171
+ e.g. the
172
+ [`SelectSafeguard`][compression_safeguards.safeguards.combinators.select.SelectSafeguard],
173
+ but they must be provided as `fixed_constants` that are *fixed* and
174
+ must be compatible with *any* data that will be encoded with this
175
+ codec. Therefore, fixed constants should only be used for late-bound
176
+ parameters that can be fixed across all uses of the codec.
177
+ fixed_constants : Mapping[str | Parameter, Value] | Bindings
178
+ Mapping of parameter names to *fixed* constant scalars or arrays that
179
+ will be provided as late-bound parameters to the safeguards.
180
+
181
+ The mapping must resolve all late-bound parameters of the safeguards
182
+ and include no extraneous parameters.
183
+
184
+ The provided values must have a compatible shape and values for *any*
185
+ data that will be encoded with this codec, otherwise
186
+ [`encode`][.encode] will fail.
187
+
188
+ You can use the [`update_fixed_constants`][.update_fixed_constants]
189
+ method inside a `with` statement to temporarily update the late-bound
190
+ parameters.
191
+
192
+ The fixed constants are included in the [config][.get_config] of the
193
+ codec. While [`int`][int] and [`float`][float] scalars are included
194
+ as-is, numpy scalars and arrays are encoded to the losslessly
195
+ compressed [`.npz`][numpy.savez_compressed] format and stored in a
196
+ `data:application/x-npz;base64,<data>`
197
+ [data URI](https://developer.mozilla.org/en-US/docs/Web/URI/Reference/Schemes/data).
198
+ lossless : None | dict[str, JSON] | Lossless, optional
199
+ The lossless encoding that is applied after the codec and the
200
+ safeguards:
201
+
202
+ - [`Lossless.for_codec`][..lossless.Lossless.for_codec] specifies the
203
+ lossless encoding that is applied to the encoded output of the
204
+ wrapped `codec`. By default, no additional lossless encoding is
205
+ applied.
206
+ - [`Lossless.for_corrections`][..lossless.Lossless.for_corrections]
207
+ specifies the lossless encoding that is applied to the corrections
208
+ that the safeguards produce. By default, Zstandard compression is
209
+ applied after entropy coding.
210
+
211
+ The lossless encoding must encode to a 1D buffer of bytes.
212
+ compute : None | dict[str, JSON] | Compute, optional
213
+ Compute configuration with options that may affect the compression
214
+ ratio and time cost of computing the safeguards corrections.
215
+
216
+ While these options can change the particular corrections that are
217
+ produced, the resulting corrections always satisfy the safety
218
+ requirements.
219
+ _version : ...
220
+ The version of the codec. Do not provide this parameter explicitly.
221
+
222
+ Raises
223
+ ------
224
+ ValueError
225
+ if `codec` wraps another `SafeguardedCodec`, which may create a printer
226
+ problem.
227
+ LateBoundParameterResolutionError
228
+ if `fixed_constants` does not resolve all late-bound parameters of the
229
+ safeguards or includes any extraneous parameters.
230
+ ...
231
+ if instantiating the `codec` or a safeguard raises an exception.
232
+ """
233
+
234
+ __slots__: tuple[str, ...] = (
235
+ "_codec",
236
+ "_safeguards",
237
+ "_late_bound",
238
+ "_lossless_for_codec",
239
+ "_lossless_for_corrections",
240
+ "_compute",
241
+ )
242
+ _codec: Codec
243
+ _safeguards: Safeguards
244
+ _late_bound: Bindings
245
+ _lossless_for_codec: None | Codec
246
+ _lossless_for_corrections: Codec
247
+ _compute: Compute
248
+
249
+ codec_id: ClassVar[str] = "safeguards" # type: ignore
250
+
251
+ def __init__(
252
+ self,
253
+ *,
254
+ codec: dict[str, JSON] | Codec,
255
+ safeguards: Collection[dict[str, JSON] | Safeguard],
256
+ fixed_constants: Mapping[str | Parameter, Value] | Bindings = Bindings.EMPTY,
257
+ lossless: None | dict[str, JSON] | Lossless = None,
258
+ compute: None | dict[str, JSON] = None,
259
+ _version: None | str | Version = None,
260
+ ) -> None:
261
+ wraps_safeguards_codec = False
262
+
263
+ def check_for_safeguards_codec(codec: Codec) -> Codec:
264
+ nonlocal wraps_safeguards_codec
265
+ wraps_safeguards_codec |= isinstance(codec, SafeguardedCodec)
266
+ return codec
267
+
268
+ self._codec = (
269
+ codec if isinstance(codec, Codec) else numcodecs.registry.get_codec(codec)
270
+ )
271
+
272
+ numcodecs_combinators.map_codec(self._codec, check_for_safeguards_codec)
273
+
274
+ if wraps_safeguards_codec:
275
+ with ctx.parameter("codec"):
276
+ raise (
277
+ ValueError(
278
+ "`SafeguardedCodec` should not wrap a codec containing "
279
+ + "another `SafeguardedCodec` since the safeguards of one "
280
+ + "might not be upheld by the other (printer problem); "
281
+ + "merge them into one combined `SafeguardedCodec` instead"
282
+ )
283
+ | ctx
284
+ )
285
+
286
+ self._safeguards = Safeguards(safeguards=safeguards, _version=_version)
287
+
288
+ self._late_bound = (
289
+ fixed_constants
290
+ if isinstance(fixed_constants, Bindings)
291
+ else Bindings(**fixed_constants)
292
+ )
293
+
294
+ late_bound_reqs = frozenset(self.late_bound - self.builtin_late_bound)
295
+ late_bound_keys = frozenset(self._late_bound.parameters())
296
+
297
+ LateBoundParameterResolutionError.check_or_raise(
298
+ late_bound_reqs, late_bound_keys
299
+ )
300
+
301
+ lossless = (
302
+ lossless
303
+ if isinstance(lossless, Lossless)
304
+ else Lossless(**lossless) # type: ignore
305
+ if lossless is not None
306
+ else Lossless()
307
+ )
308
+ self._lossless_for_codec = (
309
+ lossless.for_codec
310
+ if isinstance(lossless.for_codec, Codec)
311
+ else numcodecs.registry.get_codec(lossless.for_codec)
312
+ if lossless.for_codec is not None
313
+ else None
314
+ )
315
+ self._lossless_for_corrections = (
316
+ lossless.for_corrections
317
+ if isinstance(lossless.for_corrections, Codec)
318
+ else numcodecs.registry.get_codec(lossless.for_corrections)
319
+ )
320
+
321
+ self._compute = (
322
+ compute
323
+ if isinstance(compute, Compute)
324
+ else Compute.from_config(compute)
325
+ if compute is not None
326
+ else Compute()
327
+ )
328
+
329
+ @property
330
+ def codec(self) -> Codec:
331
+ """
332
+ The inner (unsafeguarded) codec.
333
+ """
334
+
335
+ return self._codec
336
+
337
+ @property
338
+ def safeguards(self) -> Collection[Safeguard]:
339
+ """
340
+ The collection of safeguards that will be applied.
341
+ """
342
+
343
+ return self._safeguards.safeguards
344
+
345
+ @property
346
+ def late_bound(self) -> Set[Parameter]:
347
+ """
348
+ The set of late-bound parameters that the safeguards have.
349
+
350
+ The late-bound parameters must be provided as fixed constants. They
351
+ must have a compatible shape and values for any data that will be
352
+ encoded with this codec, otherwise [`encode`][..encode] will fail.
353
+ """
354
+
355
+ return self._safeguards.late_bound
356
+
357
+ @property
358
+ def builtin_late_bound(self) -> Set[Parameter]:
359
+ """
360
+ The set of built-in late-bound constants that the numcodecs-safeguards
361
+ provide automatically, which include the safeguards' built-ins as well
362
+ as the (finite) non-NaN global minimum/maximum `$x_min`, `$x_max`,
363
+ `$x_finite_min`, and `$x_finite_max`.
364
+ """
365
+
366
+ return frozenset(self._safeguards.builtin_late_bound) | frozenset(
367
+ [
368
+ Parameter("$x_min"),
369
+ Parameter("$x_max"),
370
+ Parameter("$x_finite_min"),
371
+ Parameter("$x_finite_max"),
372
+ ]
373
+ )
374
+
375
+ def update_fixed_constants(self, **kwargs: Value) -> "SafeguardedCodec":
376
+ """
377
+ Create a new safeguarded codec, where the old fixed constants have been
378
+ overridden by new ones from `**kwargs`.
379
+
380
+ Only existing late-bound constants may be overridden and no new ones
381
+ may be added.
382
+
383
+ The provided values must have a compatible shape and values for *any*
384
+ data that will be encoded with this codec, otherwise
385
+ [`encode`][..encode] will fail.
386
+
387
+ This method can be used inside a `with` statement to temporarily update
388
+ the late-bound parameters.
389
+
390
+ Parameters
391
+ ----------
392
+ **kwargs : Value
393
+ Mapping from new parameters to values as keyword arguments.
394
+
395
+ Returns
396
+ -------
397
+ safeguards : SafeguardedCodec
398
+ The safeguarded codec, with the updated fixed constants.
399
+ """
400
+
401
+ return SafeguardedCodec(
402
+ codec=self._codec,
403
+ safeguards=self._safeguards.safeguards,
404
+ fixed_constants=self._late_bound.update(**kwargs),
405
+ lossless=Lossless(
406
+ for_codec=None
407
+ if self._lossless_for_codec is None
408
+ else self._lossless_for_codec,
409
+ for_corrections=self._lossless_for_corrections,
410
+ ),
411
+ _version=self._safeguards.version,
412
+ )
413
+
414
+ @override
415
+ def encode(self, buf: Buffer) -> bytes:
416
+ """
417
+ Encode the data in `buf` while safeguarding the compression.
418
+
419
+ The encoded data is defined by the following *stable* format:
420
+
421
+ ```
422
+ ULEB128(len(correction_bytes)), checksum, encoded_bytes, correction_bytes
423
+ ```
424
+
425
+ where
426
+
427
+ - `ULEB128` refers to the
428
+ [unsigned LEB128](https://en.wikipedia.org/wiki/LEB128#Unsigned_LEB128)
429
+ (little endian base 128) variable length encoding for unsigned
430
+ integers
431
+ - `checksum` refers to the
432
+ [RFC 1071](https://datatracker.ietf.org/doc/html/rfc1071)
433
+ "Internet Checksum" over the little-endian C-order bytes of the
434
+ corrected data, stored as two bytes in big-endian order
435
+ - `encoded_bytes` refers to the encoded bytes produced by the codec and
436
+ its optional lossless encoding
437
+ - `correction_bytes` refers to the encoded correction bytes produced by
438
+ the safeguards and their lossless encoding
439
+ - the above bytestrings are concatenated into a single bytestring
440
+
441
+ If no correction is required, `correction_bytes` is empty and there is
442
+ only a three-byte overhead from using the safeguards.
443
+
444
+ The `buf`fer must contain the complete data, i.e. not just a chunk of
445
+ data, so that non-pointwise safeguards are correctly applied and the
446
+ global minimum `$x_min` / `$x_finite_min` and global maximum `$x_max` /
447
+ `$x_finite_max` can be correctly provided. Please refer to the
448
+ [`xarray-safeguards`][xarray_safeguards] frontend for applying
449
+ safeguards to chunked data.
450
+
451
+ Parameters
452
+ ----------
453
+ buf : Buffer
454
+ Data to be encoded. May be any object supporting the new-style
455
+ buffer protocol.
456
+
457
+ Returns
458
+ -------
459
+ enc : bytes
460
+ Encoded data as a bytestring.
461
+
462
+ Raises
463
+ ------
464
+ TypeSetError
465
+ if the `buf`fer uses an unsupported data type.
466
+ RuntimeError
467
+ if decoding with the `codec` with `out=None` fails.
468
+ RuntimeError
469
+ if `codec` and `lossless` do not encode to 1D bytes or do not
470
+ recreate the data's dtype and shape during decoding.
471
+ RuntimeError
472
+ if the `buf`fer is chunked but the safeguards use the built-in
473
+ late-bound parameter `$x_min`, `$x_max`, `$x_finite_min`, or
474
+ `$x_finite_max` for the cross-chunk global minimum / maximum.
475
+ ...
476
+ if checking a safeguard or computing the correction for a safeguard
477
+ raises an exception.
478
+ """
479
+
480
+ data: np.ndarray = (
481
+ buf if isinstance(buf, np.ndarray) else numcodecs.compat.ensure_ndarray(buf)
482
+ )
483
+
484
+ TypeSetError.check_dtype_or_raise(data.dtype, Safeguards.supported_dtypes())
485
+
486
+ encoded: np.ndarray = numcodecs.compat.ensure_ndarray(
487
+ self._codec.encode(np.copy(data))
488
+ )
489
+
490
+ # check that decoding with `out=None` works
491
+ try:
492
+ with ctx.parameter("codec"):
493
+ decoded: np.ndarray = numcodecs.compat.ensure_ndarray(
494
+ self._codec.decode(np.copy(encoded), out=None)
495
+ )
496
+ except Exception as err:
497
+ err.add_note(
498
+ "decoding with `out=None` failed\n\n"
499
+ "consider using wrapping the codec in the "
500
+ "`numcodecs_combinators.framed.FramedCodecStack(codec)` "
501
+ "combinator if the codec requires knowing the output data "
502
+ "type and shape for decoding"
503
+ )
504
+ raise
505
+
506
+ if self._lossless_for_codec is not None:
507
+ encoded = numcodecs.compat.ensure_ndarray(
508
+ self._lossless_for_codec.encode(encoded)
509
+ )
510
+
511
+ try:
512
+ with ctx.parameter(
513
+ "codec" if self._lossless_for_codec is None else "lossless"
514
+ ):
515
+ if np.array(encoded, copy=None).dtype != np.dtype(np.uint8):
516
+ raise RuntimeError("codec and lossless must encode to bytes") | ctx
517
+ if np.array(encoded, copy=None).ndim != 1:
518
+ raise (
519
+ RuntimeError("codec and lossless must encode to 1D bytes") | ctx
520
+ )
521
+ encoded_bytes: bytes = numcodecs.compat.ensure_bytes(encoded)
522
+
523
+ with ctx.parameter("codec"):
524
+ if decoded.dtype != data.dtype:
525
+ raise RuntimeError("codec must decode to the data's dtype") | ctx
526
+ if decoded.shape != data.shape:
527
+ raise RuntimeError("codec must decode to the data's shape") | ctx
528
+ except RuntimeError as err:
529
+ err.add_note(
530
+ "consider using wrapping the codec in the "
531
+ "`numcodecs_combinators.framed.FramedCodecStack(codec)` "
532
+ "combinator to encode to bytes and preserve the data dtype and"
533
+ "shape"
534
+ )
535
+ raise
536
+
537
+ late_bound = self._late_bound
538
+ late_bound_reqs = self._safeguards.late_bound
539
+
540
+ if getattr(data, "chunked", False) and not late_bound_reqs.isdisjoint(
541
+ ("$x_min", "$x_max", "$x_finite_min", "$x_finite_max")
542
+ ):
543
+ with ctx.parameter("data"):
544
+ raise (
545
+ RuntimeError(
546
+ "encoding an individual chunk in a chunked array is "
547
+ "unsafe when using the $x_min, $x_max, $x_finite_min, "
548
+ "or $x_finite_max late-bound constants for the "
549
+ "cross-chunk global minimum / maximum; instead use the "
550
+ "xarray-safeguards frontend or pass the entire (not "
551
+ "chunked) data array"
552
+ )
553
+ | ctx
554
+ )
555
+
556
+ info = (
557
+ np.finfo(data.dtype)
558
+ if np.issubdtype(data.dtype, np.floating)
559
+ else np.iinfo(data.dtype)
560
+ )
561
+
562
+ if "$x_min" in late_bound_reqs:
563
+ late_bound = late_bound.update(
564
+ **{
565
+ "$x_min": np.nanmin(data)
566
+ if data.size > 0 and not np.all(np.isnan(data))
567
+ else data.dtype.type(0)
568
+ }
569
+ )
570
+ if "$x_max" in late_bound_reqs:
571
+ late_bound = late_bound.update(
572
+ **{
573
+ "$x_max": np.nanmax(data)
574
+ if data.size > 0 and not np.all(np.isnan(data))
575
+ else data.dtype.type(0)
576
+ }
577
+ )
578
+ if "$x_finite_min" in late_bound_reqs:
579
+ late_bound = late_bound.update(
580
+ **{
581
+ "$x_finite_min": np.amin(
582
+ data, where=np.isfinite(data), initial=info.max
583
+ )
584
+ if data.size > 0 and np.any(np.isfinite(data))
585
+ else data.dtype.type(0)
586
+ }
587
+ )
588
+ if "$x_finite_max" in late_bound_reqs:
589
+ late_bound = late_bound.update(
590
+ **{
591
+ "$x_finite_max": np.amax(
592
+ data, where=np.isfinite(data), initial=info.min
593
+ )
594
+ if data.size > 0 and np.any(np.isfinite(data))
595
+ else data.dtype.type(0)
596
+ }
597
+ )
598
+
599
+ # the codec always compresses the complete data ... at least chunking
600
+ # is not our concern
601
+ correction: np.ndarray[tuple[int, ...], np.dtype[np.unsignedinteger]]
602
+ if self._compute.unstable_lossless_corrections:
603
+ correction = Safeguards(
604
+ safeguards=[LosslessSafeguard()],
605
+ _version=self._safeguards.version,
606
+ ).compute_correction(
607
+ data,
608
+ decoded,
609
+ late_bound=Bindings.EMPTY,
610
+ where=True,
611
+ )
612
+ else:
613
+ correction = self._safeguards.compute_correction(
614
+ data,
615
+ decoded,
616
+ late_bound=late_bound,
617
+ where=True,
618
+ )
619
+
620
+ if self._compute.unstable_iterative:
621
+ correction = _refine_correction_iteratively(
622
+ self._safeguards, data, decoded, correction, late_bound
623
+ )
624
+
625
+ corrected = self._safeguards.apply_correction(decoded, correction)
626
+ corrected_checksum: bytes = checksum(corrected)
627
+
628
+ correction_bytes: bytes
629
+ if np.all(correction == 0):
630
+ correction_bytes = b""
631
+ else:
632
+ correction_bytes = numcodecs.compat.ensure_bytes(
633
+ self._lossless_for_corrections.encode(correction)
634
+ )
635
+
636
+ correction_len: bytearray = leb128.u.encode(len(correction_bytes))
637
+
638
+ return b"".join(
639
+ [correction_len, corrected_checksum, encoded_bytes, correction_bytes]
640
+ )
641
+
642
+ @override
643
+ def decode(self, buf: Buffer, out: None | Buffer = None) -> Buffer:
644
+ """
645
+ Decode the data in `buf` and apply the safeguards corrections.
646
+
647
+ Parameters
648
+ ----------
649
+ buf : Buffer
650
+ Encoded data. Must be an object representing a bytestring, e.g.
651
+ [`bytes`][bytes] or a 1D array of [`np.uint8`][numpy.uint8]s etc.
652
+ out : None | Buffer
653
+ Writable buffer to store decoded data. N.B. if provided, this buffer must
654
+ be exactly the right size to store the decoded data.
655
+
656
+ Returns
657
+ -------
658
+ dec : Buffer
659
+ Decoded data. May be any object supporting the new-style
660
+ buffer protocol.
661
+
662
+ Raises
663
+ ------
664
+ ValueError
665
+ if `buf` is not a 1D bytes buffer.
666
+ ValueError
667
+ if `buf` has a corrupted header.
668
+ ...
669
+ if applying the safeguards correction raises an exception.
670
+ """
671
+
672
+ with ctx.parameter("buf"):
673
+ buf_array: np.ndarray = numcodecs.compat.ensure_ndarray(buf)
674
+ if buf_array.dtype != np.dtype(np.uint8):
675
+ raise ValueError("can only decode from bytes") | ctx
676
+ if buf_array.ndim != 1:
677
+ raise ValueError("can only decode from 1D bytes") | ctx
678
+ buf_bytes: bytes = numcodecs.compat.ensure_bytes(buf)
679
+
680
+ buf_io = BytesIO(buf_bytes)
681
+ correction_len, _ = leb128.u.decode_reader(buf_io)
682
+ corrected_checksum = buf_io.read(2)
683
+ if correction_len < 0:
684
+ raise (
685
+ ValueError("cannot decode from corrupt buf with invalid header")
686
+ | ctx
687
+ )
688
+
689
+ encoded_bytes: bytes
690
+ correction_bytes: bytes
691
+ if correction_len > 0:
692
+ encoded_bytes = buf_bytes[buf_io.tell() : -correction_len]
693
+ correction_bytes = buf_bytes[-correction_len:]
694
+ else:
695
+ encoded_bytes = buf_bytes[buf_io.tell() :]
696
+ correction_bytes = b""
697
+
698
+ encoded: np.ndarray = np.frombuffer(
699
+ encoded_bytes, dtype="uint8", count=len(encoded_bytes)
700
+ )
701
+
702
+ if self._lossless_for_codec is not None:
703
+ encoded = numcodecs.compat.ensure_ndarray(
704
+ self._lossless_for_codec.decode(encoded)
705
+ )
706
+
707
+ decoded: np.ndarray = numcodecs.compat.ensure_ndarray(
708
+ self._codec.decode(encoded, out=out)
709
+ )
710
+
711
+ corrected: np.ndarray
712
+ if correction_len > 0:
713
+ correction: np.ndarray = (
714
+ numcodecs.compat.ensure_ndarray(
715
+ self._lossless_for_corrections.decode(correction_bytes)
716
+ )
717
+ .view(as_bits(np.array((), dtype=decoded.dtype)).dtype)
718
+ .reshape(decoded.shape)
719
+ )
720
+
721
+ corrected = self._safeguards.apply_correction(decoded, correction)
722
+ else:
723
+ corrected = decoded
724
+
725
+ newly_corrected_checksum = checksum(corrected)
726
+
727
+ if newly_corrected_checksum != corrected_checksum:
728
+ err = ValueError("mismatch in the checksum for the corrected data")
729
+ err.add_note(
730
+ "The checksum of the corrected data is checked to ensure that "
731
+ "the safeguards correction is applied to the bitwise "
732
+ "equivalent decompressed data as when the correction was "
733
+ "computed, i.e. that the corrected data meets all safety "
734
+ "requirements."
735
+ )
736
+ err.add_note(
737
+ "A mismatch in the checksum likely comes from a wrapped "
738
+ "`codec` that produces non-deterministic decompressed output. "
739
+ "Note that the safeguards can only be used with a "
740
+ "deterministic decompressor."
741
+ )
742
+
743
+ raise (err | ctx)
744
+
745
+ return numcodecs.compat.ndarray_copy(corrected, out) # type: ignore
746
+
747
+ @override
748
+ def get_config(self) -> dict[str, JSON]:
749
+ """
750
+ Returns the configuration of this safeguarded codec.
751
+
752
+ [`numcodecs.registry.get_codec(config)`][numcodecs.registry.get_codec]
753
+ can be used to reconstruct this adapter from the returned config.
754
+
755
+ Returns
756
+ -------
757
+ config : dict[str, JSON]
758
+ Configuration of this safeguarded codec.
759
+ """
760
+
761
+ return dict(
762
+ id=type(self).codec_id,
763
+ codec=self._codec.get_config(),
764
+ safeguards=[
765
+ safeguard.get_config() for safeguard in self._safeguards.safeguards
766
+ ],
767
+ fixed_constants=self._late_bound.get_config(),
768
+ lossless=dict(
769
+ for_codec=None
770
+ if self._lossless_for_codec is None
771
+ else self._lossless_for_codec.get_config(),
772
+ for_corrections=self._lossless_for_corrections.get_config(),
773
+ ),
774
+ compute=self._compute.get_config(),
775
+ _version=str(self._safeguards.version),
776
+ )
777
+
778
+ @classmethod
779
+ @override
780
+ def from_config(cls, config: dict[str, JSON]) -> Self:
781
+ """
782
+ Instantiate the safeguarded codec from a configuration [`dict`][dict].
783
+
784
+ Parameters
785
+ ----------
786
+ config : dict[str, JSON]
787
+ Configuration of the safeguarded codec.
788
+
789
+ Returns
790
+ -------
791
+ safeguards : Self
792
+ Instantiated safeguarded codec.
793
+ """
794
+
795
+ # Bindings.from_config handles the encoding and decoding of late-bound
796
+ # constants, which may be in a JSON-compatible serialised form
797
+ config_: dict[str, JSON | Bindings] = {
798
+ k: (Bindings.from_config(v) if k == "fixed_constants" else v) # type: ignore
799
+ for k, v in config.items()
800
+ }
801
+
802
+ return cls(**config_) # type: ignore
803
+
804
+ @override
805
+ def __repr__(self) -> str:
806
+ return f"{type(self).__name__}(codec={self._codec!r}, safeguards={list(self._safeguards.safeguards)!r}, fixed_constants={dict(**self._late_bound._bindings)!r}, lossless={Lossless(for_codec=self._lossless_for_codec, for_corrections=self._lossless_for_corrections)!r}, compute={self._compute!r})"
807
+
808
+ @override
809
+ def map(self, mapper: Callable[[Codec], Codec]) -> "SafeguardedCodec":
810
+ """
811
+ Apply the `mapper` to this safeguarded codec.
812
+
813
+ In the returned [`SafeguardedCodec`][..], the codec is
814
+ replaced by its mapped codec.
815
+
816
+ The `mapper` should recursively apply itself to any inner codecs that
817
+ also implement the
818
+ [`CodecCombinatorMixin`][numcodecs_combinators.abc.CodecCombinatorMixin]
819
+ mixin.
820
+
821
+ To automatically handle the recursive application as a caller, you can
822
+ use
823
+ ```python
824
+ numcodecs_combinators.map_codec(codec, mapper)
825
+ ```
826
+ instead.
827
+
828
+ Parameters
829
+ ----------
830
+ mapper : Callable[[Codec], Codec]
831
+ The callable that should be applied to the inner (unsafeguarded)
832
+ codec to map over this safeguarded codec.
833
+
834
+ Returns
835
+ -------
836
+ mapped : SafeguardedCodec
837
+ The mapped safeguarded codec.
838
+ """
839
+
840
+ return SafeguardedCodec(
841
+ codec=mapper(self._codec),
842
+ safeguards=self._safeguards.safeguards,
843
+ fixed_constants=self._late_bound,
844
+ lossless=Lossless(
845
+ for_codec=None
846
+ if self._lossless_for_codec is None
847
+ else mapper(self._lossless_for_codec),
848
+ for_corrections=mapper(self._lossless_for_corrections),
849
+ ),
850
+ compute=self._compute.get_config(),
851
+ _version=self._safeguards.version,
852
+ )
853
+
854
+
855
+ numcodecs.registry.register_codec(SafeguardedCodec)