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_dtype::{DType, PType};
6use vortex_error::VortexResult;
7
8use crate::arrays::chunked::ChunkedArray;
9use crate::arrays::{ChunkedVTable, PrimitiveArray};
10use crate::compute::{TakeKernel, TakeKernelAdapter, cast, take};
11use crate::validity::Validity;
12use crate::{Array, ArrayRef, IntoArray, ToCanonical, register_kernel};
13
14impl TakeKernel for ChunkedVTable {
15    fn take(&self, array: &ChunkedArray, indices: &dyn Array) -> VortexResult<ArrayRef> {
16        let indices = cast(
17            indices,
18            &DType::Primitive(PType::U64, indices.dtype().nullability()),
19        )?
20        .to_primitive()?;
21
22        // TODO(joe): Should we split this implementation based on indices nullability?
23        let nullability = indices.dtype().nullability();
24        let indices_mask = indices.validity_mask()?;
25        let indices = indices.as_slice::<u64>();
26
27        let mut chunks = Vec::new();
28        let mut indices_in_chunk = BufferMut::<u64>::empty();
29        let mut start = 0;
30        let mut stop = 0;
31        // We assume indices are non-empty as it's handled in the top-level `take` function
32        let mut prev_chunk_idx = array.find_chunk_idx(indices[0].try_into()?).0;
33        for idx in indices {
34            let idx = usize::try_from(*idx)?;
35            let (chunk_idx, idx_in_chunk) = array.find_chunk_idx(idx);
36
37            if chunk_idx != prev_chunk_idx {
38                // Start a new chunk
39                let indices_in_chunk_array = PrimitiveArray::new(
40                    indices_in_chunk.clone().freeze(),
41                    Validity::from_mask(indices_mask.slice(start, stop - start), nullability),
42                );
43                chunks.push(take(
44                    array.chunk(prev_chunk_idx)?,
45                    indices_in_chunk_array.as_ref(),
46                )?);
47                indices_in_chunk.clear();
48                start = stop;
49            }
50
51            indices_in_chunk.push(idx_in_chunk as u64);
52            stop += 1;
53            prev_chunk_idx = chunk_idx;
54        }
55
56        if !indices_in_chunk.is_empty() {
57            let indices_in_chunk_array = PrimitiveArray::new(
58                indices_in_chunk.freeze(),
59                Validity::from_mask(indices_mask.slice(start, stop - start), nullability),
60            );
61            chunks.push(take(
62                array.chunk(prev_chunk_idx)?,
63                indices_in_chunk_array.as_ref(),
64            )?);
65        }
66
67        Ok(ChunkedArray::new_unchecked(
68            chunks,
69            array.dtype().clone().union_nullability(nullability),
70        )
71        .into_array())
72    }
73}
74
75register_kernel!(TakeKernelAdapter(ChunkedVTable).lift());
76
77#[cfg(test)]
78mod test {
79    use vortex_buffer::buffer;
80    use vortex_dtype::{FieldNames, Nullability};
81
82    use crate::IntoArray;
83    use crate::array::Array;
84    use crate::arrays::chunked::ChunkedArray;
85    use crate::arrays::{BoolArray, PrimitiveArray, StructArray};
86    use crate::canonical::ToCanonical;
87    use crate::compute::conformance::take::test_take_conformance;
88    use crate::compute::take;
89    use crate::validity::Validity;
90
91    #[test]
92    fn test_take() {
93        let a = buffer![1i32, 2, 3].into_array();
94        let arr = ChunkedArray::try_new(vec![a.clone(), a.clone(), a.clone()], a.dtype().clone())
95            .unwrap();
96        assert_eq!(arr.nchunks(), 3);
97        assert_eq!(arr.len(), 9);
98        let indices = buffer![0u64, 0, 6, 4].into_array();
99
100        let result = take(arr.as_ref(), indices.as_ref())
101            .unwrap()
102            .to_primitive()
103            .unwrap();
104        assert_eq!(result.as_slice::<i32>(), &[1, 1, 1, 2]);
105    }
106
107    #[test]
108    fn test_take_nullability() {
109        let struct_array =
110            StructArray::try_new(FieldNames::default(), vec![], 100, Validity::NonNullable)
111                .unwrap();
112
113        let arr = ChunkedArray::from_iter(vec![struct_array.to_array(), struct_array.to_array()]);
114
115        let result = take(
116            arr.as_ref(),
117            PrimitiveArray::from_option_iter(vec![Some(0), None, Some(101)]).as_ref(),
118        )
119        .unwrap();
120
121        let expect = StructArray::try_new(
122            FieldNames::default(),
123            vec![],
124            3,
125            Validity::Array(BoolArray::from_iter(vec![true, false, true]).to_array()),
126        )
127        .unwrap();
128        assert_eq!(result.dtype(), expect.dtype());
129        assert_eq!(result.scalar_at(0).unwrap(), expect.scalar_at(0).unwrap());
130        assert_eq!(result.scalar_at(1).unwrap(), expect.scalar_at(1).unwrap());
131        assert_eq!(result.scalar_at(2).unwrap(), expect.scalar_at(2).unwrap());
132    }
133
134    #[test]
135    fn test_empty_take() {
136        let a = buffer![1i32, 2, 3].into_array();
137        let arr = ChunkedArray::try_new(vec![a.clone(), a.clone(), a.clone()], a.dtype().clone())
138            .unwrap();
139        assert_eq!(arr.nchunks(), 3);
140        assert_eq!(arr.len(), 9);
141
142        let indices = PrimitiveArray::empty::<u64>(Nullability::NonNullable);
143        let result = take(arr.as_ref(), indices.as_ref())
144            .unwrap()
145            .to_primitive()
146            .unwrap();
147
148        assert!(result.is_empty());
149        assert_eq!(result.dtype(), arr.dtype());
150        assert!(result.as_slice::<i32>().is_empty());
151    }
152
153    #[test]
154    fn test_take_chunked_conformance() {
155        let a = buffer![1i32, 2, 3].into_array();
156        let b = buffer![4i32, 5].into_array();
157        let arr = ChunkedArray::try_new(
158            vec![a, b],
159            PrimitiveArray::empty::<i32>(Nullability::NonNullable)
160                .dtype()
161                .clone(),
162        )
163        .unwrap();
164        test_take_conformance(arr.as_ref());
165
166        // Test with nullable chunked array
167        let a = PrimitiveArray::from_option_iter([Some(1i32), None, Some(3)]);
168        let b = PrimitiveArray::from_option_iter([Some(4i32), Some(5)]);
169        let dtype = a.dtype().clone();
170        let arr = ChunkedArray::try_new(vec![a.into_array(), b.into_array()], dtype).unwrap();
171        test_take_conformance(arr.as_ref());
172
173        // Test with multiple identical chunks
174        let chunk = buffer![10i32, 20, 30, 40, 50].into_array();
175        let arr = ChunkedArray::try_new(
176            vec![chunk.clone(), chunk.clone(), chunk.clone()],
177            chunk.dtype().clone(),
178        )
179        .unwrap();
180        test_take_conformance(arr.as_ref());
181    }
182}