Skip to main content

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