Skip to main content

vortex_array/scalar_fn/builtin/mask/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4mod kernel;
5
6pub use kernel::*;
7use vortex_error::VortexExpect;
8use vortex_error::VortexResult;
9use vortex_error::vortex_ensure_eq;
10use vortex_session::VortexSession;
11use vortex_session::registry::CachedId;
12
13use crate::ArrayRef;
14use crate::Canonical;
15use crate::ExecutionCtx;
16use crate::IntoArray;
17use crate::arrays::Constant;
18use crate::arrays::ConstantArray;
19use crate::arrays::ScalarFnArray;
20use crate::arrays::masked::mask_validity_canonical;
21use crate::builtins::ArrayBuiltins;
22use crate::child_to_validity;
23use crate::dtype::DType;
24use crate::dtype::Nullability;
25use crate::scalar::Scalar;
26use crate::scalar_fn::Arity;
27use crate::scalar_fn::ChildName;
28use crate::scalar_fn::EmptyOptions;
29use crate::scalar_fn::ExecutionArgs;
30use crate::scalar_fn::ReduceNode;
31use crate::scalar_fn::ReduceNodeValidity;
32use crate::scalar_fn::ScalarFnId;
33use crate::scalar_fn::ScalarFnVTable;
34use crate::scalar_fn::ScalarFnVTableExt;
35use crate::scalar_fn::builtin::boolean::Boolean;
36use crate::scalar_fn::builtin::operators::BooleanOperator;
37use crate::scalar_fn::is_not_null_node;
38
39/// An expression that masks an input based on a boolean mask.
40///
41/// Where the mask is true, the input value is retained; where the mask is false, the output is
42/// null. In other words, this performs an intersection of the input's validity with the mask.
43#[derive(Clone)]
44pub struct Mask;
45
46impl Mask {
47    /// Creates a lazy mask operation over `input`.
48    ///
49    /// # Errors
50    ///
51    /// Returns an error if the children have different lengths or `mask` is not non-nullable
52    /// boolean data.
53    pub fn try_new(input: ArrayRef, mask: ArrayRef) -> VortexResult<ScalarFnArray> {
54        ScalarFnArray::try_new(Mask.bind(EmptyOptions), [input, mask])
55    }
56}
57
58impl ScalarFnVTable for Mask {
59    type Options = EmptyOptions;
60
61    fn id(&self) -> ScalarFnId {
62        static ID: CachedId = CachedId::new("vortex.mask");
63        *ID
64    }
65
66    fn serialize(&self, _options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
67        Ok(Some(vec![]))
68    }
69
70    fn deserialize(
71        &self,
72        _metadata: &[u8],
73        _session: &VortexSession,
74    ) -> VortexResult<Self::Options> {
75        Ok(EmptyOptions)
76    }
77
78    fn arity(&self, _options: &Self::Options) -> Arity {
79        Arity::Exact(2)
80    }
81
82    fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName {
83        match child_idx {
84            0 => ChildName::from("input"),
85            1 => ChildName::from("mask"),
86            _ => unreachable!("Invalid child index {} for Mask expression", child_idx),
87        }
88    }
89
90    fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
91        vortex_ensure_eq!(
92            arg_dtypes[1],
93            DType::Bool(Nullability::NonNullable),
94            "The mask argument to 'mask' must be a non-nullable boolean array"
95        );
96        Ok(arg_dtypes[0].as_nullable())
97    }
98
99    fn execute(
100        &self,
101        _options: &Self::Options,
102        args: &dyn ExecutionArgs,
103        ctx: &mut ExecutionCtx,
104    ) -> VortexResult<ArrayRef> {
105        let input = args.get(0)?;
106        let mask_array = args.get(1)?;
107
108        if let Some(result) = execute_constant(&input, &mask_array)? {
109            return Ok(result);
110        }
111
112        execute_canonical(input, mask_array, ctx)
113    }
114
115    fn simplify<T: ReduceNode>(
116        &self,
117        _options: &Self::Options,
118        node: &T,
119    ) -> VortexResult<Option<T>> {
120        let mask = node.child(1);
121        let Some(mask_constant) = mask.as_constant() else {
122            return Ok(None);
123        };
124
125        let mask_constant = mask_constant
126            .as_bool()
127            .value()
128            .vortex_expect("Mask must be non-nullable");
129
130        if mask_constant {
131            // Mask is all true, so the output is just the input.
132            Ok(Some(node.child(0)))
133        } else {
134            // Mask is all false, so the output is all nulls.
135            let input_dtype = node.child(0).node_dtype()?;
136            Ok(Some(
137                node.new_constant(Scalar::null(input_dtype.as_nullable())),
138            ))
139        }
140    }
141
142    fn validity<T: ReduceNode>(
143        &self,
144        _options: &Self::Options,
145        node: &T,
146    ) -> VortexResult<ReduceNodeValidity<T>> {
147        let input_validity = is_not_null_node(&node.child(0))?;
148        Ok(ReduceNodeValidity::Reduced(input_validity.new_node(
149            Boolean.bind(BooleanOperator::And),
150            &[input_validity.clone(), node.child(1)],
151        )?))
152    }
153
154    fn is_strict(&self, _options: &Self::Options) -> bool {
155        true
156    }
157}
158
159/// Try to handle masking when at least one of the input or mask is a constant array.
160///
161/// Returns `Ok(Some(result))` if the constant case was handled, `Ok(None)` if not.
162fn execute_constant(input: &ArrayRef, mask_array: &ArrayRef) -> VortexResult<Option<ArrayRef>> {
163    let len = input.len();
164
165    if let Some(constant_mask) = mask_array.as_opt::<Constant>() {
166        let mask_value = constant_mask.scalar().as_bool().value().unwrap_or(false);
167        return if mask_value {
168            input.cast(input.dtype().as_nullable()).map(Some)
169        } else {
170            Ok(Some(
171                ConstantArray::new(Scalar::null(input.dtype().as_nullable()), len).into_array(),
172            ))
173        };
174    }
175
176    if let Some(constant_input) = input.as_opt::<Constant>()
177        && constant_input.scalar().is_null()
178    {
179        return Ok(Some(
180            ConstantArray::new(Scalar::null(input.dtype().as_nullable()), len).into_array(),
181        ));
182    }
183
184    Ok(None)
185}
186
187/// Execute the mask by materializing both inputs to their canonical forms.
188fn execute_canonical(
189    input: ArrayRef,
190    mask_array: ArrayRef,
191    ctx: &mut ExecutionCtx,
192) -> VortexResult<ArrayRef> {
193    let validity = child_to_validity(Some(&mask_array), Nullability::Nullable);
194    let canonical = input.execute::<Canonical>(ctx)?;
195    Ok(mask_validity_canonical(canonical, validity, ctx)?.into_array())
196}