Skip to main content

numcodecs_zfp_classic/
lib.rs

1//! [![CI Status]][workflow] [![MSRV]][repo] [![Latest Version]][crates.io] [![Rust Doc Crate]][docs.rs] [![Rust Doc Main]][docs]
2//!
3//! [CI Status]: https://img.shields.io/github/actions/workflow/status/juntyr/numcodecs-rs/ci.yml?branch=main
4//! [workflow]: https://github.com/juntyr/numcodecs-rs/actions/workflows/ci.yml?query=branch%3Amain
5//!
6//! [MSRV]: https://img.shields.io/badge/MSRV-1.88.0-blue
7//! [repo]: https://github.com/juntyr/numcodecs-rs
8//!
9//! [Latest Version]: https://img.shields.io/crates/v/numcodecs-zfp-classic
10//! [crates.io]: https://crates.io/crates/numcodecs-zfp-classic
11//!
12//! [Rust Doc Crate]: https://img.shields.io/docsrs/numcodecs-zfp-classic
13//! [docs.rs]: https://docs.rs/numcodecs-zfp-classic/
14//!
15//! [Rust Doc Main]: https://img.shields.io/badge/docs-main-blue
16//! [docs]: https://juntyr.github.io/numcodecs-rs/numcodecs_zfp_classic
17//!
18//! ZFP (classic) codec implementation for the [`numcodecs`] API.
19//!
20//! This implementation uses ZFP's default
21//! [`ZFP_ROUNDING_MODE=ZFP_ROUND_NEVER`](https://zfp.readthedocs.io/en/release1.0.1/installation.html#c.ZFP_ROUNDING_MODE)
22//! rounding mode, which is known to increase bias and correlation in ZFP's
23//! errors
24//! (see <https://zfp.readthedocs.io/en/release1.0.1/faq.html#zfp-rounding>).
25//!
26//! Please see the `numcodecs-zfp` codec for an implementation that uses an
27//! improved version of ZFP.
28
29#![allow(clippy::multiple_crate_versions)] // embedded-io
30
31use std::{borrow::Cow, fmt};
32
33use ndarray::{Array, Array1, ArrayView, Dimension, Zip};
34use numcodecs::{
35    AnyArray, AnyArrayAssignError, AnyArrayDType, AnyArrayView, AnyArrayViewMut, AnyCowArray,
36    Codec, StaticCodec, StaticCodecConfig, StaticCodecVersion,
37};
38use schemars::JsonSchema;
39use serde::{Deserialize, Serialize};
40use thiserror::Error;
41
42#[cfg(test)]
43use ::serde_json as _;
44
45mod ffi;
46
47type ZfpClassicCodecVersion = StaticCodecVersion<0, 2, 0>;
48
49#[derive(Clone, Serialize, Deserialize, JsonSchema)]
50// serde cannot deny unknown fields because of the flatten
51#[schemars(deny_unknown_fields)]
52/// Codec providing compression using ZFP (classic)
53pub struct ZfpClassicCodec {
54    /// ZFP compression mode
55    #[serde(flatten)]
56    pub mode: ZfpCompressionMode,
57    /// ZFP non-finite values mode
58    #[serde(default)]
59    pub non_finite: ZfpNonFiniteValuesMode,
60    /// The codec's encoding format version. Do not provide this parameter explicitly.
61    #[serde(default, rename = "_version")]
62    pub version: ZfpClassicCodecVersion,
63}
64
65#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
66#[serde(tag = "mode")]
67#[serde(deny_unknown_fields)]
68/// ZFP compression mode
69pub enum ZfpCompressionMode {
70    #[serde(rename = "expert")]
71    /// The most general mode, which can describe all four other modes
72    Expert {
73        /// Minimum number of compressed bits used to represent a block
74        min_bits: u32,
75        /// Maximum number of bits used to represent a block
76        max_bits: u32,
77        /// Maximum number of bit planes encoded
78        max_prec: u32,
79        /// Smallest absolute bit plane number encoded.
80        ///
81        /// This parameter applies to floating-point data only and is ignored
82        /// for integer data.
83        min_exp: i32,
84    },
85    /// In fixed-rate mode, each d-dimensional compressed block of `$4^d$`
86    /// values is stored using a fixed number of bits. This number of
87    /// compressed bits per block is amortized over the `$4^d$` values to give
88    /// a rate of `$rate = \frac{maxbits}{4^d}$` in bits per value.
89    #[serde(rename = "fixed-rate")]
90    FixedRate {
91        /// Rate in bits per value
92        rate: f64,
93    },
94    /// In fixed-precision mode, the number of bits used to encode a block may
95    /// vary, but the number of bit planes (the precision) encoded for the
96    /// transform coefficients is fixed.
97    #[serde(rename = "fixed-precision")]
98    FixedPrecision {
99        /// Number of bit planes encoded
100        precision: u32,
101    },
102    /// In fixed-accuracy mode, all transform coefficient bit planes up to a
103    /// minimum bit plane number are encoded. The smallest absolute bit plane
104    /// number is chosen such that
105    /// `$minexp = \text{floor}(\log_{2}(tolerance))$`.
106    #[serde(rename = "fixed-accuracy")]
107    FixedAccuracy {
108        /// Absolute error tolerance
109        tolerance: f64,
110    },
111    /// Lossless per-block compression that preserves integer and floating point
112    /// bit patterns.
113    #[serde(rename = "reversible")]
114    Reversible,
115}
116
117#[derive(Copy, Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
118#[schemars(inline)]
119/// ZFP non-finite values mode
120pub enum ZfpNonFiniteValuesMode {
121    /// Deny compressing non-finite values, i.e. return an error.
122    #[default]
123    #[serde(rename = "deny")]
124    Deny,
125    /// Unsafely allow compressing non-finite values, even though undefined
126    /// behaviour may be triggered, see
127    /// <https://zfp.readthedocs.io/en/release1.0.1/faq.html#q-valid>.
128    #[serde(rename = "allow-unsafe")]
129    AllowUnsafe,
130}
131
132impl Codec for ZfpClassicCodec {
133    type Error = ZfpClassicCodecError;
134
135    fn encode(&self, data: AnyCowArray) -> Result<AnyArray, Self::Error> {
136        if matches!(data.dtype(), AnyArrayDType::I32 | AnyArrayDType::I64)
137            && matches!(
138                self.mode,
139                ZfpCompressionMode::FixedAccuracy { tolerance: _ }
140            )
141        {
142            return Err(ZfpClassicCodecError::FixedAccuracyModeIntegerData);
143        }
144
145        match data {
146            AnyCowArray::I32(data) => Ok(AnyArray::U8(
147                Array1::from(compress(data.view(), &self.mode, self.non_finite)?).into_dyn(),
148            )),
149            AnyCowArray::I64(data) => Ok(AnyArray::U8(
150                Array1::from(compress(data.view(), &self.mode, self.non_finite)?).into_dyn(),
151            )),
152            AnyCowArray::F32(data) => Ok(AnyArray::U8(
153                Array1::from(compress(data.view(), &self.mode, self.non_finite)?).into_dyn(),
154            )),
155            AnyCowArray::F64(data) => Ok(AnyArray::U8(
156                Array1::from(compress(data.view(), &self.mode, self.non_finite)?).into_dyn(),
157            )),
158            encoded => Err(ZfpClassicCodecError::UnsupportedDtype(encoded.dtype())),
159        }
160    }
161
162    fn decode(&self, encoded: AnyCowArray) -> Result<AnyArray, Self::Error> {
163        let AnyCowArray::U8(encoded) = encoded else {
164            return Err(ZfpClassicCodecError::EncodedDataNotBytes {
165                dtype: encoded.dtype(),
166            });
167        };
168
169        if !matches!(encoded.shape(), [_]) {
170            return Err(ZfpClassicCodecError::EncodedDataNotOneDimensional {
171                shape: encoded.shape().to_vec(),
172            });
173        }
174
175        decompress(&AnyCowArray::U8(encoded).as_bytes())
176    }
177
178    fn decode_into(
179        &self,
180        encoded: AnyArrayView,
181        decoded: AnyArrayViewMut,
182    ) -> Result<(), Self::Error> {
183        let AnyArrayView::U8(encoded) = encoded else {
184            return Err(ZfpClassicCodecError::EncodedDataNotBytes {
185                dtype: encoded.dtype(),
186            });
187        };
188
189        if !matches!(encoded.shape(), [_]) {
190            return Err(ZfpClassicCodecError::EncodedDataNotOneDimensional {
191                shape: encoded.shape().to_vec(),
192            });
193        }
194
195        decompress_into(&AnyArrayView::U8(encoded).as_bytes(), decoded)
196    }
197}
198
199impl StaticCodec for ZfpClassicCodec {
200    const CODEC_ID: &'static str = "zfp-classic.rs";
201
202    type Config<'de> = Self;
203
204    fn from_config(config: Self::Config<'_>) -> Self {
205        config
206    }
207
208    fn get_config(&self) -> StaticCodecConfig<'_, Self> {
209        StaticCodecConfig::from(self)
210    }
211}
212
213#[derive(Debug, Error)]
214/// Errors that may occur when applying the [`ZfpClassicCodec`].
215pub enum ZfpClassicCodecError {
216    /// [`ZfpClassicCodec`] does not support the dtype
217    #[error("ZfpClassic does not support the dtype {0}")]
218    UnsupportedDtype(AnyArrayDType),
219    /// [`ZfpClassicCodec`] does not support the fixed accuracy mode for
220    /// integer data
221    #[error("ZfpClassic does not support the fixed accuracy mode for integer data")]
222    FixedAccuracyModeIntegerData,
223    /// [`ZfpClassicCodec`] only supports 1-4 dimensional data
224    #[error("ZfpClassic only supports 1-4 dimensional data but found shape {shape:?}")]
225    ExcessiveDimensionality {
226        /// The unexpected shape of the data
227        shape: Vec<usize>,
228    },
229    /// [`ZfpClassicCodec`] was configured with an invalid expert `mode`
230    #[error("ZfpClassic was configured with an invalid expert mode {mode:?}")]
231    InvalidExpertMode {
232        /// The unexpected compression mode
233        mode: ZfpCompressionMode,
234    },
235    /// [`ZfpClassicCodec`] does not support non-finite (infinite or NaN)
236    /// floating point data  in non-reversible lossy compression
237    #[error(
238        "ZfpClassic does not support non-finite (infinite or NaN) floating point data in non-reversible lossy compression"
239    )]
240    NonFiniteData,
241    /// [`ZfpClassicCodec`] failed to encode the header
242    #[error("ZfpClassic failed to encode the header")]
243    HeaderEncodeFailed,
244    /// [`ZfpClassicCodec`] failed to encode the array metadata header
245    #[error("ZfpClassic failed to encode the array metadata header")]
246    MetaHeaderEncodeFailed {
247        /// Opaque source error
248        source: ZfpHeaderError,
249    },
250    /// [`ZfpClassicCodec`] failed to encode the data
251    #[error("ZfpClassic failed to encode the data")]
252    ZfpEncodeFailed,
253    /// [`ZfpClassicCodec`] can only decode one-dimensional byte arrays but
254    /// received an array of a different dtype
255    #[error(
256        "ZfpClassic can only decode one-dimensional byte arrays but received an array of dtype {dtype}"
257    )]
258    EncodedDataNotBytes {
259        /// The unexpected dtype of the encoded array
260        dtype: AnyArrayDType,
261    },
262    /// [`ZfpClassicCodec`] can only decode one-dimensional byte arrays but
263    /// received an array of a different shape
264    #[error(
265        "ZfpClassic can only decode one-dimensional byte arrays but received a byte array of shape {shape:?}"
266    )]
267    EncodedDataNotOneDimensional {
268        /// The unexpected shape of the encoded array
269        shape: Vec<usize>,
270    },
271    /// [`ZfpClassicCodec`] failed to decode the header
272    #[error("ZfpClassic failed to decode the header")]
273    HeaderDecodeFailed,
274    /// [`ZfpClassicCodec`] failed to decode the array metadata header
275    #[error("ZfpClassic failed to decode the array metadata header")]
276    MetaHeaderDecodeFailed {
277        /// Opaque source error
278        source: ZfpHeaderError,
279    },
280    /// [`ZfpClassicCodec`] cannot decode into the provided array
281    #[error("ZfpClassicCodec cannot decode into the provided array")]
282    MismatchedDecodeIntoArray {
283        /// The source of the error
284        #[from]
285        source: AnyArrayAssignError,
286    },
287    /// [`ZfpClassicCodec`] failed to decode the data
288    #[error("ZfpClassic failed to decode the data")]
289    ZfpDecodeFailed,
290}
291
292#[derive(Debug, Error)]
293#[error(transparent)]
294/// Opaque error for when encoding or decoding the header fails
295pub struct ZfpHeaderError(postcard::Error);
296
297/// Compress the `data` array using ZFP with the provided `mode`.
298///
299/// # Errors
300///
301/// Errors with
302/// - [`ZfpClassicCodecError::NonFiniteData`] if any data element is non-finite
303///   (infinite or NaN) and a non-reversible lossy compression `mode` is used
304///   and the `non_finite` mode is not [`ZfpNonFiniteValuesMode::AllowUnsafe`]
305/// - [`ZfpClassicCodecError::ExcessiveDimensionality`] if data is more than
306///   4-dimensional
307/// - [`ZfpClassicCodecError::InvalidExpertMode`] if the `mode` has invalid
308///   expert mode parameters
309/// - [`ZfpClassicCodecError::HeaderEncodeFailed`] if encoding the ZFP header
310///   failed
311/// - [`ZfpClassicCodecError::MetaHeaderEncodeFailed`] if encoding the array
312///   metadata header failed
313/// - [`ZfpClassicCodecError::ZfpEncodeFailed`] if an opaque encoding error
314///   occurred
315pub fn compress<T: ffi::ZfpCompressible, D: Dimension>(
316    data: ArrayView<T, D>,
317    mode: &ZfpCompressionMode,
318    non_finite: ZfpNonFiniteValuesMode,
319) -> Result<Vec<u8>, ZfpClassicCodecError> {
320    if !matches!(mode, ZfpCompressionMode::Reversible)
321        && !matches!(non_finite, ZfpNonFiniteValuesMode::AllowUnsafe)
322        && !Zip::from(&data).all(|x| x.is_finite())
323    {
324        return Err(ZfpClassicCodecError::NonFiniteData);
325    }
326
327    let mut encoded = postcard::to_extend(
328        &CompressionHeader {
329            dtype: <T as ffi::ZfpCompressible>::D_TYPE,
330            shape: Cow::Borrowed(data.shape()),
331            version: StaticCodecVersion,
332        },
333        Vec::new(),
334    )
335    .map_err(|err| ZfpClassicCodecError::MetaHeaderEncodeFailed {
336        source: ZfpHeaderError(err),
337    })?;
338
339    // ZFP cannot handle zero-length dimensions
340    if data.is_empty() {
341        return Ok(encoded);
342    }
343
344    // Setup zfp structs to begin compression
345    // Squeeze the data to avoid wasting ZFP dimensions on axes of length 1
346    let field = ffi::ZfpField::new(data.into_dyn().squeeze())?;
347    let stream = ffi::ZfpCompressionStream::new(&field, mode)?;
348
349    // Allocate space based on the maximum size potentially required by zfp to
350    //  store the compressed array
351    let stream = stream.with_bitstream(field, &mut encoded);
352
353    // Write the header so we can reconstruct ZFP's mode on decompression
354    let stream = stream.write_header()?;
355
356    // Compress the field into the allocated output array
357    stream.compress()?;
358
359    Ok(encoded)
360}
361
362/// Decompress the `encoded` data into an array using ZFP.
363///
364/// # Errors
365///
366/// Errors with
367/// - [`ZfpClassicCodecError::HeaderDecodeFailed`] if decoding the ZFP header
368///   failed
369/// - [`ZfpClassicCodecError::MetaHeaderDecodeFailed`] if decoding the array
370///   metadata header failed
371/// - [`ZfpClassicCodecError::ZfpDecodeFailed`] if an opaque decoding error
372///   occurred
373pub fn decompress(encoded: &[u8]) -> Result<AnyArray, ZfpClassicCodecError> {
374    let (header, encoded) =
375        postcard::take_from_bytes::<CompressionHeader>(encoded).map_err(|err| {
376            ZfpClassicCodecError::MetaHeaderDecodeFailed {
377                source: ZfpHeaderError(err),
378            }
379        })?;
380
381    // Return empty data for zero-size arrays
382    if header.shape.iter().copied().any(|s| s == 0) {
383        let decoded = match header.dtype {
384            ZfpDType::I32 => AnyArray::I32(Array::zeros(&*header.shape)),
385            ZfpDType::I64 => AnyArray::I64(Array::zeros(&*header.shape)),
386            ZfpDType::F32 => AnyArray::F32(Array::zeros(&*header.shape)),
387            ZfpDType::F64 => AnyArray::F64(Array::zeros(&*header.shape)),
388        };
389        return Ok(decoded);
390    }
391
392    // Setup zfp structs to begin decompression
393    let stream = ffi::ZfpDecompressionStream::new(encoded);
394
395    // Read the header to reconstruct ZFP's mode
396    let stream = stream.read_header()?;
397
398    // Decompress the field into a newly allocated output array
399    match header.dtype {
400        ZfpDType::I32 => {
401            let mut decompressed = Array::zeros(&*header.shape);
402            stream.decompress_into(decompressed.view_mut().squeeze())?;
403            Ok(AnyArray::I32(decompressed))
404        }
405        ZfpDType::I64 => {
406            let mut decompressed = Array::zeros(&*header.shape);
407            stream.decompress_into(decompressed.view_mut().squeeze())?;
408            Ok(AnyArray::I64(decompressed))
409        }
410        ZfpDType::F32 => {
411            let mut decompressed = Array::zeros(&*header.shape);
412            stream.decompress_into(decompressed.view_mut().squeeze())?;
413            Ok(AnyArray::F32(decompressed))
414        }
415        ZfpDType::F64 => {
416            let mut decompressed = Array::zeros(&*header.shape);
417            stream.decompress_into(decompressed.view_mut().squeeze())?;
418            Ok(AnyArray::F64(decompressed))
419        }
420    }
421}
422
423/// Decompress the `encoded` data into a `decoded` array using ZFP.
424///
425/// # Errors
426///
427/// Errors with
428/// - [`ZfpClassicCodecError::HeaderDecodeFailed`] if decoding the ZFP header
429///   failed
430/// - [`ZfpClassicCodecError::MetaHeaderDecodeFailed`] if decoding the array
431///   metadata header failed
432/// - [`ZfpClassicCodecError::MismatchedDecodeIntoArray`] if the `decoded`
433///   array is of the wrong dtype or shape
434/// - [`ZfpClassicCodecError::ZfpDecodeFailed`] if an opaque decoding error
435///   occurred
436pub fn decompress_into(
437    encoded: &[u8],
438    decoded: AnyArrayViewMut,
439) -> Result<(), ZfpClassicCodecError> {
440    let (header, encoded) =
441        postcard::take_from_bytes::<CompressionHeader>(encoded).map_err(|err| {
442            ZfpClassicCodecError::MetaHeaderDecodeFailed {
443                source: ZfpHeaderError(err),
444            }
445        })?;
446
447    if decoded.shape() != &*header.shape {
448        return Err(ZfpClassicCodecError::MismatchedDecodeIntoArray {
449            source: AnyArrayAssignError::ShapeMismatch {
450                src: header.shape.into_owned(),
451                dst: decoded.shape().to_vec(),
452            },
453        });
454    }
455
456    // Empty data doesn't need to be initialized
457    if decoded.is_empty() {
458        return Ok(());
459    }
460
461    // Setup zfp structs to begin decompression
462    let stream = ffi::ZfpDecompressionStream::new(encoded);
463
464    // Read the header to reconstruct ZFP's mode
465    let stream = stream.read_header()?;
466
467    // Decompress the field into the output array
468    match (decoded, header.dtype) {
469        (AnyArrayViewMut::I32(decoded), ZfpDType::I32) => stream.decompress_into(decoded.squeeze()),
470        (AnyArrayViewMut::I64(decoded), ZfpDType::I64) => stream.decompress_into(decoded.squeeze()),
471        (AnyArrayViewMut::F32(decoded), ZfpDType::F32) => stream.decompress_into(decoded.squeeze()),
472        (AnyArrayViewMut::F64(decoded), ZfpDType::F64) => stream.decompress_into(decoded.squeeze()),
473        (decoded, dtype) => Err(ZfpClassicCodecError::MismatchedDecodeIntoArray {
474            source: AnyArrayAssignError::DTypeMismatch {
475                src: dtype.into_dtype(),
476                dst: decoded.dtype(),
477            },
478        }),
479    }
480}
481
482#[derive(Serialize, Deserialize)]
483struct CompressionHeader<'a> {
484    dtype: ZfpDType,
485    #[serde(borrow)]
486    shape: Cow<'a, [usize]>,
487    version: ZfpClassicCodecVersion,
488}
489
490/// Dtypes that Zfp can compress and decompress
491#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
492#[expect(missing_docs)]
493pub enum ZfpDType {
494    #[serde(rename = "i32", alias = "int32")]
495    I32,
496    #[serde(rename = "i64", alias = "int64")]
497    I64,
498    #[serde(rename = "f32", alias = "float32")]
499    F32,
500    #[serde(rename = "f64", alias = "float64")]
501    F64,
502}
503
504impl ZfpDType {
505    /// Get the corresponding [`AnyArrayDType`]
506    #[must_use]
507    pub const fn into_dtype(self) -> AnyArrayDType {
508        match self {
509            Self::I32 => AnyArrayDType::I32,
510            Self::I64 => AnyArrayDType::I64,
511            Self::F32 => AnyArrayDType::F32,
512            Self::F64 => AnyArrayDType::F64,
513        }
514    }
515}
516
517impl fmt::Display for ZfpDType {
518    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
519        fmt.write_str(match self {
520            Self::I32 => "i32",
521            Self::I64 => "i64",
522            Self::F32 => "f32",
523            Self::F64 => "f64",
524        })
525    }
526}
527
528#[cfg(test)]
529#[expect(clippy::unwrap_used)]
530mod tests {
531    use ndarray::ArrayView1;
532
533    use super::*;
534
535    #[test]
536    fn zero_length() {
537        let encoded = compress(
538            Array::<f32, _>::from_shape_vec([1, 27, 0].as_slice(), vec![])
539                .unwrap()
540                .view(),
541            &ZfpCompressionMode::FixedPrecision { precision: 7 },
542            ZfpNonFiniteValuesMode::Deny,
543        )
544        .unwrap();
545        let decoded = decompress(&encoded).unwrap();
546
547        assert_eq!(decoded.dtype(), AnyArrayDType::F32);
548        assert!(decoded.is_empty());
549        assert_eq!(decoded.shape(), &[1, 27, 0]);
550    }
551
552    #[test]
553    fn one_dimension() {
554        let data = Array::from_shape_vec(
555            [2_usize, 1, 2, 1, 1, 1].as_slice(),
556            vec![1.0, 2.0, 3.0, 4.0],
557        )
558        .unwrap();
559
560        let encoded = compress(
561            data.view(),
562            &ZfpCompressionMode::FixedAccuracy { tolerance: 0.1 },
563            ZfpNonFiniteValuesMode::Deny,
564        )
565        .unwrap();
566        let decoded = decompress(&encoded).unwrap();
567
568        assert_eq!(decoded, AnyArray::F32(data));
569    }
570
571    #[test]
572    fn small_state() {
573        for data in [
574            &[][..],
575            &[0.0],
576            &[0.0, 1.0],
577            &[0.0, 1.0, 0.0],
578            &[0.0, 1.0, 0.0, 1.0],
579        ] {
580            let encoded = compress(
581                ArrayView1::from(data),
582                &ZfpCompressionMode::FixedAccuracy { tolerance: 0.1 },
583                ZfpNonFiniteValuesMode::Deny,
584            )
585            .unwrap();
586            let decoded = decompress(&encoded).unwrap();
587
588            assert_eq!(
589                decoded,
590                AnyArray::F64(Array1::from_vec(data.to_vec()).into_dyn())
591            );
592        }
593    }
594}