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        .to_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            .to_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    use crate::ToCanonical;
130    use crate::arrays::BoolArray;
131    use crate::arrays::ChunkedArray;
132    use crate::arrays::PrimitiveArray;
133    use crate::arrays::StructArray;
134    use crate::arrays::chunked::ChunkedArrayExt;
135    use crate::assert_arrays_eq;
136    use crate::compute::conformance::take::test_take_conformance;
137    use crate::dtype::FieldNames;
138    use crate::dtype::Nullability;
139    use crate::validity::Validity;
140
141    #[test]
142    fn test_take() {
143        let a = buffer![1i32, 2, 3].into_array();
144        let arr = ChunkedArray::try_new(vec![a.clone(), a.clone(), a.clone()], a.dtype().clone())
145            .unwrap();
146        assert_eq!(arr.nchunks(), 3);
147        assert_eq!(arr.len(), 9);
148        let indices = buffer![0u64, 0, 6, 4].into_array();
149
150        let result = arr.take(indices).unwrap();
151        assert_arrays_eq!(result, PrimitiveArray::from_iter([1i32, 1, 1, 2]));
152    }
153
154    #[test]
155    fn test_take_nullable_values() {
156        let a = PrimitiveArray::new(buffer![1i32, 2, 3], Validity::AllValid).into_array();
157        let arr = ChunkedArray::try_new(vec![a.clone(), a.clone(), a.clone()], a.dtype().clone())
158            .unwrap();
159        assert_eq!(arr.nchunks(), 3);
160        assert_eq!(arr.len(), 9);
161        let indices = PrimitiveArray::new(buffer![0u64, 0, 6, 4], Validity::NonNullable);
162
163        let result = arr.take(indices.into_array()).unwrap();
164        assert_arrays_eq!(
165            result,
166            PrimitiveArray::from_option_iter([1i32, 1, 1, 2].map(Some))
167        );
168    }
169
170    #[test]
171    fn test_take_nullable_indices() {
172        let a = buffer![1i32, 2, 3].into_array();
173        let arr = ChunkedArray::try_new(vec![a.clone(), a.clone(), a.clone()], a.dtype().clone())
174            .unwrap();
175        assert_eq!(arr.nchunks(), 3);
176        assert_eq!(arr.len(), 9);
177        let indices = PrimitiveArray::new(
178            buffer![0u64, 0, 6, 4],
179            Validity::Array(bitbuffer![1 0 0 1].into_array()),
180        );
181
182        let result = arr.take(indices.into_array()).unwrap();
183        assert_arrays_eq!(
184            result,
185            PrimitiveArray::from_option_iter([Some(1i32), None, None, Some(2)])
186        );
187    }
188
189    #[test]
190    fn test_take_nullable_struct() {
191        let struct_array =
192            StructArray::try_new(FieldNames::default(), vec![], 100, Validity::NonNullable)
193                .unwrap();
194
195        let arr = ChunkedArray::from_iter(vec![
196            struct_array.clone().into_array(),
197            struct_array.into_array(),
198        ]);
199
200        let result = arr
201            .take(PrimitiveArray::from_option_iter(vec![Some(0), None, Some(101)]).into_array())
202            .unwrap();
203
204        let expect = StructArray::try_new(
205            FieldNames::default(),
206            vec![],
207            3,
208            Validity::Array(BoolArray::from_iter(vec![true, false, true]).into_array()),
209        )
210        .unwrap();
211        assert_arrays_eq!(result, expect);
212    }
213
214    #[test]
215    fn test_empty_take() {
216        let a = buffer![1i32, 2, 3].into_array();
217        let arr = ChunkedArray::try_new(vec![a.clone(), a.clone(), a.clone()], a.dtype().clone())
218            .unwrap();
219        assert_eq!(arr.nchunks(), 3);
220        assert_eq!(arr.len(), 9);
221
222        let indices = PrimitiveArray::empty::<u64>(Nullability::NonNullable);
223        let result = arr.take(indices.into_array()).unwrap();
224
225        assert!(result.is_empty());
226        assert_eq!(result.dtype(), arr.dtype());
227        assert_arrays_eq!(
228            result,
229            PrimitiveArray::empty::<i32>(Nullability::NonNullable)
230        );
231    }
232
233    #[test]
234    fn test_take_shuffled_indices() -> VortexResult<()> {
235        let c0 = buffer![0i32, 1, 2].into_array();
236        let c1 = buffer![3i32, 4, 5].into_array();
237        let c2 = buffer![6i32, 7, 8].into_array();
238        let arr = ChunkedArray::try_new(
239            vec![c0, c1, c2],
240            PrimitiveArray::empty::<i32>(Nullability::NonNullable)
241                .dtype()
242                .clone(),
243        )?;
244
245        // Fully shuffled indices that cross every chunk boundary.
246        let indices = buffer![8u64, 0, 5, 3, 2, 7, 1, 6, 4].into_array();
247        let result = arr.take(indices)?;
248
249        assert_arrays_eq!(
250            result,
251            PrimitiveArray::from_iter([8i32, 0, 5, 3, 2, 7, 1, 6, 4])
252        );
253        Ok(())
254    }
255
256    #[test]
257    fn test_take_shuffled_large() -> VortexResult<()> {
258        let nchunks: i32 = 100;
259        let chunk_len: i32 = 1_000;
260        let total = nchunks * chunk_len;
261
262        let chunks: Vec<_> = (0..nchunks)
263            .map(|c| {
264                let start = c * chunk_len;
265                PrimitiveArray::from_iter(start..start + chunk_len).into_array()
266            })
267            .collect();
268        let dtype = chunks[0].dtype().clone();
269        let arr = ChunkedArray::try_new(chunks, dtype)?;
270
271        // Fisher-Yates shuffle with a fixed seed for determinism.
272        let mut indices: Vec<u64> = (0..u64::try_from(total)?).collect();
273        let mut seed: u64 = 0xdeadbeef;
274        for i in (1..indices.len()).rev() {
275            seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
276            let j = (seed >> 33) as usize % (i + 1);
277            indices.swap(i, j);
278        }
279
280        let indices_arr = PrimitiveArray::new(
281            vortex_buffer::Buffer::from(indices.clone()),
282            Validity::NonNullable,
283        );
284        let result = arr.take(indices_arr.into_array())?;
285
286        // Verify every element.
287        let result = result.to_primitive();
288        let result_vals = result.as_slice::<i32>();
289        for (pos, &idx) in indices.iter().enumerate() {
290            assert_eq!(
291                result_vals[pos],
292                i32::try_from(idx)?,
293                "mismatch at position {pos}"
294            );
295        }
296        Ok(())
297    }
298
299    #[test]
300    fn test_take_null_indices() -> VortexResult<()> {
301        let c0 = buffer![10i32, 20, 30].into_array();
302        let c1 = buffer![40i32, 50, 60].into_array();
303        let arr = ChunkedArray::try_new(
304            vec![c0, c1],
305            PrimitiveArray::empty::<i32>(Nullability::NonNullable)
306                .dtype()
307                .clone(),
308        )?;
309
310        // Indices with nulls scattered across chunk boundaries.
311        let indices =
312            PrimitiveArray::from_option_iter([Some(5u64), None, Some(0), Some(3), None, Some(2)]);
313        let result = arr.take(indices.into_array())?;
314
315        assert_arrays_eq!(
316            result,
317            PrimitiveArray::from_option_iter([
318                Some(60i32),
319                None,
320                Some(10),
321                Some(40),
322                None,
323                Some(30)
324            ])
325        );
326        Ok(())
327    }
328
329    #[test]
330    fn test_take_chunked_conformance() {
331        let a = buffer![1i32, 2, 3].into_array();
332        let b = buffer![4i32, 5].into_array();
333        let arr = ChunkedArray::try_new(
334            vec![a, b],
335            PrimitiveArray::empty::<i32>(Nullability::NonNullable)
336                .dtype()
337                .clone(),
338        )
339        .unwrap();
340        test_take_conformance(&arr.into_array());
341
342        // Test with nullable chunked array
343        let a = PrimitiveArray::from_option_iter([Some(1i32), None, Some(3)]);
344        let b = PrimitiveArray::from_option_iter([Some(4i32), Some(5)]);
345        let dtype = a.dtype().clone();
346        let arr = ChunkedArray::try_new(vec![a.into_array(), b.into_array()], dtype).unwrap();
347        test_take_conformance(&arr.into_array());
348
349        // Test with multiple identical chunks
350        let chunk = buffer![10i32, 20, 30, 40, 50].into_array();
351        let arr = ChunkedArray::try_new(
352            vec![chunk.clone(), chunk.clone(), chunk.clone()],
353            chunk.dtype().clone(),
354        )
355        .unwrap();
356        test_take_conformance(&arr.into_array());
357    }
358}