vortex_sparse/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Debug;
5
6use itertools::Itertools as _;
7use num_traits::NumCast;
8use vortex_array::arrays::{BooleanBufferBuilder, ConstantArray};
9use vortex_array::compute::{Operator, compare, fill_null, filter, sub_scalar};
10use vortex_array::patches::Patches;
11use vortex_array::stats::{ArrayStats, StatsSetRef};
12use vortex_array::vtable::{ArrayVTable, NotSupported, VTable, ValidityVTable};
13use vortex_array::{Array, ArrayRef, EncodingId, EncodingRef, IntoArray, ToCanonical, vtable};
14use vortex_buffer::Buffer;
15use vortex_dtype::{DType, NativePType, Nullability, match_each_integer_ptype};
16use vortex_error::{VortexExpect as _, VortexResult, vortex_bail, vortex_ensure};
17use vortex_mask::{AllOr, Mask};
18use vortex_scalar::Scalar;
19
20mod canonical;
21mod compute;
22mod ops;
23mod serde;
24
25vtable!(Sparse);
26
27impl VTable for SparseVTable {
28    type Array = SparseArray;
29    type Encoding = SparseEncoding;
30
31    type ArrayVTable = Self;
32    type CanonicalVTable = Self;
33    type OperationsVTable = Self;
34    type ValidityVTable = Self;
35    type VisitorVTable = Self;
36    type ComputeVTable = NotSupported;
37    type EncodeVTable = Self;
38    type SerdeVTable = Self;
39    type PipelineVTable = NotSupported;
40
41    fn id(_encoding: &Self::Encoding) -> EncodingId {
42        EncodingId::new_ref("vortex.sparse")
43    }
44
45    fn encoding(_array: &Self::Array) -> EncodingRef {
46        EncodingRef::new_ref(SparseEncoding.as_ref())
47    }
48}
49
50#[derive(Clone, Debug)]
51pub struct SparseArray {
52    patches: Patches,
53    fill_value: Scalar,
54    stats_set: ArrayStats,
55}
56
57#[derive(Clone, Debug)]
58pub struct SparseEncoding;
59
60impl SparseArray {
61    pub fn try_new(
62        indices: ArrayRef,
63        values: ArrayRef,
64        len: usize,
65        fill_value: Scalar,
66    ) -> VortexResult<Self> {
67        vortex_ensure!(
68            indices.len() == values.len(),
69            "Mismatched indices {} and values {} length",
70            indices.len(),
71            values.len()
72        );
73
74        vortex_ensure!(
75            indices.statistics().compute_is_strict_sorted() == Some(true),
76            "SparseArray: indices must be strict-sorted"
77        );
78
79        // Verify the indices are all in the valid range
80        if !indices.is_empty() {
81            let last_index = usize::try_from(&indices.scalar_at(indices.len() - 1))?;
82
83            vortex_ensure!(
84                last_index < len,
85                "Array length was {len} but the last index is {last_index}"
86            );
87        }
88
89        let patches = Patches::new(len, 0, indices, values);
90
91        Ok(Self {
92            patches,
93            fill_value,
94            stats_set: Default::default(),
95        })
96    }
97
98    /// Build a new SparseArray from an existing set of patches.
99    pub fn try_new_from_patches(patches: Patches, fill_value: Scalar) -> VortexResult<Self> {
100        vortex_ensure!(
101            fill_value.dtype() == patches.values().dtype(),
102            "fill value, {:?}, should be instance of values dtype, {} but was {}.",
103            fill_value,
104            patches.values().dtype(),
105            fill_value.dtype(),
106        );
107
108        Ok(Self {
109            patches,
110            fill_value,
111            stats_set: Default::default(),
112        })
113    }
114
115    pub(crate) unsafe fn new_unchecked(patches: Patches, fill_value: Scalar) -> Self {
116        Self {
117            patches,
118            fill_value,
119            stats_set: Default::default(),
120        }
121    }
122
123    #[inline]
124    pub fn patches(&self) -> &Patches {
125        &self.patches
126    }
127
128    #[inline]
129    pub fn resolved_patches(&self) -> VortexResult<Patches> {
130        let patches = self.patches();
131        let indices_offset = Scalar::from(patches.offset()).cast(patches.indices().dtype())?;
132        let indices = sub_scalar(patches.indices(), indices_offset)?;
133        Ok(Patches::new(
134            patches.array_len(),
135            0,
136            indices,
137            patches.values().clone(),
138        ))
139    }
140
141    #[inline]
142    pub fn fill_scalar(&self) -> &Scalar {
143        &self.fill_value
144    }
145
146    /// Encode given array as a SparseArray.
147    ///
148    /// Optionally provided fill value will be respected if the array is less than 90% null.
149    pub fn encode(array: &dyn Array, fill_value: Option<Scalar>) -> VortexResult<ArrayRef> {
150        if let Some(fill_value) = fill_value.as_ref()
151            && array.dtype() != fill_value.dtype()
152        {
153            vortex_bail!(
154                "Array and fill value types must match. got {} and {}",
155                array.dtype(),
156                fill_value.dtype()
157            )
158        }
159        let mask = array.validity_mask();
160
161        if mask.all_false() {
162            // Array is constant NULL
163            return Ok(
164                ConstantArray::new(Scalar::null(array.dtype().clone()), array.len()).into_array(),
165            );
166        } else if mask.false_count() as f64 > (0.9 * mask.len() as f64) {
167            // Array is dominated by NULL but has non-NULL values
168            let non_null_values = filter(array, &mask)?;
169            let non_null_indices = match mask.indices() {
170                AllOr::All => {
171                    // We already know that the mask is 90%+ false
172                    unreachable!("Mask is mostly null")
173                }
174                AllOr::None => {
175                    // we know there are some non-NULL values
176                    unreachable!("Mask is mostly null but not all null")
177                }
178                AllOr::Some(values) => {
179                    let buffer: Buffer<u32> = values
180                        .iter()
181                        .map(|&v| v.try_into().vortex_expect("indices must fit in u32"))
182                        .collect();
183
184                    buffer.into_array()
185                }
186            };
187
188            return Ok(SparseArray::try_new(
189                non_null_indices,
190                non_null_values,
191                array.len(),
192                Scalar::null(array.dtype().clone()),
193            )?
194            .into_array());
195        }
196
197        let fill = if let Some(fill) = fill_value {
198            fill
199        } else {
200            // TODO(robert): Support other dtypes, only thing missing is getting most common value out of the array
201            let (top_pvalue, _) = array
202                .to_primitive()?
203                .top_value()?
204                .vortex_expect("Non empty or all null array");
205
206            Scalar::primitive_value(top_pvalue, top_pvalue.ptype(), array.dtype().nullability())
207        };
208
209        let fill_array = ConstantArray::new(fill.clone(), array.len()).into_array();
210        let non_top_mask = Mask::from_buffer(
211            fill_null(
212                &compare(array, &fill_array, Operator::NotEq)?,
213                &Scalar::bool(true, Nullability::NonNullable),
214            )?
215            .to_bool()?
216            .boolean_buffer()
217            .clone(),
218        );
219
220        let non_top_values = filter(array, &non_top_mask)?;
221
222        let indices: Buffer<u64> = match non_top_mask {
223            Mask::AllTrue(count) => {
224                // all true -> complete slice
225                (0u64..count as u64).collect()
226            }
227            Mask::AllFalse(_) => {
228                // All values are equal to the top value
229                return Ok(fill_array);
230            }
231            Mask::Values(values) => values.indices().iter().map(|v| *v as u64).collect(),
232        };
233
234        SparseArray::try_new(indices.into_array(), non_top_values, array.len(), fill)
235            .map(|a| a.into_array())
236    }
237}
238
239impl ArrayVTable<SparseVTable> for SparseVTable {
240    fn len(array: &SparseArray) -> usize {
241        array.patches.array_len()
242    }
243
244    fn dtype(array: &SparseArray) -> &DType {
245        array.fill_scalar().dtype()
246    }
247
248    fn stats(array: &SparseArray) -> StatsSetRef<'_> {
249        array.stats_set.to_ref(array.as_ref())
250    }
251}
252
253impl ValidityVTable<SparseVTable> for SparseVTable {
254    fn is_valid(array: &SparseArray, index: usize) -> bool {
255        match array.patches().get_patched(index) {
256            None => array.fill_scalar().is_valid(),
257            Some(patch_value) => patch_value.is_valid(),
258        }
259    }
260
261    fn all_valid(array: &SparseArray) -> bool {
262        if array.fill_scalar().is_null() {
263            // We need _all_ values to be patched, and all patches to be valid
264            return array.patches().values().len() == array.len()
265                && array.patches().values().all_valid();
266        }
267
268        array.patches().values().all_valid()
269    }
270
271    fn all_invalid(array: &SparseArray) -> bool {
272        if !array.fill_scalar().is_null() {
273            // We need _all_ values to be patched, and all patches to be invalid
274            return array.patches().values().len() == array.len()
275                && array.patches().values().all_invalid();
276        }
277
278        array.patches().values().all_invalid()
279    }
280
281    #[allow(clippy::unnecessary_fallible_conversions)]
282    fn validity_mask(array: &SparseArray) -> Mask {
283        let fill_is_valid = array.fill_scalar().is_valid();
284        let values_validity = array.patches().values().validity_mask();
285        let len = array.len();
286
287        if matches!(values_validity, Mask::AllTrue(_)) && fill_is_valid {
288            return Mask::AllTrue(len);
289        }
290        if matches!(values_validity, Mask::AllFalse(_)) && !fill_is_valid {
291            return Mask::AllFalse(len);
292        }
293
294        // TODO(ngates): use vortex-buffer::BitBufferMut when it exists.
295        let mut is_valid_buffer = BooleanBufferBuilder::new(len);
296        is_valid_buffer.append_n(len, fill_is_valid);
297
298        let indices = array
299            .patches()
300            .indices()
301            .to_primitive()
302            .vortex_expect("sparse indices must be primitive");
303        let index_offset = array.patches().offset();
304
305        match_each_integer_ptype!(indices.ptype(), |I| {
306            let indices = indices.as_slice::<I>();
307            patch_validity(&mut is_valid_buffer, indices, index_offset, values_validity);
308        });
309
310        Mask::from_buffer(is_valid_buffer.finish())
311    }
312}
313
314fn patch_validity<I: NativePType>(
315    is_valid_buffer: &mut BooleanBufferBuilder,
316    indices: &[I],
317    index_offset: usize,
318    values_validity: Mask,
319) {
320    let indices = indices.iter().map(|index| {
321        let index = <usize as NumCast>::from(*index).vortex_expect("Failed to cast to usize");
322        index - index_offset
323    });
324    match values_validity {
325        Mask::AllTrue(_) => {
326            for index in indices {
327                is_valid_buffer.set_bit(index, true);
328            }
329        }
330        Mask::AllFalse(_) => {
331            for index in indices {
332                is_valid_buffer.set_bit(index, false);
333            }
334        }
335        Mask::Values(mask_values) => {
336            let is_valid = mask_values.boolean_buffer().iter();
337            for (index, is_valid) in indices.zip_eq(is_valid) {
338                is_valid_buffer.set_bit(index, is_valid);
339            }
340        }
341    }
342}
343
344#[cfg(test)]
345mod test {
346    use itertools::Itertools;
347    use vortex_array::IntoArray;
348    use vortex_array::arrays::{ConstantArray, PrimitiveArray};
349    use vortex_array::compute::cast;
350    use vortex_array::validity::Validity;
351    use vortex_buffer::buffer;
352    use vortex_dtype::{DType, Nullability, PType};
353    use vortex_error::VortexUnwrap;
354    use vortex_scalar::{PrimitiveScalar, Scalar};
355
356    use super::*;
357
358    fn nullable_fill() -> Scalar {
359        Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable))
360    }
361
362    fn non_nullable_fill() -> Scalar {
363        Scalar::from(42i32)
364    }
365
366    fn sparse_array(fill_value: Scalar) -> ArrayRef {
367        // merged array: [null, null, 100, null, null, 200, null, null, 300, null]
368        let mut values = buffer![100i32, 200, 300].into_array();
369        values = cast(&values, fill_value.dtype()).unwrap();
370
371        SparseArray::try_new(buffer![2u64, 5, 8].into_array(), values, 10, fill_value)
372            .unwrap()
373            .into_array()
374    }
375
376    #[test]
377    pub fn test_scalar_at() {
378        let array = sparse_array(nullable_fill());
379
380        assert_eq!(array.scalar_at(0), nullable_fill());
381        assert_eq!(array.scalar_at(2), Scalar::from(Some(100_i32)));
382        assert_eq!(array.scalar_at(5), Scalar::from(Some(200_i32)));
383    }
384
385    #[test]
386    #[should_panic(expected = "out of bounds")]
387    fn test_scalar_at_oob() {
388        let array = sparse_array(nullable_fill());
389        let _ = array.scalar_at(10);
390    }
391
392    #[test]
393    pub fn test_scalar_at_again() {
394        let arr = SparseArray::try_new(
395            ConstantArray::new(10u32, 1).into_array(),
396            ConstantArray::new(Scalar::primitive(1234u32, Nullability::Nullable), 1).into_array(),
397            100,
398            Scalar::null(DType::Primitive(PType::U32, Nullability::Nullable)),
399        )
400        .unwrap();
401
402        assert_eq!(
403            PrimitiveScalar::try_from(&arr.scalar_at(10))
404                .unwrap()
405                .typed_value::<u32>(),
406            Some(1234)
407        );
408        assert!(arr.scalar_at(0).is_null());
409        assert!(arr.scalar_at(99).is_null());
410    }
411
412    #[test]
413    pub fn scalar_at_sliced() {
414        let sliced = sparse_array(nullable_fill()).slice(2..7);
415        assert_eq!(usize::try_from(&sliced.scalar_at(0)).unwrap(), 100);
416    }
417
418    #[test]
419    pub fn validity_mask_sliced_null_fill() {
420        let sliced = sparse_array(nullable_fill()).slice(2..7);
421        assert_eq!(
422            sliced.validity_mask(),
423            Mask::from_iter(vec![true, false, false, true, false])
424        );
425    }
426
427    #[test]
428    pub fn validity_mask_sliced_nonnull_fill() {
429        let sliced = SparseArray::try_new(
430            buffer![2u64, 5, 8].into_array(),
431            ConstantArray::new(
432                Scalar::null(DType::Primitive(PType::F32, Nullability::Nullable)),
433                3,
434            )
435            .into_array(),
436            10,
437            Scalar::primitive(1.0f32, Nullability::Nullable),
438        )
439        .unwrap()
440        .slice(2..7);
441
442        assert_eq!(
443            sliced.validity_mask(),
444            Mask::from_iter(vec![false, true, true, false, true])
445        );
446    }
447
448    #[test]
449    pub fn scalar_at_sliced_twice() {
450        let sliced_once = sparse_array(nullable_fill()).slice(1..8);
451        assert_eq!(usize::try_from(&sliced_once.scalar_at(1)).unwrap(), 100);
452
453        let sliced_twice = sliced_once.slice(1..6);
454        assert_eq!(usize::try_from(&sliced_twice.scalar_at(3)).unwrap(), 200);
455    }
456
457    #[test]
458    pub fn sparse_validity_mask() {
459        let array = sparse_array(nullable_fill());
460        assert_eq!(
461            array
462                .validity_mask()
463                .to_boolean_buffer()
464                .iter()
465                .collect_vec(),
466            [
467                false, false, true, false, false, true, false, false, true, false
468            ]
469        );
470    }
471
472    #[test]
473    fn sparse_validity_mask_non_null_fill() {
474        let array = sparse_array(non_nullable_fill());
475        assert!(array.validity_mask().all_true());
476    }
477
478    #[test]
479    #[should_panic]
480    fn test_invalid_length() {
481        let values = buffer![15_u32, 135, 13531, 42].into_array();
482        let indices = buffer![10_u64, 11, 50, 100].into_array();
483
484        SparseArray::try_new(indices, values, 100, 0_u32.into()).unwrap();
485    }
486
487    #[test]
488    fn test_valid_length() {
489        let values = buffer![15_u32, 135, 13531, 42].into_array();
490        let indices = buffer![10_u64, 11, 50, 100].into_array();
491
492        SparseArray::try_new(indices, values, 101, 0_u32.into()).unwrap();
493    }
494
495    #[test]
496    fn encode_with_nulls() {
497        let sparse = SparseArray::encode(
498            &PrimitiveArray::new(
499                buffer![0, 1, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4],
500                Validity::from_iter(vec![
501                    true, true, false, true, false, true, false, true, true, false, true, false,
502                ]),
503            )
504            .into_array(),
505            None,
506        )
507        .vortex_unwrap();
508        let canonical = sparse.to_primitive().vortex_unwrap();
509        assert_eq!(
510            sparse.validity_mask(),
511            Mask::from_iter(vec![
512                true, true, false, true, false, true, false, true, true, false, true, false,
513            ])
514        );
515        assert_eq!(
516            canonical.as_slice::<i32>(),
517            vec![0, 1, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4]
518        );
519    }
520
521    #[test]
522    fn validity_mask_includes_null_values_when_fill_is_null() {
523        let indices = buffer![0u8, 2, 4, 6, 8].into_array();
524        let values = PrimitiveArray::from_option_iter([Some(0i16), Some(1), None, None, Some(4)])
525            .into_array();
526        let array = SparseArray::try_new(indices, values, 10, Scalar::null_typed::<i16>()).unwrap();
527        let actual = array.validity_mask();
528        let expected = Mask::from_iter([
529            true, false, true, false, false, false, false, false, true, false,
530        ]);
531
532        assert_eq!(actual, expected);
533    }
534}