numcodecs_safeguards
numcodecs_safeguards
Fearless lossy compression with numcodecs-safeguards
Lossy compression can be scary as valuable information or features of the data may be lost.
By using Safeguards to guarantee
your safety requirements, lossy compression can be applied safely and
without fear.
Overview
This package provides the SafeguardedCodec adapter /
meta-compressor that can be wrapped around any existing (lossy)
numcodecs.abc.Codec to guarantee that certain
properties of the original data are preserved by compression.
The SafeguardedCodec treats the wrapped inner codec as a blackbox. To
guarantee the user's safety requirements, it post-processes the decompressed
data, if necessary. If no correction is needed, the SafeguardedCodec only has
a three-byte overhead for the compressed data and a computational overhead at
compression time (at decompression time, only the checksum is verified).
By using the SafeguardedCodec adapter, badly behaving lossy codecs become safe
to use, at the cost of potentially less efficient compression, and lossy
compression can be applied without fear.
The SafeguardedCodec must only be used to encode the complete data, i.e. not
just a chunk of data, so that non-pointwise safeguards are correctly applied.
Please refer to the xarray-safeguards frontend for
applying safeguards to chunked data.
Example
You can wrap an existing codec with e.g. a relative error bound of \(eb_{rel} = 1\%\) and preserve data signs as follows:
import numpy as np
from numcodecs.fixedscaleoffset import FixedScaleOffset
from numcodecs_safeguards import SafeguardedCodec
# use any numcodecs-compatible codec
# here we quantize data >= -10 with one decimal digit
lossy_codec = FixedScaleOffset(
offset=-10, scale=10, dtype="float64", astype="uint8",
)
# wrap the codec in the `SafeguardedCodec` and specify the safeguards to apply
sg_codec = SafeguardedCodec(codec=lossy_codec, safeguards=[
# guarantee a relative error bound of 1%:
# |x - x'| <= |x| * 0.01
dict(kind="eb", type="rel", eb=0.01),
# guarantee that the sign is preserved:
# sign(x) = sign(x')
dict(kind="sign"),
])
# some n-dimensional data
data = np.linspace(-10, 10, 21)
# encode and decode the data
encoded = sg_codec.encode(data)
decoded = sg_codec.decode(encoded)
# the safeguard properties are guaranteed to hold
assert np.all(np.abs(data - decoded) <= np.abs(data) * 0.01)
assert np.all(np.sign(data) == np.sign(decoded))
Please refer to the
compression_safeguards.SafeguardKind
for an enumeration of all supported safeguards.
Modules:
-
checksum– -
compute–Helper classes for configuring the compute behaviour of the
SafeguardedCodec. -
lossless–Helper classes for lossless encoding for the
SafeguardedCodec.
Classes:
-
SafeguardedCodec–An adaptor codec that uses
SafeguardedCodec
SafeguardedCodec(
*,
codec: dict[str, JSON] | Codec,
safeguards: Collection[dict[str, JSON] | Safeguard],
fixed_constants: Mapping[str | Parameter, Value]
| Bindings = EMPTY,
lossless: None | dict[str, JSON] | Lossless = None,
compute: None | dict[str, JSON] = None,
_version: None | str | Version = None,
)
Bases: Codec, CodecCombinatorMixin
An adaptor codec that uses
Safeguards to guarantee certain
properties / safety requirements are upheld by the wrapped codec.
| Parameters: |
|
|---|
| Raises: |
|
|---|
Methods:
-
update_fixed_constants–Create a new safeguarded codec, where the old fixed constants have been
-
encode–Encode the data in
bufwhile safeguarding the compression. -
decode–Decode the data in
bufand apply the safeguards corrections. -
get_config–Returns the configuration of this safeguarded codec.
-
from_config–Instantiate the safeguarded codec from a configuration
dict. -
map–Apply the
mapperto this safeguarded codec.
safeguards
property
safeguards: Collection[Safeguard]
The collection of safeguards that will be applied.
late_bound
property
The set of late-bound parameters that the safeguards have.
The late-bound parameters must be provided as fixed constants. They
must have a compatible shape and values for any data that will be
encoded with this codec, otherwise encode will fail.
builtin_late_bound
property
The set of built-in late-bound constants that the numcodecs-safeguards
provide automatically, which include the safeguards' built-ins as well
as $x_min and $x_max.
update_fixed_constants
update_fixed_constants(**kwargs: Value) -> SafeguardedCodec
Create a new safeguarded codec, where the old fixed constants have been
overridden by new ones from **kwargs.
Only existing late-bound constants may be overridden and no new ones may be added.
The provided values must have a compatible shape and values for any
data that will be encoded with this codec, otherwise
encode will fail.
This method can be used inside a with statement to temporarily update
the late-bound parameters.
| Parameters: |
|
|---|
| Returns: |
|
|---|
- API Reference numcodecs_safeguards SafeguardedCodec
encode
encode(buf: Buffer) -> bytes
Encode the data in buf while safeguarding the compression.
The encoded data is defined by the following stable format:
ULEB128(len(correction_bytes)), checksum, encoded_bytes, correction_bytes
where
ULEB128refers to the unsigned LEB128 (little endian base 128) variable length encoding for unsigned integerschecksumrefers to the RFC 1071 "Internet Checksum" over the little-endian C-order bytes of the corrected data, stored as two bytes in big-endian orderencoded_bytesrefers to the encoded bytes produced by the codec and its optional lossless encodingcorrection_bytesrefers to the encoded correction bytes produced by the safeguards and their lossless encoding- the above bytestrings are concatenated into a single bytestring
If no correction is required, correction_bytes is empty and there is
only a three-byte overhead from using the safeguards.
The buffer must contain the complete data, i.e. not just a chunk of
data, so that non-pointwise safeguards are correctly applied and the
global minimum $x_min and global maximum $x_max can be correctly
provided. Please refer to the xarray-safeguards
frontend for applying safeguards to chunked data.
| Parameters: |
|
|---|
| Returns: |
|
|---|
| Raises: |
|
|---|
- API Reference numcodecs_safeguards SafeguardedCodec
decode
decode(buf: Buffer, out: None | Buffer = None) -> Buffer
Decode the data in buf and apply the safeguards corrections.
| Parameters: |
|
|---|
| Returns: |
|
|---|
| Raises: |
|
|---|
get_config
Returns the configuration of this safeguarded codec.
numcodecs.registry.get_codec(config)
can be used to reconstruct this adapter from the returned config.
| Returns: |
|---|
- API Reference numcodecs_safeguards SafeguardedCodec
from_config
classmethod
map
map(mapper: Callable[[Codec], Codec]) -> SafeguardedCodec
Apply the mapper to this safeguarded codec.
In the returned SafeguardedCodec, the codec is
replaced by its mapped codec.
The mapper should recursively apply itself to any inner codecs that
also implement the
CodecCombinatorMixin
mixin.
To automatically handle the recursive application as a caller, you can use
numcodecs_combinators.map_codec(codec, mapper)
| Parameters: |
|---|
| Returns: |
|
|---|