vortex_alp/alp/
array.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
use std::fmt::{Debug, Display};
use std::sync::Arc;

use serde::{Deserialize, Serialize};
use vortex_array::array::visitor::{AcceptArrayVisitor, ArrayVisitor};
use vortex_array::array::PrimitiveArray;
use vortex_array::encoding::ids;
use vortex_array::iter::{Accessor, AccessorRef};
use vortex_array::stats::ArrayStatisticsCompute;
use vortex_array::validity::{ArrayValidity, LogicalValidity, Validity};
use vortex_array::variants::{ArrayVariants, PrimitiveArrayTrait};
use vortex_array::{
    impl_encoding, Array, ArrayDType, ArrayTrait, Canonical, IntoArray, IntoCanonical,
};
use vortex_dtype::{DType, PType};
use vortex_error::{vortex_bail, vortex_panic, VortexExpect as _, VortexResult};

use crate::alp::{alp_encode, decompress, Exponents};
use crate::ALPFloat;

impl_encoding!("vortex.alp", ids::ALP, ALP);

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ALPMetadata {
    exponents: Exponents,
}

impl Display for ALPMetadata {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(self, f)
    }
}

impl ALPArray {
    pub fn try_new(
        encoded: Array,
        exponents: Exponents,
        patches: Option<Array>,
    ) -> VortexResult<Self> {
        let dtype = match encoded.dtype() {
            DType::Primitive(PType::I32, nullability) => DType::Primitive(PType::F32, *nullability),
            DType::Primitive(PType::I64, nullability) => DType::Primitive(PType::F64, *nullability),
            d => vortex_bail!(MismatchedTypes: "int32 or int64", d),
        };

        let length = encoded.len();
        if let Some(parray) = patches.as_ref() {
            if parray.len() != length {
                vortex_bail!(
                    "Mismatched length in ALPArray between encoded({}) {} and it's patches({}) {}",
                    encoded.encoding().id(),
                    encoded.len(),
                    parray.encoding().id(),
                    parray.len()
                )
            }
        }

        let mut children = Vec::with_capacity(2);
        children.push(encoded);
        if let Some(patch) = patches {
            if !patch.dtype().eq_ignore_nullability(&dtype) || !patch.dtype().is_nullable() {
                vortex_bail!(
                    "ALP patches dtype, {}, must be nullable version of array dtype, {}",
                    patch.dtype(),
                    dtype,
                );
            }
            children.push(patch);
        }

        Self::try_from_parts(
            dtype,
            length,
            ALPMetadata { exponents },
            children.into(),
            Default::default(),
        )
    }

    pub fn encode(array: Array) -> VortexResult<Array> {
        if let Ok(parray) = PrimitiveArray::try_from(array) {
            Ok(alp_encode(&parray)?.into_array())
        } else {
            vortex_bail!("ALP can only encode primitive arrays");
        }
    }

    pub fn encoded(&self) -> Array {
        self.as_ref()
            .child(0, &self.encoded_dtype(), self.len())
            .vortex_expect("Missing encoded child in ALPArray")
    }

    #[inline]
    pub fn exponents(&self) -> Exponents {
        self.metadata().exponents
    }

    pub fn patches(&self) -> Option<Array> {
        (self.as_ref().nchildren() > 1).then(|| {
            self.as_ref()
                .child(1, &self.patches_dtype(), self.len())
                .vortex_expect("Missing patches child in ALPArray")
        })
    }

    #[inline]
    pub fn ptype(&self) -> PType {
        self.dtype()
            .try_into()
            .vortex_expect("Failed to convert DType to PType")
    }

    #[inline]
    fn encoded_dtype(&self) -> DType {
        match self.dtype() {
            DType::Primitive(PType::F32, _) => {
                DType::Primitive(PType::I32, self.dtype().nullability())
            }
            DType::Primitive(PType::F64, _) => {
                DType::Primitive(PType::I64, self.dtype().nullability())
            }
            d => vortex_panic!(MismatchedTypes: "f32 or f64", d),
        }
    }

    #[inline]
    fn patches_dtype(&self) -> DType {
        self.dtype().as_nullable()
    }
}

impl ArrayTrait for ALPArray {}

impl ArrayVariants for ALPArray {
    fn as_primitive_array(&self) -> Option<&dyn PrimitiveArrayTrait> {
        Some(self)
    }
}

