1#![allow(clippy::multiple_crate_versions)] use std::borrow::Cow;
23
24use ndarray::Array1;
25use numcodecs::{
26 AnyArray, AnyArrayAssignError, AnyArrayDType, AnyArrayView, AnyArrayViewMut, AnyCowArray,
27 Codec, StaticCodec, StaticCodecConfig, StaticCodecVersion,
28};
29use schemars::{JsonSchema, JsonSchema_repr};
30use serde::{Deserialize, Deserializer, Serialize};
31use serde_repr::{Deserialize_repr, Serialize_repr};
32use thiserror::Error;
33
34#[cfg(test)]
35use ::serde_json as _;
36
37type LcCodecVersion = StaticCodecVersion<0, 1, 0>;
38
39#[derive(Clone, Serialize, Deserialize, JsonSchema)]
40#[serde(deny_unknown_fields)]
41pub struct LcCodec {
43 #[serde(default)]
45 pub preprocessors: Vec<LcPreprocessor>,
46 #[serde(deserialize_with = "deserialize_components")]
48 #[schemars(length(min = 1, max = lc_framework::MAX_COMPONENTS))]
49 pub components: Vec<LcComponent>,
50 #[serde(default, rename = "_version")]
52 pub version: LcCodecVersion,
53}
54
55fn deserialize_components<'de, D: Deserializer<'de>>(
56 deserializer: D,
57) -> Result<Vec<LcComponent>, D::Error> {
58 let components = Vec::<LcComponent>::deserialize(deserializer)?;
59
60 if components.is_empty() {
61 return Err(serde::de::Error::custom("expected at least one component"));
62 }
63
64 if components.len() > lc_framework::MAX_COMPONENTS {
65 return Err(serde::de::Error::custom(format_args!(
66 "expected at most {} components",
67 lc_framework::MAX_COMPONENTS
68 )));
69 }
70
71 Ok(components)
72}
73
74#[expect(missing_docs)]
75#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
76#[serde(deny_unknown_fields)]
77#[serde(tag = "id")]
78#[schemars(inline)]
79pub enum LcPreprocessor {
81 #[serde(rename = "NUL")]
82 Noop,
83 #[serde(rename = "LOR")]
84 Lorenzo1D { dtype: LcLorenzoDtype },
85 #[serde(rename = "QUANT")]
86 QuantizeErrorBound {
87 dtype: LcQuantizeDType,
88 kind: LcErrorKind,
89 error_bound: f64,
90 threshold: Option<f64>,
91 decorrelation: LcDecorrelation,
92 },
93}
94
95impl LcPreprocessor {
96 const fn into_lc(self) -> lc_framework::Preprocessor {
97 match self {
98 Self::Noop => lc_framework::Preprocessor::Noop,
99 Self::Lorenzo1D { dtype } => lc_framework::Preprocessor::Lorenzo1D {
100 dtype: dtype.into_lc(),
101 },
102 Self::QuantizeErrorBound {
103 dtype,
104 kind,
105 error_bound,
106 threshold,
107 decorrelation,
108 } => lc_framework::Preprocessor::QuantizeErrorBound {
109 dtype: dtype.into_lc(),
110 kind: kind.into_lc(),
111 error_bound,
112 threshold,
113 decorrelation: decorrelation.into_lc(),
114 },
115 }
116 }
117}
118
119#[derive(
120 Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
121)]
122#[schemars(inline)]
123pub enum LcErrorKind {
125 #[serde(rename = "ABS")]
127 Abs,
128 #[serde(rename = "NOA")]
130 Noa,
131 #[serde(rename = "REL")]
133 Rel,
134}
135
136impl LcErrorKind {
137 const fn into_lc(self) -> lc_framework::ErrorKind {
138 match self {
139 Self::Abs => lc_framework::ErrorKind::Abs,
140 Self::Noa => lc_framework::ErrorKind::Noa,
141 Self::Rel => lc_framework::ErrorKind::Rel,
142 }
143 }
144}
145
146#[expect(missing_docs)]
147#[derive(
148 Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
149)]
150#[schemars(inline)]
151pub enum LcDecorrelation {
153 #[serde(rename = "0")]
154 Zero,
155 #[serde(rename = "R")]
156 Random,
157}
158
159impl LcDecorrelation {
160 const fn into_lc(self) -> lc_framework::Decorrelation {
161 match self {
162 Self::Zero => lc_framework::Decorrelation::Zero,
163 Self::Random => lc_framework::Decorrelation::Random,
164 }
165 }
166}
167
168#[expect(missing_docs)]
169#[derive(
170 Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
171)]
172#[schemars(inline)]
173pub enum LcLorenzoDtype {
175 #[serde(rename = "i32")]
176 I32,
177}
178
179impl LcLorenzoDtype {
180 const fn into_lc(self) -> lc_framework::LorenzoDtype {
181 match self {
182 Self::I32 => lc_framework::LorenzoDtype::I32,
183 }
184 }
185}
186
187#[expect(missing_docs)]
188#[derive(
189 Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
190)]
191#[schemars(inline)]
192pub enum LcQuantizeDType {
194 #[serde(rename = "f32")]
195 F32,
196 #[serde(rename = "f64")]
197 F64,
198}
199
200impl LcQuantizeDType {
201 const fn into_lc(self) -> lc_framework::QuantizeDType {
202 match self {
203 Self::F32 => lc_framework::QuantizeDType::F32,
204 Self::F64 => lc_framework::QuantizeDType::F64,
205 }
206 }
207}
208
209#[expect(missing_docs)]
210#[derive(
211 Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
212)]
213#[serde(deny_unknown_fields)]
214#[serde(tag = "id")]
215#[schemars(inline)]
216pub enum LcComponent {
218 #[serde(rename = "NUL")]
219 Noop,
220 #[serde(rename = "TCMS")]
222 TwosComplementToSignMagnitude { size: LcElemSize },
223 #[serde(rename = "TCNB")]
224 TwosComplementToNegaBinary { size: LcElemSize },
225 #[serde(rename = "DBEFS")]
226 DebiasedExponentFractionSign { size: LcFloatSize },
227 #[serde(rename = "DBESF")]
228 DebiasedExponentSignFraction { size: LcFloatSize },
229 #[serde(rename = "BIT")]
231 BitShuffle { size: LcElemSize },
232 #[serde(rename = "TUPL")]
233 Tuple { size: LcTupleSize },
234 #[serde(rename = "DIFF")]
236 Delta { size: LcElemSize },
237 #[serde(rename = "DIFFMS")]
238 DeltaAsSignMagnitude { size: LcElemSize },
239 #[serde(rename = "DIFFNB")]
240 DeltaAsNegaBinary { size: LcElemSize },
241 #[serde(rename = "CLOG")]
243 Clog { size: LcElemSize },
244 #[serde(rename = "HCLOG")]
245 HClog { size: LcElemSize },
246 #[serde(rename = "RARE")]
247 Rare { size: LcElemSize },
248 #[serde(rename = "RAZE")]
249 Raze { size: LcElemSize },
250 #[serde(rename = "RLE")]
251 RunLengthEncoding { size: LcElemSize },
252 #[serde(rename = "RRE")]
253 RepetitionRunBitmapEncoding { size: LcElemSize },
254 #[serde(rename = "RZE")]
255 ZeroRunBitmapEncoding { size: LcElemSize },
256}
257
258impl LcComponent {
259 const fn into_lc(self) -> lc_framework::Component {
260 match self {
261 Self::Noop => lc_framework::Component::Noop,
262 Self::TwosComplementToSignMagnitude { size } => {
264 lc_framework::Component::TwosComplementToSignMagnitude {
265 size: size.into_lc(),
266 }
267 }
268 Self::TwosComplementToNegaBinary { size } => {
269 lc_framework::Component::TwosComplementToNegaBinary {
270 size: size.into_lc(),
271 }
272 }
273 Self::DebiasedExponentFractionSign { size } => {
274 lc_framework::Component::DebiasedExponentFractionSign {
275 size: size.into_lc(),
276 }
277 }
278 Self::DebiasedExponentSignFraction { size } => {
279 lc_framework::Component::DebiasedExponentSignFraction {
280 size: size.into_lc(),
281 }
282 }
283 Self::BitShuffle { size } => lc_framework::Component::BitShuffle {
285 size: size.into_lc(),
286 },
287 Self::Tuple { size } => lc_framework::Component::Tuple {
288 size: size.into_lc(),
289 },
290 Self::Delta { size } => lc_framework::Component::Delta {
292 size: size.into_lc(),
293 },
294 Self::DeltaAsSignMagnitude { size } => lc_framework::Component::DeltaAsSignMagnitude {
295 size: size.into_lc(),
296 },
297 Self::DeltaAsNegaBinary { size } => lc_framework::Component::DeltaAsNegaBinary {
298 size: size.into_lc(),
299 },
300 Self::Clog { size } => lc_framework::Component::Clog {
302 size: size.into_lc(),
303 },
304 Self::HClog { size } => lc_framework::Component::HClog {
305 size: size.into_lc(),
306 },
307 Self::Rare { size } => lc_framework::Component::Rare {
308 size: size.into_lc(),
309 },
310 Self::Raze { size } => lc_framework::Component::Raze {
311 size: size.into_lc(),
312 },
313 Self::RunLengthEncoding { size } => lc_framework::Component::RunLengthEncoding {
314 size: size.into_lc(),
315 },
316 Self::RepetitionRunBitmapEncoding { size } => {
317 lc_framework::Component::RepetitionRunBitmapEncoding {
318 size: size.into_lc(),
319 }
320 }
321 Self::ZeroRunBitmapEncoding { size } => {
322 lc_framework::Component::ZeroRunBitmapEncoding {
323 size: size.into_lc(),
324 }
325 }
326 }
327 }
328}
329
330#[expect(missing_docs)]
331#[derive(
332 Copy,
333 Clone,
334 Debug,
335 PartialEq,
336 Eq,
337 PartialOrd,
338 Ord,
339 Hash,
340 Serialize_repr,
341 Deserialize_repr,
342 JsonSchema_repr,
343)]
344#[repr(u8)]
346pub enum LcElemSize {
347 S1 = 1,
348 S2 = 2,
349 S4 = 4,
350 S8 = 8,
351}
352
353impl LcElemSize {
354 const fn into_lc(self) -> lc_framework::ElemSize {
355 match self {
356 Self::S1 => lc_framework::ElemSize::S1,
357 Self::S2 => lc_framework::ElemSize::S2,
358 Self::S4 => lc_framework::ElemSize::S4,
359 Self::S8 => lc_framework::ElemSize::S8,
360 }
361 }
362}
363
364#[expect(missing_docs)]
365#[derive(
366 Copy,
367 Clone,
368 Debug,
369 PartialEq,
370 Eq,
371 PartialOrd,
372 Ord,
373 Hash,
374 Serialize_repr,
375 Deserialize_repr,
376 JsonSchema_repr,
377)]
378#[repr(u8)]
380pub enum LcFloatSize {
381 S4 = 4,
382 S8 = 8,
383}
384
385impl LcFloatSize {
386 const fn into_lc(self) -> lc_framework::FloatSize {
387 match self {
388 Self::S4 => lc_framework::FloatSize::S4,
389 Self::S8 => lc_framework::FloatSize::S8,
390 }
391 }
392}
393
394#[expect(missing_docs)]
395#[derive(
396 Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
397)]
398#[schemars(description = "LC tuple component element size, in tuple length _ bytes")]
400pub enum LcTupleSize {
401 #[serde(rename = "2_1")]
402 S1x2,
403 #[serde(rename = "3_1")]
404 S1x3,
405 #[serde(rename = "4_1")]
406 S1x4,
407 #[serde(rename = "6_1")]
408 S1x6,
409 #[serde(rename = "8_1")]
410 S1x8,
411 #[serde(rename = "12_1")]
412 S1x12,
413 #[serde(rename = "2_2")]
414 S2x2,
415 #[serde(rename = "3_2")]
416 S2x3,
417 #[serde(rename = "4_2")]
418 S2x4,
419 #[serde(rename = "6_2")]
420 S2x6,
421 #[serde(rename = "2_4")]
422 S4x2,
423 #[serde(rename = "6_4")]
424 S4x6,
425 #[serde(rename = "3_8")]
426 S8x3,
427 #[serde(rename = "6_8")]
428 S8x6,
429}
430
431impl LcTupleSize {
432 const fn into_lc(self) -> lc_framework::TupleSize {
433 match self {
434 Self::S1x2 => lc_framework::TupleSize::S1x2,
435 Self::S1x3 => lc_framework::TupleSize::S1x3,
436 Self::S1x4 => lc_framework::TupleSize::S1x4,
437 Self::S1x6 => lc_framework::TupleSize::S1x6,
438 Self::S1x8 => lc_framework::TupleSize::S1x8,
439 Self::S1x12 => lc_framework::TupleSize::S1x12,
440 Self::S2x2 => lc_framework::TupleSize::S2x2,
441 Self::S2x3 => lc_framework::TupleSize::S2x3,
442 Self::S2x4 => lc_framework::TupleSize::S2x4,
443 Self::S2x6 => lc_framework::TupleSize::S2x6,
444 Self::S4x2 => lc_framework::TupleSize::S4x2,
445 Self::S4x6 => lc_framework::TupleSize::S4x6,
446 Self::S8x3 => lc_framework::TupleSize::S8x3,
447 Self::S8x6 => lc_framework::TupleSize::S8x6,
448 }
449 }
450}
451
452impl Codec for LcCodec {
453 type Error = LcCodecError;
454
455 fn encode(&self, data: AnyCowArray) -> Result<AnyArray, Self::Error> {
456 compress(data.view(), &self.preprocessors, &self.components)
457 .map(|bytes| AnyArray::U8(Array1::from_vec(bytes).into_dyn()))
458 }
459
460 fn decode(&self, encoded: AnyCowArray) -> Result<AnyArray, Self::Error> {
461 let AnyCowArray::U8(encoded) = encoded else {
462 return Err(LcCodecError::EncodedDataNotBytes {
463 dtype: encoded.dtype(),
464 });
465 };
466
467 if !matches!(encoded.shape(), [_]) {
468 return Err(LcCodecError::EncodedDataNotOneDimensional {
469 shape: encoded.shape().to_vec(),
470 });
471 }
472
473 decompress(
474 &self.preprocessors,
475 &self.components,
476 &AnyCowArray::U8(encoded).as_bytes(),
477 )
478 }
479
480 fn decode_into(
481 &self,
482 encoded: AnyArrayView,
483 decoded: AnyArrayViewMut,
484 ) -> Result<(), Self::Error> {
485 let AnyArrayView::U8(encoded) = encoded else {
486 return Err(LcCodecError::EncodedDataNotBytes {
487 dtype: encoded.dtype(),
488 });
489 };
490
491 if !matches!(encoded.shape(), [_]) {
492 return Err(LcCodecError::EncodedDataNotOneDimensional {
493 shape: encoded.shape().to_vec(),
494 });
495 }
496
497 decompress_into(
498 &self.preprocessors,
499 &self.components,
500 &AnyArrayView::U8(encoded).as_bytes(),
501 decoded,
502 )
503 }
504}
505
506impl StaticCodec for LcCodec {
507 const CODEC_ID: &'static str = "lc.rs";
508
509 type Config<'de> = Self;
510
511 fn from_config(config: Self::Config<'_>) -> Self {
512 config
513 }
514
515 fn get_config(&self) -> StaticCodecConfig<'_, Self> {
516 StaticCodecConfig::from(self)
517 }
518}
519
520#[derive(Debug, Error)]
521pub enum LcCodecError {
523 #[error("Lc failed to encode the header")]
525 HeaderEncodeFailed {
526 source: LcHeaderError,
528 },
529 #[error("Lc failed to decode the encoded data")]
531 LcEncodeFailed {
532 source: LcCodingError,
534 },
535 #[error(
538 "Lc can only decode one-dimensional byte arrays but received an array of dtype {dtype}"
539 )]
540 EncodedDataNotBytes {
541 dtype: AnyArrayDType,
543 },
544 #[error(
547 "Lc can only decode one-dimensional byte arrays but received a byte array of shape {shape:?}"
548 )]
549 EncodedDataNotOneDimensional {
550 shape: Vec<usize>,
552 },
553 #[error("Lc failed to decode the header")]
555 HeaderDecodeFailed {
556 source: LcHeaderError,
558 },
559 #[error("Lc decode produced a different number of bytes than expected")]
561 DecodeDataLengthMismatch,
562 #[error("Lc failed to decode the encoded data")]
564 LcDecodeFailed {
565 source: LcCodingError,
567 },
568 #[error("Lc cannot decode into the provided array")]
570 MismatchedDecodeIntoArray {
571 #[from]
573 source: AnyArrayAssignError,
574 },
575}
576
577#[derive(Debug, Error)]
578#[error(transparent)]
579pub struct LcHeaderError(postcard::Error);
581
582#[derive(Debug, Error)]
583#[error(transparent)]
584pub struct LcCodingError(lc_framework::Error);
586
587#[expect(clippy::needless_pass_by_value)]
588pub fn compress(
598 array: AnyArrayView,
599 preprocessors: &[LcPreprocessor],
600 components: &[LcComponent],
601) -> Result<Vec<u8>, LcCodecError> {
602 let mut encoded = postcard::to_extend(
603 &CompressionHeader {
604 dtype: array.dtype(),
605 shape: Cow::Borrowed(array.shape()),
606 version: StaticCodecVersion,
607 },
608 Vec::new(),
609 )
610 .map_err(|err| LcCodecError::HeaderEncodeFailed {
611 source: LcHeaderError(err),
612 })?;
613
614 if array.is_empty() {
616 return Ok(encoded);
617 }
618
619 let preprocessors = preprocessors
620 .iter()
621 .cloned()
622 .map(LcPreprocessor::into_lc)
623 .collect::<Vec<_>>();
624 let components = components
625 .iter()
626 .copied()
627 .map(LcComponent::into_lc)
628 .collect::<Vec<_>>();
629
630 encoded.append(
631 &mut lc_framework::compress(&preprocessors, &components, &array.as_bytes()).map_err(
632 |err| LcCodecError::LcEncodeFailed {
633 source: LcCodingError(err),
634 },
635 )?,
636 );
637
638 Ok(encoded)
639}
640
641pub fn decompress(
651 preprocessors: &[LcPreprocessor],
652 components: &[LcComponent],
653 encoded: &[u8],
654) -> Result<AnyArray, LcCodecError> {
655 let (header, encoded) =
656 postcard::take_from_bytes::<CompressionHeader>(encoded).map_err(|err| {
657 LcCodecError::HeaderDecodeFailed {
658 source: LcHeaderError(err),
659 }
660 })?;
661
662 let (decoded, result) = AnyArray::with_zeros_bytes(header.dtype, &header.shape, |decoded| {
663 decompress_into_bytes(preprocessors, components, encoded, decoded)
664 });
665
666 result.map(|()| decoded)
667}
668
669pub fn decompress_into(
682 preprocessors: &[LcPreprocessor],
683 components: &[LcComponent],
684 encoded: &[u8],
685 mut decoded: AnyArrayViewMut,
686) -> Result<(), LcCodecError> {
687 let (header, encoded) =
688 postcard::take_from_bytes::<CompressionHeader>(encoded).map_err(|err| {
689 LcCodecError::HeaderDecodeFailed {
690 source: LcHeaderError(err),
691 }
692 })?;
693
694 if header.dtype != decoded.dtype() {
695 return Err(LcCodecError::MismatchedDecodeIntoArray {
696 source: AnyArrayAssignError::DTypeMismatch {
697 src: header.dtype,
698 dst: decoded.dtype(),
699 },
700 });
701 }
702
703 if header.shape != decoded.shape() {
704 return Err(LcCodecError::MismatchedDecodeIntoArray {
705 source: AnyArrayAssignError::ShapeMismatch {
706 src: header.shape.into_owned(),
707 dst: decoded.shape().to_vec(),
708 },
709 });
710 }
711
712 decoded.with_bytes_mut(|decoded| {
713 decompress_into_bytes(preprocessors, components, encoded, decoded)
714 })
715}
716
717fn decompress_into_bytes(
718 preprocessors: &[LcPreprocessor],
719 components: &[LcComponent],
720 encoded: &[u8],
721 decoded: &mut [u8],
722) -> Result<(), LcCodecError> {
723 if decoded.is_empty() && encoded.is_empty() {
725 return Ok(());
726 }
727
728 let preprocessors = preprocessors
729 .iter()
730 .cloned()
731 .map(LcPreprocessor::into_lc)
732 .collect::<Vec<_>>();
733 let components = components
734 .iter()
735 .copied()
736 .map(LcComponent::into_lc)
737 .collect::<Vec<_>>();
738
739 let dec = lc_framework::decompress(&preprocessors, &components, encoded).map_err(|err| {
740 LcCodecError::LcDecodeFailed {
741 source: LcCodingError(err),
742 }
743 })?;
744
745 if dec.len() != decoded.len() {
746 return Err(LcCodecError::DecodeDataLengthMismatch);
747 }
748
749 decoded.copy_from_slice(&dec);
750
751 Ok(())
752}
753
754#[derive(Serialize, Deserialize)]
755struct CompressionHeader<'a> {
756 dtype: AnyArrayDType,
757 #[serde(borrow)]
758 shape: Cow<'a, [usize]>,
759 version: LcCodecVersion,
760}
761
762#[cfg(test)]
763#[expect(clippy::unwrap_used, clippy::panic)]
764mod tests {
765 use super::*;
766
767 #[test]
768 fn lossless() {
769 let data = ndarray::linspace(0.0, std::f32::consts::PI, 100)
770 .collect::<Array1<f32>>()
771 .into_shape_with_order((10, 10))
772 .unwrap()
773 .cos();
774
775 let preprocessors = &[];
776 let components = &[
777 LcComponent::BitShuffle {
778 size: LcElemSize::S4,
779 },
780 LcComponent::RunLengthEncoding {
781 size: LcElemSize::S4,
782 },
783 ];
784
785 let compressed = compress(
786 AnyArrayView::F32(data.view().into_dyn()),
787 preprocessors,
788 components,
789 )
790 .unwrap();
791 let decompressed = decompress(preprocessors, components, &compressed).unwrap();
792
793 assert_eq!(decompressed, AnyArray::F32(data.into_dyn()));
794 }
795
796 #[test]
797 fn abs_error() {
798 let data = ndarray::linspace(0.0, std::f32::consts::PI, 100)
799 .collect::<Array1<f32>>()
800 .into_shape_with_order((10, 10))
801 .unwrap()
802 .cos();
803
804 let preprocessors = &[LcPreprocessor::QuantizeErrorBound {
805 dtype: LcQuantizeDType::F32,
806 kind: LcErrorKind::Abs,
807 error_bound: 0.1,
808 threshold: None,
809 decorrelation: LcDecorrelation::Zero,
810 }];
811 let components = &[
812 LcComponent::BitShuffle {
813 size: LcElemSize::S4,
814 },
815 LcComponent::RunLengthEncoding {
816 size: LcElemSize::S4,
817 },
818 ];
819
820 let compressed = compress(
821 AnyArrayView::F32(data.view().into_dyn()),
822 preprocessors,
823 components,
824 )
825 .unwrap();
826 let decompressed = decompress(preprocessors, components, &compressed).unwrap();
827
828 let AnyArray::F32(decompressed) = decompressed else {
829 panic!("unexpected decompressed dtype {}", decompressed.dtype());
830 };
831 assert_eq!(decompressed.shape(), data.shape());
832
833 for (o, d) in data.into_iter().zip(decompressed) {
834 assert!((o - d).abs() <= 0.1);
835 }
836 }
837}