vortex_array/compute/
mask.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::sync::LazyLock;
5
6use arcref::ArcRef;
7use arrow_array::BooleanArray;
8use vortex_dtype::DType;
9use vortex_error::{VortexError, VortexResult, vortex_bail, vortex_err};
10use vortex_mask::Mask;
11use vortex_scalar::Scalar;
12
13use crate::arrays::ConstantArray;
14use crate::arrow::{FromArrowArray, IntoArrowArray};
15use crate::compute::{ComputeFn, ComputeFnVTable, InvocationArgs, Kernel, Output, cast};
16use crate::vtable::VTable;
17use crate::{Array, ArrayRef, IntoArray};
18
19static MASK_FN: LazyLock<ComputeFn> = LazyLock::new(|| {
20    let compute = ComputeFn::new("mask".into(), ArcRef::new_ref(&MaskFn));
21    for kernel in inventory::iter::<MaskKernelRef> {
22        compute.register_kernel(kernel.0.clone());
23    }
24    compute
25});
26
27/// Replace values with null where the mask is true.
28///
29/// The returned array is nullable but otherwise has the same dtype and length as `array`.
30///
31/// # Examples
32///
33/// ```
34/// use vortex_array::IntoArray;
35/// use vortex_array::arrays::{BoolArray, PrimitiveArray};
36/// use vortex_array::compute::{ mask};
37/// use vortex_mask::Mask;
38/// use vortex_scalar::Scalar;
39///
40/// let array =
41///     PrimitiveArray::from_option_iter([Some(0i32), None, Some(1i32), None, Some(2i32)]);
42/// let mask_array = Mask::from_iter([true, false, false, false, true]);
43///
44/// let masked = mask(array.as_ref(), &mask_array).unwrap();
45/// assert_eq!(masked.len(), 5);
46/// assert!(!masked.is_valid(0));
47/// assert!(!masked.is_valid(1));
48/// assert_eq!(masked.scalar_at(2), Scalar::from(Some(1)));
49/// assert!(!masked.is_valid(3));
50/// assert!(!masked.is_valid(4));
51/// ```
52///
53pub fn mask(array: &dyn Array, mask: &Mask) -> VortexResult<ArrayRef> {
54    MASK_FN
55        .invoke(&InvocationArgs {
56            inputs: &[array.into(), mask.into()],
57            options: &(),
58        })?
59        .unwrap_array()
60}
61
62pub struct MaskKernelRef(ArcRef<dyn Kernel>);
63inventory::collect!(MaskKernelRef);
64
65pub trait MaskKernel: VTable {
66    /// Replace masked values with null in array.
67    fn mask(&self, array: &Self::Array, mask: &Mask) -> VortexResult<ArrayRef>;
68}
69
70#[derive(Debug)]
71pub struct MaskKernelAdapter<V: VTable>(pub V);
72
73impl<V: VTable + MaskKernel> MaskKernelAdapter<V> {
74    pub const fn lift(&'static self) -> MaskKernelRef {
75        MaskKernelRef(ArcRef::new_ref(self))
76    }
77}
78
79impl<V: VTable + MaskKernel> Kernel for MaskKernelAdapter<V> {
80    fn invoke(&self, args: &InvocationArgs) -> VortexResult<Option<Output>> {
81        let inputs = MaskArgs::try_from(args)?;
82        let Some(array) = inputs.array.as_opt::<V>() else {
83            return Ok(None);
84        };
85        Ok(Some(V::mask(&self.0, array, inputs.mask)?.into()))
86    }
87}
88
89struct MaskFn;
90
91impl ComputeFnVTable for MaskFn {
92    fn invoke(
93        &self,
94        args: &InvocationArgs,
95        kernels: &[ArcRef<dyn Kernel>],
96    ) -> VortexResult<Output> {
97        let MaskArgs { array, mask } = MaskArgs::try_from(args)?;
98
99        if matches!(mask, Mask::AllFalse(_)) {
100            // Fast-path for empty mask
101            return Ok(cast(array, &array.dtype().as_nullable())?.into());
102        }
103
104        if matches!(mask, Mask::AllTrue(_)) {
105            // Fast-path for full mask.
106            return Ok(ConstantArray::new(
107                Scalar::null(array.dtype().clone().as_nullable()),
108                array.len(),
109            )
110            .into_array()
111            .into());
112        }
113
114        for kernel in kernels {
115            if let Some(output) = kernel.invoke(args)? {
116                return Ok(output);
117            }
118        }
119        if let Some(output) = array.invoke(&MASK_FN, args)? {
120            return Ok(output);
121        }
122
123        // Fallback: implement using Arrow kernels.
124        log::debug!("No mask implementation found for {}", array.encoding_id());
125
126        let array_ref = array.to_array().into_arrow_preferred()?;
127        let mask = BooleanArray::new(mask.to_boolean_buffer(), None);
128
129        let masked = arrow_select::nullif::nullif(array_ref.as_ref(), &mask)?;
130
131        Ok(ArrayRef::from_arrow(masked.as_ref(), true).into())
132    }
133
134    fn return_dtype(&self, args: &InvocationArgs) -> VortexResult<DType> {
135        let MaskArgs { array, .. } = MaskArgs::try_from(args)?;
136        Ok(array.dtype().as_nullable())
137    }
138
139    fn return_len(&self, args: &InvocationArgs) -> VortexResult<usize> {
140        let MaskArgs { array, mask } = MaskArgs::try_from(args)?;
141
142        if mask.len() != array.len() {
143            vortex_bail!(
144                "mask.len() is {}, does not equal array.len() of {}",
145                mask.len(),
146                array.len()
147            );
148        }
149
150        Ok(mask.len())
151    }
152
153    fn is_elementwise(&self) -> bool {
154        true
155    }
156}
157
158struct MaskArgs<'a> {
159    array: &'a dyn Array,
160    mask: &'a Mask,
161}
162
163impl<'a> TryFrom<&InvocationArgs<'a>> for MaskArgs<'a> {
164    type Error = VortexError;
165
166    fn try_from(value: &InvocationArgs<'a>) -> Result<Self, Self::Error> {
167        if value.inputs.len() != 2 {
168            vortex_bail!("Mask function requires 2 arguments");
169        }
170        let array = value.inputs[0]
171            .array()
172            .ok_or_else(|| vortex_err!("Expected input 0 to be an array"))?;
173        let mask = value.inputs[1]
174            .mask()
175            .ok_or_else(|| vortex_err!("Expected input 1 to be a mask"))?;
176
177        Ok(MaskArgs { array, mask })
178    }
179}