Skip to main content

vortex_array/arrays/piecewise_sequence/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Index encoding for concatenated sequential ranges.
5//!
6//! A `PiecewiseSequenceArray` represents the expanded index sequence
7//! `starts[i] + j * multipliers[i]` for `j` in `0..lengths[i]` for each piece `i`. It is
8//! intended for take operations that can gather regular runs without materializing one index per
9//! element.
10
11use itertools::Itertools;
12use num_traits::AsPrimitive;
13use vortex_buffer::Buffer;
14use vortex_buffer::BufferMut;
15use vortex_error::VortexExpect;
16use vortex_error::VortexResult;
17use vortex_error::vortex_bail;
18use vortex_error::vortex_ensure;
19use vortex_error::vortex_ensure_eq;
20use vortex_error::vortex_err;
21
22use crate::ArrayRef;
23use crate::Columnar;
24use crate::IntoArray;
25use crate::array::ArrayView;
26use crate::arrays::ConstantArray;
27use crate::arrays::Primitive;
28use crate::arrays::PrimitiveArray;
29use crate::arrays::piecewise_sequence::array::PiecewiseSequenceArraySlotsExt;
30use crate::dtype::UnsignedPType;
31use crate::executor::ExecutionCtx;
32use crate::scalar::PValue;
33use crate::validity::Validity;
34
35pub mod array;
36mod probe;
37mod vtable;
38
39#[cfg(test)]
40mod tests;
41
42pub use array::PiecewiseSequenceArrayExt;
43pub use vtable::*;
44
45pub(crate) fn check_index_arrays(
46    starts: &ArrayRef,
47    lengths: &ArrayRef,
48    multipliers: &ArrayRef,
49) -> VortexResult<()> {
50    check_index_array("starts", starts)?;
51    check_index_array("lengths", lengths)?;
52    check_index_array("multipliers", multipliers)?;
53    vortex_ensure_eq!(
54        starts.len(),
55        lengths.len(),
56        "PiecewiseSequenceArray starts length does not match lengths length",
57    );
58    vortex_ensure_eq!(
59        starts.len(),
60        multipliers.len(),
61        "PiecewiseSequenceArray starts length does not match multipliers length",
62    );
63    Ok(())
64}
65
66pub(crate) fn maybe_contiguous_slices(
67    array: ArrayView<'_, PiecewiseSequence>,
68    ctx: &mut ExecutionCtx,
69) -> VortexResult<Option<(PrimitiveArray, Columnar)>> {
70    if !is_constant_one(array.multipliers()) {
71        return Ok(None);
72    }
73
74    let starts = array.starts().clone().execute::<PrimitiveArray>(ctx)?;
75    let lengths = array.lengths().clone().execute::<Columnar>(ctx)?;
76    Ok(Some((starts, lengths)))
77}
78
79pub(crate) fn is_constant_one(multipliers: &ArrayRef) -> bool {
80    let Some(scalar) = multipliers.as_constant() else {
81        return false;
82    };
83    matches!(
84        scalar.as_primitive_opt().and_then(|scalar| scalar.pvalue()),
85        Some(PValue::U8(1) | PValue::U16(1) | PValue::U32(1) | PValue::U64(1))
86    )
87}
88
89pub(crate) fn constant_unsigned_usize(array: &ConstantArray) -> usize {
90    let pvalue = array
91        .scalar()
92        .as_primitive_opt()
93        .and_then(|scalar| scalar.pvalue())
94        .vortex_expect("validated PiecewiseSequence length constants are primitive");
95
96    match pvalue {
97        PValue::U8(value) => value as usize,
98        PValue::U16(value) => value as usize,
99        PValue::U32(value) => value as usize,
100        PValue::U64(value) => value.as_(),
101        _ => unreachable!("validated PiecewiseSequence length constants are unsigned"),
102    }
103}
104
105fn check_index_array(name: &str, array: &ArrayRef) -> VortexResult<()> {
106    vortex_ensure!(
107        array.dtype().is_unsigned_int(),
108        "PiecewiseSequenceArray {name} must have unsigned integer dtype, got {}",
109        array.dtype()
110    );
111    vortex_ensure!(
112        !array.dtype().is_nullable(),
113        "PiecewiseSequenceArray {name} must be non-nullable, got {}",
114        array.dtype()
115    );
116    Ok(())
117}
118
119pub(crate) fn materialize_ranges<S, L, M>(
120    starts: ArrayView<'_, Primitive>,
121    lengths: ArrayView<'_, Primitive>,
122    multipliers: ArrayView<'_, Primitive>,
123    output_len: usize,
124) -> VortexResult<BufferMut<u64>>
125where
126    S: UnsignedPType,
127    L: UnsignedPType,
128    M: UnsignedPType,
129{
130    let starts = starts.as_slice::<S>();
131    let lengths = lengths.as_slice::<L>();
132    let multipliers = multipliers.as_slice::<M>();
133    let mut values = BufferMut::with_capacity(output_len);
134    let mut computed_len = 0usize;
135
136    for ((&start, &length), &multiplier) in starts.iter().zip_eq(lengths).zip_eq(multipliers) {
137        let start: usize = start.as_();
138        let length: usize = length.as_();
139        let multiplier: usize = multiplier.as_();
140        if length != 0 {
141            let last_offset = length - 1;
142            let last_delta = last_offset
143                .checked_mul(multiplier)
144                .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?;
145            start
146                .checked_add(last_delta)
147                .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?;
148        }
149        computed_len = computed_len
150            .checked_add(length)
151            .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?;
152
153        values.extend((0..length).map(|offset| (start + offset * multiplier) as u64));
154    }
155
156    if computed_len != output_len {
157        vortex_bail!(
158            "PiecewiseSequenceArray expanded length {computed_len} does not match declared length {output_len}"
159        );
160    }
161    Ok(values)
162}
163
164/// Builds a `PiecewiseSequenceArray` of contiguous (unit multiplier) runs whose lengths sum to
165/// `total`.
166pub(crate) fn contiguous_runs(starts: Vec<u64>, lengths: Vec<u64>, total: usize) -> ArrayRef {
167    let count = starts.len();
168    debug_assert_eq!(count, lengths.len());
169    let starts = PrimitiveArray::new(Buffer::from(starts), Validity::NonNullable).into_array();
170    let lengths = match lengths.first() {
171        Some(&first) if lengths.iter().all(|&length| length == first) => {
172            ConstantArray::new(first, count).into_array()
173        }
174        _ => PrimitiveArray::new(Buffer::from(lengths), Validity::NonNullable).into_array(),
175    };
176    let multipliers = ConstantArray::new(1u64, count).into_array();
177    // SAFETY: starts, lengths, and multipliers are non-nullable u64 arrays of equal length, and
178    // `total` is the sum of the lengths.
179    unsafe { PiecewiseSequenceArray::new_unchecked(starts, lengths, multipliers, total) }
180        .into_array()
181}