vortex_sampling_compressor/compressors/
alp.rs

1use vortex_alp::{
2    alp_encode_components, match_each_alp_float_ptype, ALPArray, ALPEncoding, ALPRDEncoding,
3};
4use vortex_array::aliases::hash_set::HashSet;
5use vortex_array::array::PrimitiveArray;
6use vortex_array::variants::PrimitiveArrayTrait;
7use vortex_array::{Array, Encoding, EncodingId, IntoArray, IntoArrayVariant};
8use vortex_dtype::PType;
9use vortex_error::VortexResult;
10use vortex_fastlanes::BitPackedEncoding;
11
12use super::alp_rd::ALPRDCompressor;
13use crate::compressors::{CompressedArray, CompressionTree, EncodingCompressor};
14use crate::{constants, SamplingCompressor};
15
16#[derive(Debug)]
17pub struct ALPCompressor;
18
19impl EncodingCompressor for ALPCompressor {
20    fn id(&self) -> &str {
21        ALPEncoding::ID.as_ref()
22    }
23
24    fn cost(&self) -> u8 {
25        constants::ALP_COST
26    }
27
28    fn can_compress(&self, array: &Array) -> Option<&dyn EncodingCompressor> {
29        // Only support primitive arrays
30        let parray = PrimitiveArray::maybe_from(array)?;
31
32        // Only supports f32 and f64
33        if !matches!(parray.ptype(), PType::F32 | PType::F64) {
34            return None;
35        }
36
37        Some(self)
38    }
39
40    fn compress<'a>(
41        &'a self,
42        array: &Array,
43        like: Option<CompressionTree<'a>>,
44        ctx: SamplingCompressor<'a>,
45    ) -> VortexResult<CompressedArray<'a>> {
46        let parray = array.clone().into_primitive()?;
47
48        let (exponents, encoded, patches) = match_each_alp_float_ptype!(
49            parray.ptype(), |$T| {
50            alp_encode_components::<$T>(&parray, None)
51        });
52
53        let compressed_encoded = ctx
54            .named("packed")
55            .excluding(self)
56            .compress(&encoded, like.as_ref().and_then(|l| l.child(0)))?;
57
58        // Attempt to compress patches with ALP-RD encoding
59        let compressed_patches = patches
60            .map(|p| {
61                ctx.auxiliary("patches")
62                    .excluding(self)
63                    .including(&ALPRDCompressor)
64                    .compress_patches(p)
65            })
66            .transpose()?;
67
68        Ok(CompressedArray::compressed(
69            ALPArray::try_new(compressed_encoded.array, exponents, compressed_patches)?
70                .into_array(),
71            Some(CompressionTree::new(self, vec![compressed_encoded.path])),
72            array,
73        ))
74    }
75
76    fn used_encodings(&self) -> HashSet<EncodingId> {
77        HashSet::from([
78            ALPEncoding::ID,
79            // ALP-RD + BitPacking possibly used for patches
80            ALPRDEncoding::ID,
81            BitPackedEncoding::ID,
82        ])
83    }
84}