numcodecs-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.
- numcodecs_safeguards/__init__.py +749 -0
- numcodecs_safeguards/compute.py +229 -0
- numcodecs_safeguards/lossless.py +48 -0
- numcodecs_safeguards/py.typed +0 -0
- numcodecs_safeguards-0.1.0a1.dist-info/METADATA +425 -0
- numcodecs_safeguards-0.1.0a1.dist-info/RECORD +9 -0
- numcodecs_safeguards-0.1.0a1.dist-info/WHEEL +4 -0
- numcodecs_safeguards-0.1.0a1.dist-info/entry_points.txt +2 -0
- numcodecs_safeguards-0.1.0a1.dist-info/licenses/LICENSE +373 -0
|
@@ -0,0 +1,749 @@
|
|
|
1
|
+
r"""
|
|
2
|
+
# 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 [`SafeguardsCodec`][.SafeguardsCodec] 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 `SafeguardsCodec` 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 `SafeguardsCodec` only has
|
|
21
|
+
a one-byte overhead for the compressed data and a computational overhead at
|
|
22
|
+
compression time.
|
|
23
|
+
|
|
24
|
+
By using the `SafeguardsCodec` 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 `SafeguardsCodec` 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 SafeguardsCodec
|
|
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 `SafeguardsCodec` and specify the safeguards to apply
|
|
50
|
+
sg_codec = SafeguardsCodec(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__ = ["SafeguardsCodec"]
|
|
77
|
+
|
|
78
|
+
from collections.abc import Callable, Collection, Mapping, Set
|
|
79
|
+
from io import BytesIO
|
|
80
|
+
from typing import ClassVar
|
|
81
|
+
|
|
82
|
+
import numcodecs
|
|
83
|
+
import numcodecs.compat
|
|
84
|
+
import numcodecs.registry
|
|
85
|
+
import numcodecs_combinators
|
|
86
|
+
import numpy as np
|
|
87
|
+
import varint
|
|
88
|
+
from compression_safeguards.api import Safeguards
|
|
89
|
+
from compression_safeguards.safeguards.abc import Safeguard
|
|
90
|
+
from compression_safeguards.utils.bindings import Bindings, Parameter, Value
|
|
91
|
+
from compression_safeguards.utils.cast import as_bits
|
|
92
|
+
from compression_safeguards.utils.error import (
|
|
93
|
+
LateBoundParameterResolutionError,
|
|
94
|
+
TypeSetError,
|
|
95
|
+
ctx,
|
|
96
|
+
)
|
|
97
|
+
from compression_safeguards.utils.typing import JSON
|
|
98
|
+
from numcodecs.abc import Codec
|
|
99
|
+
from numcodecs_combinators.abc import CodecCombinatorMixin
|
|
100
|
+
from semver import Version
|
|
101
|
+
from typing_extensions import (
|
|
102
|
+
Buffer, # MSPV 3.12
|
|
103
|
+
Self, # MSPV 3.11
|
|
104
|
+
override, # MSPV 3.12
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
from .compute import Compute, _refine_correction_iteratively
|
|
108
|
+
from .lossless import Lossless
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class SafeguardsCodec(Codec, CodecCombinatorMixin):
|
|
112
|
+
"""
|
|
113
|
+
An adaptor codec that uses
|
|
114
|
+
[`Safeguards`][compression_safeguards.api.Safeguards] to guarantee certain
|
|
115
|
+
properties / safety requirements are upheld by the wrapped codec.
|
|
116
|
+
|
|
117
|
+
Parameters
|
|
118
|
+
----------
|
|
119
|
+
codec : dict[str, JSON] | Codec
|
|
120
|
+
The codec to wrap with safeguards. It can either be passed as a codec
|
|
121
|
+
configuration [`dict`][dict], which is passed to
|
|
122
|
+
[`numcodecs.registry.get_codec(config)`][numcodecs.registry.get_codec],
|
|
123
|
+
or an already initialized [`Codec`][numcodecs.abc.Codec]. If you want to
|
|
124
|
+
wrap a sequence or stack of codecs, you can use the
|
|
125
|
+
[`numcodecs_combinators.stack.CodecStack`][numcodecs_combinators.stack.CodecStack]
|
|
126
|
+
combinator.
|
|
127
|
+
|
|
128
|
+
It is desirable to perform lossless compression after applying the
|
|
129
|
+
safeguards (rather than before), e.g. by customising the
|
|
130
|
+
[`Lossless.for_codec`][..lossless.Lossless.for_codec] field of the
|
|
131
|
+
`lossless` parameter.
|
|
132
|
+
|
|
133
|
+
The `codec` combined with its `lossless` encoding must encode to a 1D
|
|
134
|
+
buffer of bytes. It is also recommended that the `codec` can
|
|
135
|
+
[`decode`][numcodecs.abc.Codec.decode]
|
|
136
|
+
without receiving the output data type and shape via the `out`
|
|
137
|
+
parameter. If the `codec` does not fulfil these requirements, it can be
|
|
138
|
+
wrapped inside the
|
|
139
|
+
[`numcodecs_combinators.framed.FramedCodecStack`][numcodecs_combinators.framed.FramedCodecStack]
|
|
140
|
+
combinator.
|
|
141
|
+
|
|
142
|
+
It is also possible to compress the data with *just* the safeguards
|
|
143
|
+
(i.e. without a `codec` that provides proper lossy compression) by
|
|
144
|
+
passing [`numcodecs_zero.ZeroCodec()`][numcodecs_zero.ZeroCodec] or
|
|
145
|
+
`dict(id="zero")` to `codec`. The zero codec only encodes the data
|
|
146
|
+
type and shape, not the data values themselves, and decodes to all-
|
|
147
|
+
zero values, forcing the safeguards to correct (almost) all values.
|
|
148
|
+
With this configuration, the safeguards thus act as a safe lossy
|
|
149
|
+
compressor in their own right, as any size reduction comes from the
|
|
150
|
+
`lossless` compression of the safeguards corrections (which the
|
|
151
|
+
safeguards produce to be highly-compressible, if possible).
|
|
152
|
+
safeguards : Collection[dict[str, JSON] | Safeguard]
|
|
153
|
+
The safeguards that will be applied to the codec. They can either be
|
|
154
|
+
passed as a safeguard configuration [`dict`][dict] or an already
|
|
155
|
+
initialized
|
|
156
|
+
[`Safeguard`][compression_safeguards.safeguards.abc.Safeguard].
|
|
157
|
+
|
|
158
|
+
Please refer to the
|
|
159
|
+
[`SafeguardKind`][compression_safeguards.safeguards.SafeguardKind]
|
|
160
|
+
for an enumeration of all supported safeguards.
|
|
161
|
+
|
|
162
|
+
The `SafeguardsCodec` supports safeguards with late-bound parameters,
|
|
163
|
+
e.g. the
|
|
164
|
+
[`SelectSafeguard`][compression_safeguards.safeguards.combinators.select.SelectSafeguard],
|
|
165
|
+
but they must be provided as `fixed_constants` that are *fixed* and
|
|
166
|
+
must be compatible with *any* data that will be encoded with this
|
|
167
|
+
codec. Therefore, fixed constants should only be used for late-bound
|
|
168
|
+
parameters that can be fixed across all uses of the codec.
|
|
169
|
+
fixed_constants : Mapping[str | Parameter, Value] | Bindings
|
|
170
|
+
Mapping of parameter names to *fixed* constant scalars or arrays that
|
|
171
|
+
will be provided as late-bound parameters to the safeguards.
|
|
172
|
+
|
|
173
|
+
The mapping must resolve all late-bound parameters of the safeguards
|
|
174
|
+
and include no extraneous parameters.
|
|
175
|
+
|
|
176
|
+
The provided values must have a compatible shape and values for *any*
|
|
177
|
+
data that will be encoded with this codec, otherwise
|
|
178
|
+
[`encode`][.encode] will fail.
|
|
179
|
+
|
|
180
|
+
You can use the [`update_fixed_constants`][.update_fixed_constants]
|
|
181
|
+
method inside a `with` statement to temporarily update the late-bound
|
|
182
|
+
parameters.
|
|
183
|
+
|
|
184
|
+
The fixed constants are included in the [config][.get_config] of the
|
|
185
|
+
codec. While [`int`][int] and [`float`][float] scalars are included
|
|
186
|
+
as-is, numpy scalars and arrays are encoded to the losslessly
|
|
187
|
+
compressed [`.npz`][numpy.savez_compressed] format and stored in a
|
|
188
|
+
`data:application/x-npz;base64,<data>`
|
|
189
|
+
[data URI](https://developer.mozilla.org/en-US/docs/Web/URI/Reference/Schemes/data).
|
|
190
|
+
lossless : None | dict[str, JSON] | Lossless, optional
|
|
191
|
+
The lossless encoding that is applied after the codec and the
|
|
192
|
+
safeguards:
|
|
193
|
+
|
|
194
|
+
- [`Lossless.for_codec`][..lossless.Lossless.for_codec] specifies the
|
|
195
|
+
lossless encoding that is applied to the encoded output of the
|
|
196
|
+
wrapped `codec`. By default, no additional lossless encoding is
|
|
197
|
+
applied.
|
|
198
|
+
- [`Lossless.for_safeguards`][..lossless.Lossless.for_safeguards]
|
|
199
|
+
specifies the lossless encoding that is applied to the corrections
|
|
200
|
+
that the safeguards produce. By default, Huffman coding followed by
|
|
201
|
+
Zstandard compression is applied.
|
|
202
|
+
|
|
203
|
+
The lossless encoding must encode to a 1D buffer of bytes.
|
|
204
|
+
compute : None | dict[str, JSON] | Compute, optional
|
|
205
|
+
Compute configuration with options that may affect the compression
|
|
206
|
+
ratio and time cost of computing the safeguards corrections.
|
|
207
|
+
|
|
208
|
+
While these options can change the particular corrections that are
|
|
209
|
+
produced, the resulting corrections always satisfy the safety
|
|
210
|
+
requirements.
|
|
211
|
+
_version : ...
|
|
212
|
+
The version of the codec. Do not provide this parameter explicitly.
|
|
213
|
+
|
|
214
|
+
Raises
|
|
215
|
+
------
|
|
216
|
+
ValueError
|
|
217
|
+
if `codec` wraps another `SafeguardsCodec`, which may create a printer
|
|
218
|
+
problem.
|
|
219
|
+
LateBoundParameterResolutionError
|
|
220
|
+
if `fixed_constants` does not resolve all late-bound parameters of the
|
|
221
|
+
safeguards or includes any extraneous parameters.
|
|
222
|
+
...
|
|
223
|
+
if instantiating the `codec` or a safeguard raises an exception.
|
|
224
|
+
"""
|
|
225
|
+
|
|
226
|
+
__slots__: tuple[str, ...] = (
|
|
227
|
+
"_codec",
|
|
228
|
+
"_safeguards",
|
|
229
|
+
"_late_bound",
|
|
230
|
+
"_lossless_for_codec",
|
|
231
|
+
"_lossless_for_safeguards",
|
|
232
|
+
"_compute",
|
|
233
|
+
)
|
|
234
|
+
_codec: Codec
|
|
235
|
+
_safeguards: Safeguards
|
|
236
|
+
_late_bound: Bindings
|
|
237
|
+
_lossless_for_codec: None | Codec
|
|
238
|
+
_lossless_for_safeguards: Codec
|
|
239
|
+
_compute: Compute
|
|
240
|
+
|
|
241
|
+
codec_id: ClassVar[str] = "safeguards" # type: ignore
|
|
242
|
+
|
|
243
|
+
def __init__(
|
|
244
|
+
self,
|
|
245
|
+
*,
|
|
246
|
+
codec: dict[str, JSON] | Codec,
|
|
247
|
+
safeguards: Collection[dict[str, JSON] | Safeguard],
|
|
248
|
+
fixed_constants: Mapping[str | Parameter, Value] | Bindings = Bindings.EMPTY,
|
|
249
|
+
lossless: None | dict[str, JSON] | Lossless = None,
|
|
250
|
+
compute: None | dict[str, JSON] = None,
|
|
251
|
+
_version: None | str | Version = None,
|
|
252
|
+
) -> None:
|
|
253
|
+
wraps_safeguards_codec = False
|
|
254
|
+
|
|
255
|
+
def check_for_safeguards_codec(codec: Codec) -> Codec:
|
|
256
|
+
nonlocal wraps_safeguards_codec
|
|
257
|
+
wraps_safeguards_codec |= isinstance(codec, SafeguardsCodec)
|
|
258
|
+
return codec
|
|
259
|
+
|
|
260
|
+
self._codec = (
|
|
261
|
+
codec if isinstance(codec, Codec) else numcodecs.registry.get_codec(codec)
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
numcodecs_combinators.map_codec(self._codec, check_for_safeguards_codec)
|
|
265
|
+
|
|
266
|
+
if wraps_safeguards_codec:
|
|
267
|
+
with ctx.parameter("codec"):
|
|
268
|
+
raise (
|
|
269
|
+
ValueError(
|
|
270
|
+
"`SafeguardsCodec` should not wrap a codec containing "
|
|
271
|
+
+ "another `SafeguardsCodec` since the safeguards of one "
|
|
272
|
+
+ "might not be upheld by the other (printer problem); "
|
|
273
|
+
+ "merge them into one combined `SafeguardsCodec` instead"
|
|
274
|
+
)
|
|
275
|
+
| ctx
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
self._safeguards = Safeguards(safeguards=safeguards, _version=_version)
|
|
279
|
+
|
|
280
|
+
self._late_bound = (
|
|
281
|
+
fixed_constants
|
|
282
|
+
if isinstance(fixed_constants, Bindings)
|
|
283
|
+
else Bindings(**fixed_constants)
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
late_bound_reqs = frozenset(self.late_bound - self.builtin_late_bound)
|
|
287
|
+
late_bound_keys = frozenset(self._late_bound.parameters())
|
|
288
|
+
|
|
289
|
+
LateBoundParameterResolutionError.check_or_raise(
|
|
290
|
+
late_bound_reqs, late_bound_keys
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
lossless = (
|
|
294
|
+
lossless
|
|
295
|
+
if isinstance(lossless, Lossless)
|
|
296
|
+
else Lossless(**lossless) # type: ignore
|
|
297
|
+
if lossless is not None
|
|
298
|
+
else Lossless()
|
|
299
|
+
)
|
|
300
|
+
self._lossless_for_codec = (
|
|
301
|
+
lossless.for_codec
|
|
302
|
+
if isinstance(lossless.for_codec, Codec)
|
|
303
|
+
else numcodecs.registry.get_codec(lossless.for_codec)
|
|
304
|
+
if lossless.for_codec is not None
|
|
305
|
+
else None
|
|
306
|
+
)
|
|
307
|
+
self._lossless_for_safeguards = (
|
|
308
|
+
lossless.for_safeguards
|
|
309
|
+
if isinstance(lossless.for_safeguards, Codec)
|
|
310
|
+
else numcodecs.registry.get_codec(lossless.for_safeguards)
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
self._compute = (
|
|
314
|
+
compute
|
|
315
|
+
if isinstance(compute, Compute)
|
|
316
|
+
else Compute.from_config(compute)
|
|
317
|
+
if compute is not None
|
|
318
|
+
else Compute()
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
@property
|
|
322
|
+
def codec(self) -> Codec:
|
|
323
|
+
"""
|
|
324
|
+
The codec that is wrapped with safeguards.
|
|
325
|
+
"""
|
|
326
|
+
|
|
327
|
+
return self._codec
|
|
328
|
+
|
|
329
|
+
@property
|
|
330
|
+
def safeguards(self) -> Collection[Safeguard]:
|
|
331
|
+
"""
|
|
332
|
+
The collection of safeguards that will be applied.
|
|
333
|
+
"""
|
|
334
|
+
|
|
335
|
+
return self._safeguards.safeguards
|
|
336
|
+
|
|
337
|
+
@property
|
|
338
|
+
def late_bound(self) -> Set[Parameter]:
|
|
339
|
+
"""
|
|
340
|
+
The set of late-bound parameters that the safeguards have.
|
|
341
|
+
|
|
342
|
+
The late-bound parameters must be provided as fixed constants. They
|
|
343
|
+
must have a compatible shape and values for any data that will be
|
|
344
|
+
encoded with this codec, otherwise [`encode`][..encode] will fail.
|
|
345
|
+
"""
|
|
346
|
+
|
|
347
|
+
return self._safeguards.late_bound
|
|
348
|
+
|
|
349
|
+
@property
|
|
350
|
+
def builtin_late_bound(self) -> Set[Parameter]:
|
|
351
|
+
"""
|
|
352
|
+
The set of built-in late-bound constants that the numcodecs-safeguards
|
|
353
|
+
provide automatically, which include the safeguards' built-ins as well
|
|
354
|
+
as `$x_min` and `$x_max`.
|
|
355
|
+
"""
|
|
356
|
+
|
|
357
|
+
return frozenset(self._safeguards.builtin_late_bound) | frozenset(
|
|
358
|
+
[Parameter("$x_min"), Parameter("$x_max")]
|
|
359
|
+
)
|
|
360
|
+
|
|
361
|
+
def update_fixed_constants(self, **kwargs: Value) -> "SafeguardsCodec":
|
|
362
|
+
"""
|
|
363
|
+
Create a new codec with safeguards, where the old fixed constants have
|
|
364
|
+
been overridden by new ones from `**kwargs`.
|
|
365
|
+
|
|
366
|
+
Only existing late-bound constants may be overridden and no new ones
|
|
367
|
+
may be added.
|
|
368
|
+
|
|
369
|
+
The provided values must have a compatible shape and values for *any*
|
|
370
|
+
data that will be encoded with this codec, otherwise
|
|
371
|
+
[`encode`][..encode] will fail.
|
|
372
|
+
|
|
373
|
+
This method can be used inside a `with` statement to temporarily update
|
|
374
|
+
the late-bound parameters.
|
|
375
|
+
|
|
376
|
+
Parameters
|
|
377
|
+
----------
|
|
378
|
+
**kwargs : Value
|
|
379
|
+
Mapping from new parameters to values as keyword arguments.
|
|
380
|
+
|
|
381
|
+
Returns
|
|
382
|
+
-------
|
|
383
|
+
safeguards : SafeguardsCodec
|
|
384
|
+
The codec with safeguards, with the updated fixed constants.
|
|
385
|
+
"""
|
|
386
|
+
|
|
387
|
+
return SafeguardsCodec(
|
|
388
|
+
codec=self._codec,
|
|
389
|
+
safeguards=self._safeguards.safeguards,
|
|
390
|
+
fixed_constants=self._late_bound.update(**kwargs),
|
|
391
|
+
lossless=Lossless(
|
|
392
|
+
for_codec=None
|
|
393
|
+
if self._lossless_for_codec is None
|
|
394
|
+
else self._lossless_for_codec,
|
|
395
|
+
for_safeguards=self._lossless_for_safeguards,
|
|
396
|
+
),
|
|
397
|
+
_version=self._safeguards.version,
|
|
398
|
+
)
|
|
399
|
+
|
|
400
|
+
@override
|
|
401
|
+
def encode(self, buf: Buffer) -> bytes:
|
|
402
|
+
"""Encode the data in `buf`.
|
|
403
|
+
|
|
404
|
+
The encoded data is defined by the following *stable* format:
|
|
405
|
+
|
|
406
|
+
```
|
|
407
|
+
ULEB128(len(correction_bytes)), encoded_bytes, correction_bytes
|
|
408
|
+
```
|
|
409
|
+
|
|
410
|
+
where
|
|
411
|
+
|
|
412
|
+
- `ULEB128` refers to the
|
|
413
|
+
[unsigned LEB128](https://en.wikipedia.org/wiki/LEB128#Unsigned_LEB128)
|
|
414
|
+
(little endian base 128) variable length encoding for unsigned
|
|
415
|
+
integers
|
|
416
|
+
- `encoded_bytes` refers to the encoded bytes produced by the codec and
|
|
417
|
+
its optional lossless encoding
|
|
418
|
+
- `correction_bytes` refers to the encoded correction bytes produced by
|
|
419
|
+
the safeguards and their lossless encoding
|
|
420
|
+
|
|
421
|
+
If no correction is required, `correction_bytes` is empty and there is
|
|
422
|
+
only a single-byte overhead from using the safeguards.
|
|
423
|
+
|
|
424
|
+
The `buf`fer must contain the complete data, i.e. not just a chunk of
|
|
425
|
+
data, so that non-pointwise safeguards are correctly applied. Please
|
|
426
|
+
refer to the [`xarray-safeguards`][xarray_safeguards] frontend for
|
|
427
|
+
applying safeguards to chunked data.
|
|
428
|
+
|
|
429
|
+
Parameters
|
|
430
|
+
----------
|
|
431
|
+
buf : Buffer
|
|
432
|
+
Data to be encoded. May be any object supporting the new-style
|
|
433
|
+
buffer protocol.
|
|
434
|
+
|
|
435
|
+
Returns
|
|
436
|
+
-------
|
|
437
|
+
enc : bytes
|
|
438
|
+
Encoded data as a bytestring.
|
|
439
|
+
|
|
440
|
+
Raises
|
|
441
|
+
------
|
|
442
|
+
TypeSetError
|
|
443
|
+
if the `buf`fer uses an unsupported data type.
|
|
444
|
+
RuntimeError
|
|
445
|
+
if decoding with the `codec` with `out=None` fails.
|
|
446
|
+
RuntimError
|
|
447
|
+
if `codec` and `lossless` do not encode to 1D bytes or do not
|
|
448
|
+
recreate the data's dtype and shape during decoding.
|
|
449
|
+
...
|
|
450
|
+
if checking a safeguard or computing the correction for a safeguard
|
|
451
|
+
raises an exception.
|
|
452
|
+
"""
|
|
453
|
+
|
|
454
|
+
data = (
|
|
455
|
+
buf if isinstance(buf, np.ndarray) else numcodecs.compat.ensure_ndarray(buf)
|
|
456
|
+
)
|
|
457
|
+
|
|
458
|
+
TypeSetError.check_dtype_or_raise(data.dtype, Safeguards.supported_dtypes())
|
|
459
|
+
|
|
460
|
+
encoded = self._codec.encode(np.copy(data))
|
|
461
|
+
encoded = numcodecs.compat.ensure_ndarray(encoded)
|
|
462
|
+
|
|
463
|
+
# check that decoding with `out=None` works
|
|
464
|
+
try:
|
|
465
|
+
with ctx.parameter("codec"):
|
|
466
|
+
decoded = self._codec.decode(np.copy(encoded), out=None)
|
|
467
|
+
except Exception as err:
|
|
468
|
+
note = (
|
|
469
|
+
"decoding with `out=None` failed\n\n"
|
|
470
|
+
"consider using wrapping the codec in the "
|
|
471
|
+
"`numcodecs_combinators.framed.FramedCodecStack(codec)` "
|
|
472
|
+
"combinator if the codec requires knowing the output data "
|
|
473
|
+
"type and shape for decoding"
|
|
474
|
+
)
|
|
475
|
+
|
|
476
|
+
# MSPV 3.11
|
|
477
|
+
if getattr(err, "add_note", None) is not None:
|
|
478
|
+
err.add_note(note) # type: ignore
|
|
479
|
+
raise
|
|
480
|
+
else:
|
|
481
|
+
raise (RuntimeError(note) | ctx) from err
|
|
482
|
+
decoded = numcodecs.compat.ensure_ndarray(decoded)
|
|
483
|
+
|
|
484
|
+
if self._lossless_for_codec is not None:
|
|
485
|
+
encoded = self._lossless_for_codec.encode(encoded)
|
|
486
|
+
|
|
487
|
+
try:
|
|
488
|
+
with ctx.parameter(
|
|
489
|
+
"codec" if self._lossless_for_codec is None else "lossless"
|
|
490
|
+
):
|
|
491
|
+
if np.array(encoded, copy=None).dtype != np.dtype(np.uint8):
|
|
492
|
+
raise RuntimeError("codec and lossless must encode to bytes") | ctx
|
|
493
|
+
if np.array(encoded, copy=None).ndim != 1:
|
|
494
|
+
raise (
|
|
495
|
+
RuntimeError("codec and lossless must encode to 1D bytes") | ctx
|
|
496
|
+
)
|
|
497
|
+
encoded_bytes = numcodecs.compat.ensure_bytes(encoded)
|
|
498
|
+
|
|
499
|
+
with ctx.parameter("codec"):
|
|
500
|
+
if decoded.dtype != data.dtype:
|
|
501
|
+
raise RuntimeError("codec must decode to the data's dtype") | ctx
|
|
502
|
+
if decoded.shape != data.shape:
|
|
503
|
+
raise RuntimeError("codec must decode to the data's shape") | ctx
|
|
504
|
+
except RuntimeError as err:
|
|
505
|
+
note = (
|
|
506
|
+
"consider using wrapping the codec in the "
|
|
507
|
+
"`numcodecs_combinators.framed.FramedCodecStack(codec)` "
|
|
508
|
+
"combinator to encode to bytes and preserve the data dtype and"
|
|
509
|
+
"shape"
|
|
510
|
+
)
|
|
511
|
+
|
|
512
|
+
# MSPV 3.11
|
|
513
|
+
if getattr(err, "add_note", None) is not None:
|
|
514
|
+
err.add_note(note) # type: ignore
|
|
515
|
+
raise
|
|
516
|
+
else:
|
|
517
|
+
raise (RuntimeError(note) | ctx) from err
|
|
518
|
+
|
|
519
|
+
late_bound = self._late_bound
|
|
520
|
+
late_bound_reqs = self._safeguards.late_bound
|
|
521
|
+
|
|
522
|
+
if "$x_min" in late_bound_reqs:
|
|
523
|
+
late_bound = late_bound.update(
|
|
524
|
+
**{
|
|
525
|
+
"$x_min": np.nanmin(data)
|
|
526
|
+
if data.size > 0 and not np.all(np.isnan(data))
|
|
527
|
+
else data.dtype.type(0)
|
|
528
|
+
}
|
|
529
|
+
)
|
|
530
|
+
if "$x_max" in late_bound_reqs:
|
|
531
|
+
late_bound = late_bound.update(
|
|
532
|
+
**{
|
|
533
|
+
"$x_max": np.nanmax(data)
|
|
534
|
+
if data.size > 0 and not np.all(np.isnan(data))
|
|
535
|
+
else data.dtype.type(0)
|
|
536
|
+
}
|
|
537
|
+
)
|
|
538
|
+
|
|
539
|
+
# the codec always compresses the complete data ... at least chunking
|
|
540
|
+
# is not our concern
|
|
541
|
+
correction: np.ndarray[tuple[int, ...], np.dtype[np.unsignedinteger]] = (
|
|
542
|
+
self._safeguards.compute_correction(
|
|
543
|
+
data,
|
|
544
|
+
decoded,
|
|
545
|
+
late_bound=late_bound,
|
|
546
|
+
where=True,
|
|
547
|
+
)
|
|
548
|
+
)
|
|
549
|
+
|
|
550
|
+
if self._compute.unstable_iterative:
|
|
551
|
+
correction = _refine_correction_iteratively(
|
|
552
|
+
self._safeguards, data, decoded, correction, late_bound
|
|
553
|
+
)
|
|
554
|
+
|
|
555
|
+
if np.all(correction == 0):
|
|
556
|
+
correction_bytes = b""
|
|
557
|
+
else:
|
|
558
|
+
correction_bytes = numcodecs.compat.ensure_bytes(
|
|
559
|
+
self._lossless_for_safeguards.encode(correction)
|
|
560
|
+
)
|
|
561
|
+
|
|
562
|
+
correction_len = varint.encode(len(correction_bytes))
|
|
563
|
+
|
|
564
|
+
return correction_len + encoded_bytes + correction_bytes
|
|
565
|
+
|
|
566
|
+
@override
|
|
567
|
+
def decode(self, buf: Buffer, out: None | Buffer = None) -> Buffer:
|
|
568
|
+
"""Decode the data in `buf`.
|
|
569
|
+
|
|
570
|
+
Parameters
|
|
571
|
+
----------
|
|
572
|
+
buf : Buffer
|
|
573
|
+
Encoded data. Must be an object representing a bytestring, e.g.
|
|
574
|
+
[`bytes`][bytes] or a 1D array of [`np.uint8`][numpy.uint8]s etc.
|
|
575
|
+
out : None | Buffer
|
|
576
|
+
Writeable buffer to store decoded data. N.B. if provided, this buffer must
|
|
577
|
+
be exactly the right size to store the decoded data.
|
|
578
|
+
|
|
579
|
+
Returns
|
|
580
|
+
-------
|
|
581
|
+
dec : Buffer
|
|
582
|
+
Decoded data. May be any object supporting the new-style
|
|
583
|
+
buffer protocol.
|
|
584
|
+
|
|
585
|
+
Raises
|
|
586
|
+
------
|
|
587
|
+
ValueError
|
|
588
|
+
if `buf` is not a 1D bytes buffer.
|
|
589
|
+
ValueError
|
|
590
|
+
if `buf` has a corrupted header.
|
|
591
|
+
...
|
|
592
|
+
if applying the safeguards correction raises an exception.
|
|
593
|
+
"""
|
|
594
|
+
|
|
595
|
+
with ctx.parameter("buf"):
|
|
596
|
+
buf_array = numcodecs.compat.ensure_ndarray(buf)
|
|
597
|
+
if buf_array.dtype != np.dtype(np.uint8):
|
|
598
|
+
raise ValueError("can only decode from bytes") | ctx
|
|
599
|
+
if buf_array.ndim != 1:
|
|
600
|
+
raise ValueError("can only decode from 1D bytes") | ctx
|
|
601
|
+
buf_bytes = numcodecs.compat.ensure_bytes(buf)
|
|
602
|
+
|
|
603
|
+
buf_io = BytesIO(buf_bytes)
|
|
604
|
+
correction_len = varint.decode_stream(buf_io)
|
|
605
|
+
if correction_len < 0:
|
|
606
|
+
raise (
|
|
607
|
+
ValueError("cannot decode from corrupt buf with invalid header")
|
|
608
|
+
| ctx
|
|
609
|
+
)
|
|
610
|
+
|
|
611
|
+
if correction_len > 0:
|
|
612
|
+
encoded = buf_bytes[buf_io.tell() : -correction_len]
|
|
613
|
+
correction_bytes = buf_bytes[-correction_len:]
|
|
614
|
+
else:
|
|
615
|
+
encoded = buf_bytes[buf_io.tell() :]
|
|
616
|
+
correction_bytes = b""
|
|
617
|
+
|
|
618
|
+
if self._lossless_for_codec is not None:
|
|
619
|
+
encoded = numcodecs.compat.ensure_bytes(
|
|
620
|
+
self._lossless_for_codec.decode(encoded)
|
|
621
|
+
)
|
|
622
|
+
|
|
623
|
+
decoded = self._codec.decode(
|
|
624
|
+
np.frombuffer(encoded, dtype="uint8", count=len(encoded)), out=out
|
|
625
|
+
)
|
|
626
|
+
|
|
627
|
+
if correction_len > 0:
|
|
628
|
+
correction = (
|
|
629
|
+
numcodecs.compat.ensure_ndarray(
|
|
630
|
+
self._lossless_for_safeguards.decode(correction_bytes)
|
|
631
|
+
)
|
|
632
|
+
.view(as_bits(np.array((), dtype=decoded.dtype)).dtype)
|
|
633
|
+
.reshape(decoded.shape)
|
|
634
|
+
)
|
|
635
|
+
|
|
636
|
+
corrected = self._safeguards.apply_correction(decoded, correction)
|
|
637
|
+
else:
|
|
638
|
+
corrected = decoded
|
|
639
|
+
|
|
640
|
+
return numcodecs.compat.ndarray_copy(corrected, out) # type: ignore
|
|
641
|
+
|
|
642
|
+
@override
|
|
643
|
+
def get_config(self) -> dict[str, JSON]:
|
|
644
|
+
"""
|
|
645
|
+
Returns the configuration of the codec with safeguards.
|
|
646
|
+
|
|
647
|
+
[`numcodecs.registry.get_codec(config)`][numcodecs.registry.get_codec]
|
|
648
|
+
can be used to reconstruct this adapter from the returned config.
|
|
649
|
+
|
|
650
|
+
Returns
|
|
651
|
+
-------
|
|
652
|
+
config : dict[str, JSON]
|
|
653
|
+
Configuration of the codec with safeguards.
|
|
654
|
+
"""
|
|
655
|
+
|
|
656
|
+
return dict(
|
|
657
|
+
id=type(self).codec_id,
|
|
658
|
+
codec=self._codec.get_config(),
|
|
659
|
+
safeguards=[
|
|
660
|
+
safeguard.get_config() for safeguard in self._safeguards.safeguards
|
|
661
|
+
],
|
|
662
|
+
fixed_constants=self._late_bound.get_config(),
|
|
663
|
+
lossless=dict(
|
|
664
|
+
for_codec=None
|
|
665
|
+
if self._lossless_for_codec is None
|
|
666
|
+
else self._lossless_for_codec.get_config(),
|
|
667
|
+
for_safeguards=self._lossless_for_safeguards.get_config(),
|
|
668
|
+
),
|
|
669
|
+
compute=self._compute.get_config(),
|
|
670
|
+
_version=str(self._safeguards.version),
|
|
671
|
+
)
|
|
672
|
+
|
|
673
|
+
@classmethod
|
|
674
|
+
@override
|
|
675
|
+
def from_config(cls, config: dict[str, JSON]) -> Self:
|
|
676
|
+
"""
|
|
677
|
+
Instantiate the codec with safeguards from a configuration [`dict`][dict].
|
|
678
|
+
|
|
679
|
+
Parameters
|
|
680
|
+
----------
|
|
681
|
+
config : dict[str, JSON]
|
|
682
|
+
Configuration of the codec with safeguards.
|
|
683
|
+
|
|
684
|
+
Returns
|
|
685
|
+
-------
|
|
686
|
+
safeguards : Self
|
|
687
|
+
Instantiated codec with safeguards.
|
|
688
|
+
"""
|
|
689
|
+
|
|
690
|
+
# Bindings.from_config handles the encoding and decoding of late-bound
|
|
691
|
+
# constants, which may be in a JSON-compatible serialised form
|
|
692
|
+
config_: dict[str, JSON | Bindings] = {
|
|
693
|
+
k: (Bindings.from_config(v) if k == "fixed_constants" else v) # type: ignore
|
|
694
|
+
for k, v in config.items()
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
return cls(**config_) # type: ignore
|
|
698
|
+
|
|
699
|
+
@override
|
|
700
|
+
def __repr__(self) -> str:
|
|
701
|
+
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_safeguards=self._lossless_for_safeguards)!r})"
|
|
702
|
+
|
|
703
|
+
@override
|
|
704
|
+
def map(self, mapper: Callable[[Codec], Codec]) -> "SafeguardsCodec":
|
|
705
|
+
"""
|
|
706
|
+
Apply the `mapper` to this codec with safeguards.
|
|
707
|
+
|
|
708
|
+
In the returned [`SafeguardsCodec`][..], the codec is
|
|
709
|
+
replaced by its mapped codec.
|
|
710
|
+
|
|
711
|
+
The `mapper` should recursively apply itself to any inner codecs that
|
|
712
|
+
also implement the
|
|
713
|
+
[`CodecCombinatorMixin`][numcodecs_combinators.abc.CodecCombinatorMixin]
|
|
714
|
+
mixin.
|
|
715
|
+
|
|
716
|
+
To automatically handle the recursive application as a caller, you can
|
|
717
|
+
use
|
|
718
|
+
```python
|
|
719
|
+
numcodecs_combinators.map_codec(codec, mapper)
|
|
720
|
+
```
|
|
721
|
+
instead.
|
|
722
|
+
|
|
723
|
+
Parameters
|
|
724
|
+
----------
|
|
725
|
+
mapper : Callable[[Codec], Codec]
|
|
726
|
+
The callable that should be applied to this codec to map over this
|
|
727
|
+
codec with safeguards.
|
|
728
|
+
|
|
729
|
+
Returns
|
|
730
|
+
-------
|
|
731
|
+
mapped : SafeguardsCodec
|
|
732
|
+
The mapped codec with safeguards.
|
|
733
|
+
"""
|
|
734
|
+
|
|
735
|
+
return SafeguardsCodec(
|
|
736
|
+
codec=mapper(self._codec),
|
|
737
|
+
safeguards=self._safeguards.safeguards,
|
|
738
|
+
fixed_constants=self._late_bound,
|
|
739
|
+
lossless=Lossless(
|
|
740
|
+
for_codec=None
|
|
741
|
+
if self._lossless_for_codec is None
|
|
742
|
+
else mapper(self._lossless_for_codec),
|
|
743
|
+
for_safeguards=mapper(self._lossless_for_safeguards),
|
|
744
|
+
),
|
|
745
|
+
_version=self._safeguards.version,
|
|
746
|
+
)
|
|
747
|
+
|
|
748
|
+
|
|
749
|
+
numcodecs.registry.register_codec(SafeguardsCodec)
|