Skip to main content

vortex_functions/zip/
chunked.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use itertools::Itertools;
5use vortex_array::ArrayRef;
6use vortex_array::ArrayView;
7use vortex_array::ExecutionCtx;
8use vortex_array::IntoArray;
9use vortex_array::arrays::Chunked;
10use vortex_array::arrays::ChunkedArray;
11use vortex_array::arrays::chunked::ChunkedArrayExt;
12use vortex_error::VortexResult;
13
14use crate::builtins::ArrayFunctions;
15use crate::zip::ZipKernel;
16use crate::zip::paired_chunks::PairedChunksExt;
17
18// Push down the zip call to the chunks. Without this rule
19// the default implementation canonicalises the chunked array
20// then zips once.
21impl ZipKernel for Chunked {
22    fn zip(
23        if_true: ArrayView<'_, Chunked>,
24        if_false: &ArrayRef,
25        mask: &ArrayRef,
26        _ctx: &mut ExecutionCtx,
27    ) -> VortexResult<Option<ArrayRef>> {
28        let Some(if_false) = if_false.as_opt::<Chunked>() else {
29            return Ok(None);
30        };
31        let dtype = if_true
32            .dtype()
33            .union_nullability(if_false.dtype().nullability());
34        let chunks = if_true.paired_chunks(&if_false).map(|pair| {
35            let pair = pair?;
36            mask.slice(pair.pos)?.zip(pair.left, pair.right)
37        });
38        chunks.process_results(|chunks| {
39            // SAFETY: chunks originate from zipping slices of inputs that share dtype/nullability.
40            Some(unsafe {
41                ChunkedArray::new_unchecked_sized(
42                    chunks,
43                    dtype,
44                    if_true.nchunks() + if_false.nchunks(),
45                )
46                .into_array()
47            })
48        })
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use std::sync::LazyLock;
55
56    use vortex_array::ArrayRef;
57    use vortex_array::IntoArray;
58    use vortex_array::VortexSessionExecute;
59    use vortex_array::arrays::Chunked;
60    use vortex_array::arrays::ChunkedArray;
61    use vortex_array::arrays::PrimitiveArray;
62    use vortex_array::arrays::chunked::ChunkedArrayExt;
63    use vortex_array::dtype::DType;
64    use vortex_array::dtype::Nullability;
65    use vortex_array::dtype::PType;
66    use vortex_buffer::buffer;
67    use vortex_mask::Mask;
68    use vortex_session::VortexSession;
69
70    use crate::builtins::ArrayFunctions;
71
72    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
73        let session = VortexSession::empty();
74
75        vortex_array::initialize(&session);
76
77        crate::initialize(&session);
78
79        session
80    });
81
82    #[test]
83    fn test_chunked_zip_aligns_across_boundaries() {
84        let mut ctx = SESSION.create_execution_ctx();
85        let if_true = ChunkedArray::try_new(
86            vec![
87                buffer![1i32, 2].into_array(),
88                buffer![3i32].into_array(),
89                buffer![4i32, 5].into_array(),
90            ],
91            DType::Primitive(PType::I32, Nullability::NonNullable),
92        )
93        .unwrap();
94
95        let if_false = ChunkedArray::try_new(
96            vec![
97                buffer![10i32].into_array(),
98                buffer![11i32, 12].into_array(),
99                buffer![13i32, 14].into_array(),
100            ],
101            DType::Primitive(PType::I32, Nullability::NonNullable),
102        )
103        .unwrap();
104
105        let mask = Mask::from_iter([true, false, true, false, true]);
106
107        let zipped = &mask
108            .into_array()
109            .zip(if_true.into_array(), if_false.into_array())
110            .unwrap();
111        // One step of execution will push down the zip.
112        let zipped = zipped
113            .clone()
114            .execute::<ArrayRef>(&mut SESSION.create_execution_ctx())
115            .unwrap();
116        let zipped = zipped
117            .as_opt::<Chunked>()
118            .expect("zip should keep chunked encoding");
119
120        assert_eq!(zipped.nchunks(), 4);
121        let mut values: Vec<i32> = Vec::new();
122        for chunk in zipped.chunks() {
123            let primitive = chunk.execute::<PrimitiveArray>(&mut ctx).unwrap();
124            values.extend_from_slice(primitive.as_slice::<i32>());
125        }
126        assert_eq!(values, vec![1, 11, 3, 13, 5]);
127    }
128}