Skip to main content

vortex_array/arrays/chunked/compute/
take.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_buffer::BufferMut;
5use vortex_error::VortexResult;
6use vortex_mask::Mask;
7
8use crate::ArrayRef;
9use crate::Canonical;
10use crate::IntoArray;
11use crate::array::ArrayView;
12use crate::arrays::Chunked;
13use crate::arrays::ChunkedArray;
14use crate::arrays::PrimitiveArray;
15use crate::arrays::chunked::ChunkedArrayExt;
16use crate::arrays::dict::TakeExecute;
17use crate::builtins::ArrayBuiltins;
18use crate::dtype::DType;
19use crate::dtype::PType;
20use crate::executor::ExecutionCtx;
21use crate::validity::Validity;
22
23// TODO(joe): this is pretty unoptimized but better than before. We want canonical using a builder
24// we also want to return a chunked array ideally.
25fn take_chunked(
26    array: ArrayView<'_, Chunked>,
27    indices: &ArrayRef,
28    ctx: &mut ExecutionCtx,
29) -> VortexResult<ArrayRef> {
30    let indices = indices
31        .cast(DType::Primitive(PType::U64, indices.dtype().nullability()))?
32        .execute::<PrimitiveArray>(ctx)?;
33
34    let indices_mask = indices
35        .as_ref()
36        .validity()?
37        .execute_mask(indices.as_ref().len(), ctx)?;
38    let indices_values = indices.as_slice::<u64>();
39    let n = indices_values.len();
40
41    // 1. Sort (value, orig_pos) pairs so indices for the same chunk are contiguous.
42    //    Skip null indices — their final_take slots stay 0 and are masked null by validity.
43    let mut pairs: Vec<(u64, usize)> = indices_values
44        .iter()
45        .enumerate()
46        .filter(|&(i, _)| indices_mask.value(i))
47        .map(|(i, &v)| (v, i))
48        .collect();
49    pairs.sort_unstable();
50
51    // 2. Fused pass: walk sorted pairs against chunk boundaries.
52    //    - Dedup inline → build per-chunk filter masks
53    //    - Scatter final_take[orig_pos] = dedup_idx for every pair
54    let chunk_offsets = array.chunk_offsets();
55    let nchunks = array.nchunks();
56    let mut chunks = Vec::with_capacity(nchunks);
57    let mut final_take = BufferMut::<u64>::with_capacity(n);
58    final_take.push_n(0u64, n);
59
60    let mut cursor = 0usize;
61    let mut dedup_idx = 0u64;
62
63    for chunk_idx in 0..nchunks {
64        let chunk_start = chunk_offsets[chunk_idx];
65        let chunk_end = chunk_offsets[chunk_idx + 1];
66        let chunk_len = chunk_end - chunk_start;
67        let chunk_end_u64 = u64::try_from(chunk_end)?;
68
69        let range_end = cursor + pairs[cursor..].partition_point(|&(v, _)| v < chunk_end_u64);
70        let chunk_pairs = &pairs[cursor..range_end];
71
72        if !chunk_pairs.is_empty() {
73            let mut local_indices: Vec<usize> = Vec::new();
74            for (i, &(val, orig_pos)) in chunk_pairs.iter().enumerate() {
75                if cursor + i > 0 && val != pairs[cursor + i - 1].0 {
76                    dedup_idx += 1;
77                }
78                let local = usize::try_from(val)? - chunk_start;
79                if local_indices.last() != Some(&local) {
80                    local_indices.push(local);
81                }
82                final_take[orig_pos] = dedup_idx;
83            }
84
85            let filter_mask = Mask::from_indices(chunk_len, local_indices);
86            chunks.push(array.chunk(chunk_idx).filter(filter_mask)?);
87        }
88
89        cursor = range_end;
90    }
91
92    // SAFETY: every chunk came from a filter on a chunk with the same base dtype,
93    // unioned with the index nullability.
94    let flat = unsafe { ChunkedArray::new_unchecked(chunks, array.dtype().clone()) }
95        .into_array()
96        // TODO(joe): can we relax this.
97        .execute::<Canonical>(ctx)?
98        .into_array();
99
100    // 4. Single take to restore original order and expand duplicates.
101    //    Carry the original index validity so null indices produce null outputs.
102    let take_validity = Validity::from_mask(
103        indices
104            .as_ref()
105            .validity()?
106            .execute_mask(indices.as_ref().len(), ctx)?,
107        indices.dtype().nullability(),
108    );
109    flat.take(PrimitiveArray::new(final_take.freeze(), take_validity).into_array())
110}
111
112impl TakeExecute for Chunked {
113    fn take(
114        array: ArrayView<'_, Chunked>,
115        indices: &ArrayRef,
116        ctx: &mut ExecutionCtx,
117    ) -> VortexResult<Option<ArrayRef>> {
118        take_chunked(array, indices, ctx).map(Some)
119    }
120}
121
122#[cfg(test)]
123mod test {
124    use vortex_buffer::bitbuffer;
125    use vortex_buffer::buffer;
126    use vortex_error::VortexResult;
127
128    use crate::IntoArray;
129    #[expect(deprecated)]
130    use crate::ToCanonical as _;
131    use crate::arrays::BoolArray;
132    use crate::arrays::ChunkedArray;
133    use crate::arrays::PrimitiveArray;
134    use crate::arrays::StructArray;
135    use crate::arrays::chunked::ChunkedArrayExt;
136    use crate::assert_arrays_eq;
137    use crate::compute::conformance::take::test_take_conformance;
138    use crate::dtype::FieldNames;
139    use crate::dtype::Nullability;
140    use crate::validity::Validity;
141
142    #[test]
143    fn test_take() {
144        let a = buffer![1i32, 2, 3].into_array();
145        let arr = ChunkedArray::try_new(vec![a.clone(), a.clone(), a.clone()], a.dtype().clone())
146            .unwrap();
147        assert_eq!(arr.nchunks(), 3);
148        assert_eq!(arr.len(), 9);
149        let indices = buffer![0u64, 0, 6, 4].into_array();
150
151        let result = arr.take(indices).unwrap();
152        assert_arrays_eq!(result, PrimitiveArray::from_iter([1i32, 1, 1, 2]));
153    }
154
155    #[test]
156    fn test_take_nullable_values() {
157        let a = PrimitiveArray::new(buffer![1i32, 2, 3], Validity::AllValid).into_array();
158        let arr = ChunkedArray::try_new(vec![a.clone(), a.clone(), a.clone()], a.dtype().clone())
159            .unwrap();
160        assert_eq!(arr.nchunks(), 3);
161        assert_eq!(arr.len(), 9);
162        let indices = PrimitiveArray::new(buffer![0u64, 0, 6, 4], Validity::NonNullable);
163
164        let result = arr.take(indices.into_array()).unwrap();
165        assert_arrays_eq!(
166            result,
167            PrimitiveArray::from_option_iter([1i32, 1, 1, 2].map(Some))
168        );
169    }
170
171    #[test]
172    fn test_take_nullable_indices() {
173        let a = buffer![1i32, 2, 3].into_array();
174        let arr = ChunkedArray::try_new(vec![a.clone(), a.clone(), a.clone()], a.dtype().clone())
175            .unwrap();
176        assert_eq!(arr.nchunks(), 3);
177        assert_eq!(arr.len(), 9);
178        let indices = PrimitiveArray::new(
179            buffer![0u64, 0, 6, 4],
180            Validity::Array(bitbuffer![1 0 0 1].into_array()),
181        );
182
183        let result = arr.take(indices.into_array()).unwrap();
184        assert_arrays_eq!(
185            result,
186            PrimitiveArray::from_option_iter([Some(1i32), None, None, Some(2)])
187        );
188    }
189
190    #[test]
191    fn test_take_nullable_struct() {
192        let struct_array =
193            StructArray::try_new(FieldNames::default(), vec![], 100, Validity::NonNullable)
194                .unwrap();
195
196        let arr = ChunkedArray::from_iter(vec![
197            struct_array.clone().into_array(),
198            struct_array.into_array(),
199        ]);
200
201        let result = arr
202            .take(PrimitiveArray::from_option_iter(vec![Some(0), None, Some(101)]).into_array())
203            .unwrap();
204
205        let expect = StructArray::try_new(
206            FieldNames::default(),
207            vec![],
208            3,
209            Validity::Array(BoolArray::from_iter(vec![true, false, true]).into_array()),
210        )
211        .unwrap();
212        assert_arrays_eq!(result, expect);
213    }
214
215    #[test]
216    fn test_empty_take() {
217        let a = buffer![1i32, 2, 3].into_array();
218        let arr = ChunkedArray::try_new(vec![a.clone(), a.clone(), a.clone()], a.dtype().clone())
219            .unwrap();
220        assert_eq!(arr.nchunks(), 3);
221        assert_eq!(arr.len(), 9);
222
223        let indices = PrimitiveArray::empty::<u64>(Nullability::NonNullable);
224        let result = arr.take(indices.into_array()).unwrap();
225
226        assert!(result.is_empty());
227        assert_eq!(result.dtype(), arr.dtype());
228        assert_arrays_eq!(
229            result,
230            PrimitiveArray::empty::<i32>(Nullability::NonNullable)
231        );
232    }
233
234    #[test]
235    fn test_take_shuffled_indices() -> VortexResult<()> {
236        let c0 = buffer![0i32, 1, 2].into_array();
237        let c1 = buffer![3i32, 4, 5].into_array();
238        let c2 = buffer![6i32, 7, 8].into_array();
239        let arr = ChunkedArray::try_new(
240            vec![c0, c1, c2],
241            PrimitiveArray::empty::<i32>(Nullability::NonNullable)
242                .dtype()
243                .clone(),
244        )?;
245
246        // Fully shuffled indices that cross every chunk boundary.
247        let indices = buffer![8u64, 0, 5, 3, 2, 7, 1, 6, 4].into_array();
248        let result = arr.take(indices)?;
249
250        assert_arrays_eq!(
251            result,
252            PrimitiveArray::from_iter([8i32, 0, 5, 3, 2, 7, 1, 6, 4])
253        );
254        Ok(())
255    }
256
257    #[test]
258    fn test_take_shuffled_large() -> VortexResult<()> {
259        let nchunks: i32 = 100;
260        let chunk_len: i32 = 1_000;
261        let total = nchunks * chunk_len;
262
263        let chunks: Vec<_> = (0..nchunks)
264            .map(|c| {
265                let start = c * chunk_len;
266                PrimitiveArray::from_iter(start..start + chunk_len).into_array()
267            })
268            .collect();
269        let dtype = chunks[0].dtype().clone();
270        let arr = ChunkedArray::try_new(chunks, dtype)?;
271
272        // Fisher-Yates shuffle with a fixed seed for determinism.
273        let mut indices: Vec<u64> = (0..u64::try_from(total)?).collect();
274        let mut seed: u64 = 0xdeadbeef;
275        for i in (1..indices.len()).rev() {
276            seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
277            let j = (seed >> 33) as usize % (i + 1);
278            indices.swap(i, j);
279        }
280
281        let indices_arr = PrimitiveArray::new(
282            vortex_buffer::Buffer::from(indices.clone()),
283            Validity::NonNullable,
284        );
285        let result = arr.take(indices_arr.into_array())?;
286
287        // Verify every element.
288        #[expect(deprecated)]
289        let result = result.to_primitive();
290        let result_vals = result.as_slice::<i32>();
291        for (pos, &idx) in indices.iter().enumerate() {
292            assert_eq!(
293                result_vals[pos],
294                i32::try_from(idx)?,
295                "mismatch at position {pos}"
296            );
297        }
298        Ok(())
299    }
300
301    #[test]
302    fn test_take_null_indices() -> VortexResult<()> {
303        let c0 = buffer![10i32, 20, 30].into_array();
304        let c1 = buffer![40i32, 50, 60].into_array();
305        let arr = ChunkedArray::try_new(
306            vec![c0, c1],
307            PrimitiveArray::empty::<i32>(Nullability::NonNullable)
308                .dtype()
309                .clone(),
310        )?;
311
312        // Indices with nulls scattered across chunk boundaries.
313        let indices =
314            PrimitiveArray::from_option_iter([Some(5u64), None, Some(0), Some(3), None, Some(2)]);
315        let result = arr.take(indices.into_array())?;
316
317        assert_arrays_eq!(
318            result,
319            PrimitiveArray::from_option_iter([
320                Some(60i32),
321                None,
322                Some(10),
323                Some(40),
324                None,
325                Some(30)
326            ])
327        );
328        Ok(())
329    }
330
331    #[test]
332    fn test_take_chunked_conformance() {
333        let a = buffer![1i32, 2, 3].into_array();
334        let b = buffer![4i32, 5].into_array();
335        let arr = ChunkedArray::try_new(
336            vec![a, b],
337            PrimitiveArray::empty::<i32>(Nullability::NonNullable)
338                .dtype()
339                .clone(),
340        )
341        .unwrap();
342        test_take_conformance(&arr.into_array());
343
344        // Test with nullable chunked array
345        let a = PrimitiveArray::from_option_iter([Some(1i32), None, Some(3)]);
346        let b = PrimitiveArray::from_option_iter([Some(4i32), Some(5)]);
347        let dtype = a.dtype().clone();
348        let arr = ChunkedArray::try_new(vec![a.into_array(), b.into_array()], dtype).unwrap();
349        test_take_conformance(&arr.into_array());
350
351        // Test with multiple identical chunks
352        let chunk = buffer![10i32, 20, 30, 40, 50].into_array();
353        let arr = ChunkedArray::try_new(
354            vec![chunk.clone(), chunk.clone(), chunk.clone()],
355            chunk.dtype().clone(),
356        )
357        .unwrap();
358        test_take_conformance(&arr.into_array());
359    }
360}