struct ALPAccessor<F: ALPFloat> {
    encoded: Arc<dyn Accessor<F::ALPInt>>,
    patches: Option<Arc<dyn Accessor<F>>>,
    validity: Validity,
    exponents: Exponents,
}

impl<F: ALPFloat> ALPAccessor<F> {
    fn new(
        encoded: AccessorRef<F::ALPInt>,
        patches: Option<AccessorRef<F>>,
        exponents: Exponents,
        validity: Validity,
    ) -> Self {
        Self {
            encoded,
            patches,
            validity,
            exponents,
        }
    }
}

impl<F: ALPFloat> Accessor<F> for ALPAccessor<F> {
    fn array_len(&self) -> usize {
        self.encoded.array_len()
    }

    fn is_valid(&self, index: usize) -> bool {
        self.validity.is_valid(index)
    }

    fn value_unchecked(&self, index: usize) -> F {
        match self.patches.as_ref() {
            Some(patches) if patches.is_valid(index) => patches.value_unchecked(index),
            _ => {
                let encoded = self.encoded.value_unchecked(index);
                F::decode_single(encoded, self.exponents)
            }
        }
    }

    fn array_validity(&self) -> Validity {
        self.validity.clone()
    }

    fn decode_batch(&self, start_idx: usize) -> Vec<F> {
        let mut values = self
            .encoded
            .decode_batch(start_idx)
            .into_iter()
            .map(|v| F::decode_single(v, self.exponents))
            .collect::<Vec<F>>();

        if let Some(patches_accessor) = self.patches.as_ref() {
            for (index, item) in values.iter_mut().enumerate() {
                let index = index + start_idx;

                if patches_accessor.is_valid(index) {
                    *item = patches_accessor.value_unchecked(index);
                }
            }
        }

        values
    }
}

impl PrimitiveArrayTrait for ALPArray {
    fn f32_accessor(&self) -> Option<AccessorRef<f32>> {
        match self.dtype() {
            DType::Primitive(PType::F32, _) => {
                let patches = self
                    .patches()
                    .and_then(|p| p.with_dyn(|a| a.as_primitive_array_unchecked().f32_accessor()));

                let encoded = self
                    .encoded()
                    .with_dyn(|a| a.as_primitive_array_unchecked().i32_accessor())
                    .vortex_expect(
                        "Failed to get underlying encoded i32 array for ALP-encoded f32 array",
                    );

                Some(Arc::new(ALPAccessor::new(
                    encoded,
                    patches,
                    self.exponents(),
                    self.logical_validity().into_validity(),
                )))
            }
            _ => None,
        }
    }

    fn f64_accessor(&self) -> Option<AccessorRef<f64>> {
        match self.dtype() {
            DType::Primitive(PType::F64, _) => {
                let patches = self
                    .patches()
                    .and_then(|p| p.with_dyn(|a| a.as_primitive_array_unchecked().f64_accessor()));

                let encoded = self
                    .encoded()
                    .with_dyn(|a| a.as_primitive_array_unchecked().i64_accessor())
                    .vortex_expect(
                        "Failed to get underlying encoded i64 array for ALP-encoded f64 array",
                    );
                Some(Arc::new(ALPAccessor::new(
                    encoded,
                    patches,
                    self.exponents(),
                    self.logical_validity().into_validity(),
                )))
            }
            _ => None,
        }
    }
}

impl ArrayValidity for ALPArray {
    fn is_valid(&self, index: usize) -> bool {
        self.encoded().with_dyn(|a| a.is_valid(index))
    }

    fn logical_validity(&self) -> LogicalValidity {
        self.encoded().with_dyn(|a| a.logical_validity())
    }
}

impl IntoCanonical for ALPArray {
    fn into_canonical(self) -> VortexResult<Canonical> {
        decompress(self).map(Canonical::Primitive)
    }
}

impl AcceptArrayVisitor for ALPArray {
    fn accept(&self, visitor: &mut dyn ArrayVisitor) -> VortexResult<()> {
        visitor.visit_child("encoded", &self.encoded())?;
        if let Some(patches) = self.patches().as_ref() {
            visitor.visit_child("patches", patches)?;
        }
        Ok(())
    }
}

impl ArrayStatisticsCompute for ALPArray {}