1#![allow(clippy::multiple_crate_versions)] use 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#[schemars(deny_unknown_fields)]
52pub struct ZfpClassicCodec {
54 #[serde(flatten)]
56 pub mode: ZfpCompressionMode,
57 #[serde(default)]
59 pub non_finite: ZfpNonFiniteValuesMode,
60 #[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)]
68pub enum ZfpCompressionMode {
70 #[serde(rename = "expert")]
71 Expert {
73 min_bits: u32,
75 max_bits: u32,
77 max_prec: u32,
79 min_exp: i32,
84 },
85 #[serde(rename = "fixed-rate")]
90 FixedRate {
91 rate: f64,
93 },
94 #[serde(rename = "fixed-precision")]
98 FixedPrecision {
99 precision: u32,
101 },
102 #[serde(rename = "fixed-accuracy")]
107 FixedAccuracy {
108 tolerance: f64,
110 },
111 #[serde(rename = "reversible")]
114 Reversible,
115}
116
117#[derive(Copy, Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
118#[schemars(inline)]
119pub enum ZfpNonFiniteValuesMode {
121 #[default]
123 #[serde(rename = "deny")]
124 Deny,
125 #[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)]
214pub enum ZfpClassicCodecError {
216 #[error("ZfpClassic does not support the dtype {0}")]
218 UnsupportedDtype(AnyArrayDType),
219 #[error("ZfpClassic does not support the fixed accuracy mode for integer data")]
222 FixedAccuracyModeIntegerData,
223 #[error("ZfpClassic only supports 1-4 dimensional data but found shape {shape:?}")]
225 ExcessiveDimensionality {
226 shape: Vec<usize>,
228 },
229 #[error("ZfpClassic was configured with an invalid expert mode {mode:?}")]
231 InvalidExpertMode {
232 mode: ZfpCompressionMode,
234 },
235 #[error(
238 "ZfpClassic does not support non-finite (infinite or NaN) floating point data in non-reversible lossy compression"
239 )]
240 NonFiniteData,
241 #[error("ZfpClassic failed to encode the header")]
243 HeaderEncodeFailed,
244 #[error("ZfpClassic failed to encode the array metadata header")]
246 MetaHeaderEncodeFailed {
247 source: ZfpHeaderError,
249 },
250 #[error("ZfpClassic failed to encode the data")]
252 ZfpEncodeFailed,
253 #[error(
256 "ZfpClassic can only decode one-dimensional byte arrays but received an array of dtype {dtype}"
257 )]
258 EncodedDataNotBytes {
259 dtype: AnyArrayDType,
261 },
262 #[error(
265 "ZfpClassic can only decode one-dimensional byte arrays but received a byte array of shape {shape:?}"
266 )]
267 EncodedDataNotOneDimensional {
268 shape: Vec<usize>,
270 },
271 #[error("ZfpClassic failed to decode the header")]
273 HeaderDecodeFailed,
274 #[error("ZfpClassic failed to decode the array metadata header")]
276 MetaHeaderDecodeFailed {
277 source: ZfpHeaderError,
279 },
280 #[error("ZfpClassicCodec cannot decode into the provided array")]
282 MismatchedDecodeIntoArray {
283 #[from]
285 source: AnyArrayAssignError,
286 },
287 #[error("ZfpClassic failed to decode the data")]
289 ZfpDecodeFailed,
290}
291
292#[derive(Debug, Error)]
293#[error(transparent)]
294pub struct ZfpHeaderError(postcard::Error);
296
297pub 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 if data.is_empty() {
341 return Ok(encoded);
342 }
343
344 let field = ffi::ZfpField::new(data.into_dyn().squeeze())?;
347 let stream = ffi::ZfpCompressionStream::new(&field, mode)?;
348
349 let stream = stream.with_bitstream(field, &mut encoded);
352
353 let stream = stream.write_header()?;
355
356 stream.compress()?;
358
359 Ok(encoded)
360}
361
362pub 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 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 let stream = ffi::ZfpDecompressionStream::new(encoded);
394
395 let stream = stream.read_header()?;
397
398 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
423pub 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 if decoded.is_empty() {
458 return Ok(());
459 }
460
461 let stream = ffi::ZfpDecompressionStream::new(encoded);
463
464 let stream = stream.read_header()?;
466
467 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#[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 #[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}