Skip to main content

numcodecs_ebcc/
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-ebcc
10//! [crates.io]: https://crates.io/crates/numcodecs-ebcc
11//!
12//! [Rust Doc Crate]: https://img.shields.io/docsrs/numcodecs-ebcc
13//! [docs.rs]: https://docs.rs/numcodecs-ebcc/
14//!
15//! [Rust Doc Main]: https://img.shields.io/badge/docs-main-blue
16//! [docs]: https://juntyr.github.io/numcodecs-rs/numcodecs_ebcc
17//!
18//! EBCC codec implementation for the [`numcodecs`] API.
19
20#![allow(clippy::multiple_crate_versions)] // embedded-io
21
22#[cfg(test)]
23use ::serde_json as _;
24
25use std::{borrow::Cow, num::NonZeroUsize};
26
27use ndarray::{Array, Array1, ArrayBase, ArrayViewMut, Axis, Data, DataMut, Dimension, IxDyn};
28use num_traits::Float;
29use numcodecs::{
30    AnyArray, AnyArrayDType, AnyArrayView, AnyArrayViewMut, AnyCowArray, Codec, StaticCodec,
31    StaticCodecConfig, StaticCodecVersion,
32};
33use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
34use serde::{Deserialize, Deserializer, Serialize, Serializer};
35use thiserror::Error;
36
37type EbccCodecVersion = StaticCodecVersion<0, 1, 1>;
38
39/// Codec providing compression using EBCC.
40///
41/// EBCC combines JPEG2000 compression with error-bounded residual compression.
42///
43/// Arrays that are higher-dimensional than 3D are encoded by compressing each
44/// 3D slice with EBCC independently. Specifically, the array's shape is
45/// interpreted as `[.., depth, height, width]`. If you want to compress 3D
46/// slices along three different axes, you can swizzle the array axes
47/// beforehand.
48#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
49#[schemars(deny_unknown_fields)]
50pub struct EbccCodec {
51    /// EBCC residual compression
52    #[serde(flatten)]
53    pub residual: EbccResidualType,
54    /// JPEG2000 positive base compression ratio
55    #[serde(default = "default_base_cr")]
56    pub base_cr: Positive<f32>,
57    /// Optional EBCC-internal chunk shape.
58    #[serde(default)]
59    pub chunk_shape: EbccChunkShape,
60    /// The codec's encoding format version. Do not provide this parameter explicitly.
61    #[serde(default, rename = "_version")]
62    pub version: EbccCodecVersion,
63}
64
65#[derive(Debug, Copy, Clone, Default, Serialize, Deserialize, JsonSchema)]
66#[serde(deny_unknown_fields)]
67#[schemars(inline)]
68/// Chunk shape that EBCC uses to handle large data.
69pub enum EbccChunkShape {
70    /// EBCC chooses an appropriate chunk shape automatically.
71    #[serde(rename = "auto")]
72    #[default]
73    Auto,
74    /// EBCC uses the provided explicit chunk shape.
75    #[serde(untagged)]
76    Explicit([NonZeroUsize; 3]),
77}
78
79const fn default_base_cr() -> Positive<f32> {
80    Positive(100.0)
81}
82
83/// Residual compression types supported by EBCC.
84#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
85#[serde(tag = "residual")]
86#[serde(deny_unknown_fields)]
87pub enum EbccResidualType {
88    #[serde(rename = "jpeg2000-only")]
89    /// No residual compression - base JPEG2000 only
90    Jpeg2000Only,
91    #[serde(rename = "absolute")]
92    /// Residual compression with absolute maximum error bound
93    AbsoluteError {
94        /// The positive maximum absolute error bound
95        error: Positive<f32>,
96    },
97    #[serde(rename = "relative")]
98    /// Residual compression with relative error bound
99    RelativeError {
100        /// The positive maximum relative error bound
101        error: Positive<f32>,
102    },
103}
104
105impl Codec for EbccCodec {
106    type Error = EbccCodecError;
107
108    fn encode(&self, data: AnyCowArray) -> Result<AnyArray, Self::Error> {
109        match data {
110            AnyCowArray::F32(data) => Ok(AnyArray::U8(
111                Array1::from(compress(
112                    data,
113                    self.residual,
114                    self.base_cr,
115                    self.chunk_shape,
116                )?)
117                .into_dyn(),
118            )),
119            encoded => Err(EbccCodecError::UnsupportedDtype(encoded.dtype())),
120        }
121    }
122
123    fn decode(&self, encoded: AnyCowArray) -> Result<AnyArray, Self::Error> {
124        let AnyCowArray::U8(encoded) = encoded else {
125            return Err(EbccCodecError::EncodedDataNotBytes {
126                dtype: encoded.dtype(),
127            });
128        };
129
130        if !matches!(encoded.shape(), [_]) {
131            return Err(EbccCodecError::EncodedDataNotOneDimensional {
132                shape: encoded.shape().to_vec(),
133            });
134        }
135
136        decompress(&AnyCowArray::U8(encoded).as_bytes())
137    }
138
139    fn decode_into(
140        &self,
141        encoded: AnyArrayView,
142        decoded: AnyArrayViewMut,
143    ) -> Result<(), Self::Error> {
144        let AnyArrayView::U8(encoded) = encoded else {
145            return Err(EbccCodecError::EncodedDataNotBytes {
146                dtype: encoded.dtype(),
147            });
148        };
149
150        if !matches!(encoded.shape(), [_]) {
151            return Err(EbccCodecError::EncodedDataNotOneDimensional {
152                shape: encoded.shape().to_vec(),
153            });
154        }
155
156        match decoded {
157            AnyArrayViewMut::F32(decoded) => {
158                decompress_into(&AnyArrayView::U8(encoded).as_bytes(), decoded)
159            }
160            decoded => Err(EbccCodecError::UnsupportedDtype(decoded.dtype())),
161        }
162    }
163}
164
165impl StaticCodec for EbccCodec {
166    const CODEC_ID: &'static str = "ebcc.rs";
167
168    type Config<'de> = Self;
169
170    fn from_config(config: Self::Config<'_>) -> Self {
171        config
172    }
173
174    fn get_config(&self) -> StaticCodecConfig<'_, Self> {
175        StaticCodecConfig::from(self)
176    }
177}
178
179/// Errors that may occur when applying the [`EbccCodec`].
180#[derive(Debug, thiserror::Error)]
181pub enum EbccCodecError {
182    /// [`EbccCodec`] does not support the dtype
183    #[error("Ebcc does not support the dtype {0}")]
184    UnsupportedDtype(AnyArrayDType),
185    /// [`EbccCodec`] failed to encode the header
186    #[error("Ebcc failed to encode the header")]
187    HeaderEncodeFailed {
188        /// Opaque source error
189        source: EbccHeaderError,
190    },
191    /// [`EbccCodec`] can only encode >2D data where the last two dimensions
192    /// must be at least 32x32 but received an array with an insufficient shape
193    #[error(
194        "Ebcc can only encode >2D data where the last two dimensions must be at least 32x32 but received an array of shape {shape:?}"
195    )]
196    InsufficientDimensions {
197        /// The unexpected shape of the array
198        shape: Vec<usize>,
199    },
200    /// [`EbccCodec`] failed to encode the data
201    #[error("Ebcc failed to encode the data")]
202    EbccEncodeFailed {
203        /// Opaque source error
204        source: EbccCodingError,
205    },
206    /// [`EbccCodec`] failed to encode a 3D slice
207    #[error("Ebcc failed to encode a 3D slice")]
208    SliceEncodeFailed {
209        /// Opaque source error
210        source: EbccSliceError,
211    },
212    /// [`EbccCodec`] can only decode one-dimensional byte arrays but received
213    /// an array of a different dtype
214    #[error(
215        "Ebcc can only decode one-dimensional byte arrays but received an array of dtype {dtype}"
216    )]
217    EncodedDataNotBytes {
218        /// The unexpected dtype of the encoded array
219        dtype: AnyArrayDType,
220    },
221    /// [`EbccCodec`] can only decode one-dimensional byte arrays but received
222    /// an array of a different shape
223    #[error(
224        "Ebcc can only decode one-dimensional byte arrays but received a byte array of shape {shape:?}"
225    )]
226    EncodedDataNotOneDimensional {
227        /// The unexpected shape of the encoded array
228        shape: Vec<usize>,
229    },
230    /// [`EbccCodec`] failed to decode the header
231    #[error("Ebcc failed to decode the header")]
232    HeaderDecodeFailed {
233        /// Opaque source error
234        source: EbccHeaderError,
235    },
236    /// [`EbccCodec`] cannot decode into an array with a mismatching shape
237    #[error("Ebcc cannot decode an array of shape {decoded:?} into an array of shape {array:?}")]
238    DecodeIntoShapeMismatch {
239        /// The shape of the decoded data
240        decoded: Vec<usize>,
241        /// The mismatching shape of the array to decode into
242        array: Vec<usize>,
243    },
244    /// [`EbccCodec`] failed to decode a 3D slice
245    #[error("Ebcc failed to decode a slice")]
246    SliceDecodeFailed {
247        /// Opaque source error
248        source: EbccSliceError,
249    },
250    /// [`EbccCodec`] failed to decode from an excessive number of slices
251    #[error("Ebcc failed to decode from an excessive number of slices")]
252    DecodeTooManySlices,
253    /// [`EbccCodec`] failed to decode the data
254    #[error("Ebcc failed to decode the data")]
255    EbccDecodeFailed {
256        /// Opaque source error
257        source: EbccCodingError,
258    },
259}
260
261#[expect(clippy::derive_partial_eq_without_eq)] // floats are not Eq
262#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Hash)]
263/// Positive floating point number
264pub struct Positive<T: Float>(T);
265
266impl<T: Float> PartialEq<T> for Positive<T> {
267    fn eq(&self, other: &T) -> bool {
268        self.0 == *other
269    }
270}
271
272impl Serialize for Positive<f32> {
273    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
274        serializer.serialize_f32(self.0)
275    }
276}
277
278impl<'de> Deserialize<'de> for Positive<f32> {
279    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
280        let x = f32::deserialize(deserializer)?;
281
282        if x > 0.0 {
283            Ok(Self(x))
284        } else {
285            Err(serde::de::Error::invalid_value(
286                serde::de::Unexpected::Float(f64::from(x)),
287                &"a positive value",
288            ))
289        }
290    }
291}
292
293impl JsonSchema for Positive<f32> {
294    fn inline_schema() -> bool {
295        true
296    }
297
298    fn schema_name() -> Cow<'static, str> {
299        Cow::Borrowed("PositiveF32")
300    }
301
302    fn schema_id() -> Cow<'static, str> {
303        Cow::Borrowed(concat!(module_path!(), "::", "Positive<f32>"))
304    }
305
306    fn json_schema(_gen: &mut SchemaGenerator) -> Schema {
307        json_schema!({
308            "type": "number",
309            "exclusiveMinimum": 0.0
310        })
311    }
312}
313
314#[derive(Debug, Error)]
315#[error(transparent)]
316/// Opaque error for when encoding or decoding the header fails
317pub struct EbccHeaderError(postcard::Error);
318
319#[derive(Debug, Error)]
320#[error(transparent)]
321/// Opaque error for when encoding or decoding a 3D slice fails
322pub struct EbccSliceError(postcard::Error);
323
324#[derive(Debug, Error)]
325#[error(transparent)]
326/// Opaque error for when encoding or decoding with EBCC fails
327pub struct EbccCodingError(ebcc::EBCCError);
328
329/// Compress the `data` array using EBCC with the provided `residual` and
330/// `base_cr`. The `data` is internally chunked using the `chunk_shape`.
331///
332/// # Errors
333///
334/// Errors with
335/// - [`EbccCodecError::HeaderEncodeFailed`] if encoding the header failed
336/// - [`EbccCodecError::InsufficientDimensions`] if the `data` has fewer than
337///   two dimensions or the last two dimensions are not at least 32x32
338/// - [`EbccCodecError::EbccEncodeFailed`] if encoding with EBCC failed
339/// - [`EbccCodecError::SliceEncodeFailed`] if encoding a 3D slice failed
340#[expect(clippy::missing_panics_doc)]
341pub fn compress<S: Data<Elem = f32>, D: Dimension>(
342    data: ArrayBase<S, D>,
343    residual: EbccResidualType,
344    base_cr: Positive<f32>,
345    chunk_shape: EbccChunkShape,
346) -> Result<Vec<u8>, EbccCodecError> {
347    let mut encoded = postcard::to_extend(
348        &CompressionHeader {
349            dtype: EbccDType::F32,
350            shape: Cow::Borrowed(data.shape()),
351            version: StaticCodecVersion,
352        },
353        Vec::new(),
354    )
355    .map_err(|err| EbccCodecError::HeaderEncodeFailed {
356        source: EbccHeaderError(err),
357    })?;
358
359    // EBCC cannot handle zero-length dimensions
360    if data.is_empty() {
361        return Ok(encoded);
362    }
363
364    let mut chunk_size = Vec::from(data.shape());
365    let (width, height, depth) = match *chunk_size.as_mut_slice() {
366        [ref mut rest @ .., depth, height, width] => {
367            for r in rest {
368                *r = 1;
369            }
370            (width, height, depth)
371        }
372        [height, width] => (width, height, 1),
373        _ => {
374            return Err(EbccCodecError::InsufficientDimensions {
375                shape: Vec::from(data.shape()),
376            });
377        }
378    };
379
380    if (width < 32) || (height < 32) {
381        return Err(EbccCodecError::InsufficientDimensions {
382            shape: Vec::from(data.shape()),
383        });
384    }
385
386    for mut slice in data.into_dyn().exact_chunks(chunk_size.as_slice()) {
387        while slice.ndim() < 3 {
388            slice = slice.insert_axis(Axis(0));
389        }
390        #[expect(clippy::unwrap_used)]
391        // slice must now have at least three axes, and all but the last three
392        //  must be of size 1
393        let slice = slice.into_shape_with_order((depth, height, width)).unwrap();
394
395        let encoded_slice = ebcc::ebcc_encode_chunking_compat(
396            slice,
397            &ebcc::EBCCConfig {
398                base_cr: base_cr.0,
399                residual_compression_type: match residual {
400                    EbccResidualType::Jpeg2000Only => ebcc::EBCCResidualType::Jpeg2000Only,
401                    EbccResidualType::AbsoluteError { error } => {
402                        ebcc::EBCCResidualType::AbsoluteError(error.0)
403                    }
404                    EbccResidualType::RelativeError { error } => {
405                        ebcc::EBCCResidualType::RelativeError(error.0)
406                    }
407                },
408            },
409            match chunk_shape {
410                EbccChunkShape::Auto => ebcc::EBCCCompatChunkShape::Auto,
411                EbccChunkShape::Explicit(chunk_shape) => {
412                    ebcc::EBCCCompatChunkShape::Explicit(chunk_shape)
413                }
414            },
415        )
416        .map_err(|err| EbccCodecError::EbccEncodeFailed {
417            source: EbccCodingError(err),
418        })?;
419
420        encoded = postcard::to_extend(encoded_slice.as_slice(), encoded).map_err(|err| {
421            EbccCodecError::SliceEncodeFailed {
422                source: EbccSliceError(err),
423            }
424        })?;
425    }
426
427    Ok(encoded)
428}
429
430/// Decompress the `encoded` data into an array using EBCC.
431///
432/// # Errors
433///
434/// Errors with
435/// - [`EbccCodecError::HeaderDecodeFailed`] if decoding the header failed
436/// - [`EbccCodecError::SliceDecodeFailed`] if decoding a 3D slice failed
437/// - [`EbccCodecError::EbccDecodeFailed`] if decoding with EBCC failed
438/// - [`EbccCodecError::DecodeTooManySlices`] if the encoded data contains
439///   too many slices
440pub fn decompress(encoded: &[u8]) -> Result<AnyArray, EbccCodecError> {
441    fn decompress_typed(
442        encoded: &[u8],
443        shape: &[usize],
444    ) -> Result<Array<f32, IxDyn>, EbccCodecError> {
445        let mut decoded = Array::<f32, _>::zeros(shape);
446        decompress_into_typed(encoded, decoded.view_mut())?;
447        Ok(decoded)
448    }
449
450    let (header, encoded) =
451        postcard::take_from_bytes::<CompressionHeader>(encoded).map_err(|err| {
452            EbccCodecError::HeaderDecodeFailed {
453                source: EbccHeaderError(err),
454            }
455        })?;
456
457    // Return empty data for zero-size arrays
458    if header.shape.iter().copied().any(|s| s == 0) {
459        return match header.dtype {
460            EbccDType::F32 => Ok(AnyArray::F32(Array::zeros(&*header.shape))),
461        };
462    }
463
464    match header.dtype {
465        EbccDType::F32 => Ok(AnyArray::F32(decompress_typed(encoded, &header.shape)?)),
466    }
467}
468
469/// Decompress the `encoded` data into the `decoded` array using EBCC.
470///
471/// # Errors
472///
473/// Errors with
474/// - [`EbccCodecError::HeaderDecodeFailed`] if decoding the header failed
475/// - [`EbccCodecError::DecodeIntoShapeMismatch`] is the `decoded` array shape
476///   does not match the shape of the decoded data
477/// - [`EbccCodecError::SliceDecodeFailed`] if decoding a 3D slice failed
478/// - [`EbccCodecError::EbccDecodeFailed`] if decoding with EBCC failed
479/// - [`EbccCodecError::DecodeTooManySlices`] if the encoded data contains
480///   too many slices
481pub fn decompress_into<S: DataMut<Elem = f32>, D: Dimension>(
482    encoded: &[u8],
483    decoded: ArrayBase<S, D>,
484) -> Result<(), EbccCodecError> {
485    let (header, encoded) =
486        postcard::take_from_bytes::<CompressionHeader>(encoded).map_err(|err| {
487            EbccCodecError::HeaderDecodeFailed {
488                source: EbccHeaderError(err),
489            }
490        })?;
491
492    if decoded.shape() != &*header.shape {
493        return Err(EbccCodecError::DecodeIntoShapeMismatch {
494            decoded: header.shape.into_owned(),
495            array: Vec::from(decoded.shape()),
496        });
497    }
498
499    // Return empty data for zero-size arrays
500    if header.shape.iter().copied().any(|s| s == 0) {
501        return match header.dtype {
502            EbccDType::F32 => Ok(()),
503        };
504    }
505
506    match header.dtype {
507        EbccDType::F32 => decompress_into_typed(encoded, decoded.into_dyn().view_mut()),
508    }
509}
510
511fn decompress_into_typed(
512    mut encoded: &[u8],
513    mut decoded: ArrayViewMut<f32, IxDyn>,
514) -> Result<(), EbccCodecError> {
515    let mut chunk_size = Vec::from(decoded.shape());
516    let (width, height, depth) = match *chunk_size.as_mut_slice() {
517        [ref mut rest @ .., depth, height, width] => {
518            for r in rest {
519                *r = 1;
520            }
521            (width, height, depth)
522        }
523        [height, width] => (width, height, 1),
524        [width] => (width, 1, 1),
525        [] => (1, 1, 1),
526    };
527
528    for mut slice in decoded.exact_chunks_mut(chunk_size.as_slice()) {
529        let (encoded_slice, rest) =
530            postcard::take_from_bytes::<Cow<[u8]>>(encoded).map_err(|err| {
531                EbccCodecError::SliceDecodeFailed {
532                    source: EbccSliceError(err),
533                }
534            })?;
535        encoded = rest;
536
537        while slice.ndim() < 3 {
538            slice = slice.insert_axis(Axis(0));
539        }
540        #[expect(clippy::unwrap_used)]
541        // slice must now have at least three axes, and all but the last
542        //  three must be of size 1
543        let slice = slice.into_shape_with_order((depth, height, width)).unwrap();
544
545        ebcc::ebcc_decode_chunking_into(&encoded_slice, slice).map_err(|err| {
546            EbccCodecError::EbccDecodeFailed {
547                source: EbccCodingError(err),
548            }
549        })?;
550    }
551
552    if !encoded.is_empty() {
553        return Err(EbccCodecError::DecodeTooManySlices);
554    }
555
556    Ok(())
557}
558
559#[derive(Serialize, Deserialize)]
560struct CompressionHeader<'a> {
561    dtype: EbccDType,
562    #[serde(borrow)]
563    shape: Cow<'a, [usize]>,
564    version: EbccCodecVersion,
565}
566
567/// Dtypes that EBCC can compress and decompress
568#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
569enum EbccDType {
570    #[serde(rename = "f32", alias = "float32")]
571    F32,
572}
573
574#[cfg(test)]
575mod tests {
576    use super::*;
577
578    #[test]
579    fn test_unsupported_dtype() {
580        let codec = EbccCodec {
581            residual: EbccResidualType::Jpeg2000Only,
582            base_cr: Positive(10.0),
583            version: StaticCodecVersion,
584            chunk_shape: EbccChunkShape::Auto,
585        };
586
587        let data = Array1::<i32>::zeros(100);
588        let result = codec.encode(AnyCowArray::I32(data.into_dyn().into()));
589
590        assert!(matches!(result, Err(EbccCodecError::UnsupportedDtype(_))));
591    }
592
593    #[test]
594    fn test_invalid_dimensions() {
595        let codec = EbccCodec {
596            residual: EbccResidualType::Jpeg2000Only,
597            base_cr: Positive(10.0),
598            version: StaticCodecVersion,
599            chunk_shape: EbccChunkShape::Auto,
600        };
601
602        // Test dimensions too small (32 < 32x32 requirement)
603        let data = Array::zeros(32);
604        let result = codec.encode(AnyCowArray::F32(data.into_dyn().into()));
605        assert!(
606            matches!(result, Err(EbccCodecError::InsufficientDimensions { shape }) if shape == [32])
607        );
608
609        // Test dimensions too small (16x16 < 32x32 requirement)
610        let data = Array::zeros((16, 16));
611        let result = codec.encode(AnyCowArray::F32(data.into_dyn().into()));
612        assert!(
613            matches!(result, Err(EbccCodecError::InsufficientDimensions { shape }) if shape == [16, 16])
614        );
615
616        // Test mixed valid/invalid dimensions
617        let data = Array::zeros((1, 32, 16));
618        let result = codec.encode(AnyCowArray::F32(data.into_dyn().into()));
619        assert!(
620            matches!(result, Err(EbccCodecError::InsufficientDimensions { shape }) if shape == [1, 32, 16])
621        );
622
623        // Test valid dimensions
624        let data = Array::zeros((1, 32, 32));
625        let result = codec.encode(AnyCowArray::F32(data.into_dyn().into()));
626        assert!(result.is_ok());
627
628        // Test valid dimensions with slicing
629        let data = Array::zeros((2, 2, 2, 32, 32));
630        let result = codec.encode(AnyCowArray::F32(data.into_dyn().into()));
631        assert!(result.is_ok());
632    }
633
634    #[test]
635    fn test_large_array() -> Result<(), EbccCodecError> {
636        // Test with a larger array (similar to small climate dataset)
637        let height = 721; // Quarter degree resolution
638        let width = 1440;
639        let frames = 1;
640
641        #[expect(clippy::suboptimal_flops, clippy::cast_precision_loss)]
642        let data = Array::from_shape_fn((frames, height, width), |(_k, i, j)| {
643            let lat = -90.0 + (i as f32 / height as f32) * 180.0;
644            let lon = -180.0 + (j as f32 / width as f32) * 360.0;
645            #[allow(clippy::let_and_return)]
646            let temp = 273.15 + 30.0 * (1.0 - lat.abs() / 90.0) + 5.0 * (lon / 180.0).sin();
647            temp
648        });
649
650        let codec_error = 0.1;
651        let codec = EbccCodec {
652            residual: EbccResidualType::AbsoluteError {
653                error: Positive(codec_error),
654            },
655            base_cr: Positive(20.0),
656            version: StaticCodecVersion,
657            chunk_shape: EbccChunkShape::Auto,
658        };
659
660        let encoded = codec.encode(AnyArray::F32(data.clone().into_dyn()).into_cow())?;
661        let decoded = codec.decode(encoded.cow())?;
662
663        let AnyArray::U8(encoded) = encoded else {
664            return Err(EbccCodecError::EncodedDataNotBytes {
665                dtype: encoded.dtype(),
666            });
667        };
668
669        let AnyArray::F32(decoded) = decoded else {
670            return Err(EbccCodecError::UnsupportedDtype(decoded.dtype()));
671        };
672
673        // Check compression ratio
674        let original_size = data.len() * std::mem::size_of::<f32>();
675        #[expect(clippy::cast_precision_loss)]
676        let compression_ratio = original_size as f64 / encoded.len() as f64;
677
678        assert!(
679            compression_ratio > 5.0,
680            "Compression ratio {compression_ratio} should be at least 5:1",
681        );
682
683        // Check error bound is respected
684        let max_error = data
685            .iter()
686            .zip(decoded.iter())
687            .map(|(&orig, &decomp)| (orig - decomp).abs())
688            .fold(0.0f32, f32::max);
689
690        assert!(
691            max_error <= (codec_error + 1e-6),
692            "Max error {max_error} exceeds error bound {codec_error}",
693        );
694
695        Ok(())
696    }
697
698    #[test]
699    fn test_huge_array() -> Result<(), EbccCodecError> {
700        // Test with a huge array that would require chunking
701        let height = 721 * 2; // Quarter degree resolution
702        let width = 1440 * 2;
703        let frames = 2;
704
705        #[expect(clippy::suboptimal_flops, clippy::cast_precision_loss)]
706        let data = Array::from_shape_fn((frames, height, width), |(_k, i, j)| {
707            let lat = -90.0 + (i as f32 / height as f32) * 180.0;
708            let lon = -180.0 + (j as f32 / width as f32) * 360.0;
709            #[allow(clippy::let_and_return)]
710            let temp = 273.15 + 30.0 * (1.0 - lat.abs() / 90.0) + 5.0 * (lon / 180.0).sin();
711            temp
712        });
713
714        let codec_error = 0.1;
715        let codec = EbccCodec {
716            residual: EbccResidualType::AbsoluteError {
717                error: Positive(codec_error),
718            },
719            base_cr: Positive(20.0),
720            version: StaticCodecVersion,
721            chunk_shape: EbccChunkShape::Auto,
722        };
723
724        let encoded = codec.encode(AnyArray::F32(data.clone().into_dyn()).into_cow())?;
725        let decoded = codec.decode(encoded.cow())?;
726
727        let AnyArray::U8(encoded) = encoded else {
728            return Err(EbccCodecError::EncodedDataNotBytes {
729                dtype: encoded.dtype(),
730            });
731        };
732
733        let AnyArray::F32(decoded) = decoded else {
734            return Err(EbccCodecError::UnsupportedDtype(decoded.dtype()));
735        };
736
737        // Check compression ratio
738        let original_size = data.len() * std::mem::size_of::<f32>();
739        #[expect(clippy::cast_precision_loss)]
740        let compression_ratio = original_size as f64 / encoded.len() as f64;
741
742        assert!(
743            compression_ratio > 5.0,
744            "Compression ratio {compression_ratio} should be at least 5:1",
745        );
746
747        // Check error bound is respected
748        let max_error = data
749            .iter()
750            .zip(decoded.iter())
751            .map(|(&orig, &decomp)| (orig - decomp).abs())
752            .fold(0.0f32, f32::max);
753
754        assert!(
755            max_error <= (codec_error + 1e-6),
756            "Max error {max_error} exceeds error bound {codec_error}",
757        );
758
759        Ok(())
760    }
761}