Skip to main content

vortex_functions/
is_nan.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_array::dtype::DType;
5use vortex_array::match_each_float_ptype;
6use vortex_array::scalar_fn::EmptyOptions;
7use vortex_array::scalar_fn::ScalarFnId;
8use vortex_array::scalar_fn::unstable::row::RowFn;
9use vortex_array::scalar_fn::unstable::row::RowVisitor;
10use vortex_error::VortexResult;
11use vortex_error::vortex_bail;
12use vortex_session::registry::CachedId;
13
14/// Expression that checks for NaN values.
15///
16/// The function is strict: null inputs produce null outputs. Only primitive float inputs
17/// are supported.
18#[derive(Clone)]
19pub struct IsNan;
20
21impl RowFn for IsNan {
22    type Options = EmptyOptions;
23
24    const ARG_NAMES: &'static [&'static str] = &["input"];
25    const INFALLIBLE: bool = true;
26
27    fn id(&self) -> ScalarFnId {
28        static ID: CachedId = CachedId::new("vortex.is_nan");
29        *ID
30    }
31
32    fn dispatch<V: RowVisitor>(
33        &self,
34        _options: &Self::Options,
35        args: &[DType],
36        visitor: V,
37    ) -> VortexResult<V::VisitResult> {
38        let ptype = match args {
39            [DType::Primitive(ptype, _)] if ptype.is_float() => *ptype,
40            _ => vortex_bail!("is_nan expects a single float input, got {args:?}"),
41        };
42        match_each_float_ptype!(ptype, |T| {
43            visitor.visit_bool::<(T,), false>(|(value,)| value.is_nan())
44        })
45    }
46}
47
48#[cfg(test)]
49mod tests {
50    use std::sync::LazyLock;
51
52    use vortex_array::IntoArray;
53    use vortex_array::VortexSessionExecute;
54    use vortex_array::arrays::PrimitiveArray;
55    use vortex_array::dtype::DType;
56    use vortex_array::dtype::Nullability;
57    use vortex_array::dtype::PType;
58    use vortex_array::scalar::Scalar;
59    use vortex_array::validity::Validity;
60    use vortex_buffer::buffer;
61    use vortex_expr::ArrayExprExt;
62    use vortex_expr::get_item;
63    use vortex_expr::lit;
64    use vortex_expr::root;
65    use vortex_session::VortexSession;
66
67    use crate::expr::is_nan;
68
69    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
70        let session = VortexSession::empty();
71        vortex_array::initialize(&session);
72        crate::initialize(&session);
73        session
74    });
75
76    #[test]
77    fn dtype() {
78        assert_eq!(
79            is_nan(root())
80                .return_dtype(&DType::Primitive(PType::F32, Nullability::Nullable))
81                .unwrap(),
82            DType::Bool(Nullability::Nullable)
83        );
84        assert_eq!(
85            is_nan(root())
86                .return_dtype(&DType::Primitive(PType::F64, Nullability::NonNullable))
87                .unwrap(),
88            DType::Bool(Nullability::NonNullable)
89        );
90    }
91
92    #[test]
93    fn dtype_rejects_non_float() {
94        assert!(
95            is_nan(root())
96                .return_dtype(&DType::Primitive(PType::I32, Nullability::NonNullable))
97                .is_err()
98        );
99        assert!(
100            is_nan(root())
101                .return_dtype(&DType::Bool(Nullability::NonNullable))
102                .is_err()
103        );
104    }
105
106    #[test]
107    fn evaluate_floats() {
108        let test_array = PrimitiveArray::from_option_iter([
109            Some(1.0f32),
110            Some(f32::NAN),
111            None,
112            Some(f32::NEG_INFINITY),
113            Some(-f32::NAN),
114        ])
115        .into_array();
116        let expected = [Some(false), Some(true), None, Some(false), Some(true)];
117
118        let result = test_array.clone().apply(&is_nan(root())).unwrap();
119
120        assert_eq!(result.len(), test_array.len());
121        assert_eq!(result.dtype(), &DType::Bool(Nullability::Nullable));
122        for (i, expected_value) in expected.iter().enumerate() {
123            let expected_scalar = match expected_value {
124                Some(value) => Scalar::bool(*value, Nullability::Nullable),
125                None => Scalar::null(DType::Bool(Nullability::Nullable)),
126            };
127            assert_eq!(
128                result
129                    .execute_scalar(i, &mut SESSION.create_execution_ctx())
130                    .unwrap(),
131                expected_scalar
132            );
133        }
134    }
135
136    #[test]
137    fn evaluate_all_valid_floats() {
138        let test_array = PrimitiveArray::new(
139            buffer![1.0f64, f64::NAN, f64::INFINITY, -f64::NAN],
140            Validity::NonNullable,
141        )
142        .into_array();
143        let expected = [false, true, false, true];
144
145        let result = test_array.clone().apply(&is_nan(root())).unwrap();
146
147        assert_eq!(result.len(), test_array.len());
148        assert_eq!(result.dtype(), &DType::Bool(Nullability::NonNullable));
149        for (i, expected_value) in expected.iter().enumerate() {
150            assert_eq!(
151                result
152                    .execute_scalar(i, &mut SESSION.create_execution_ctx())
153                    .unwrap(),
154                Scalar::bool(*expected_value, Nullability::NonNullable)
155            );
156        }
157    }
158
159    #[test]
160    fn evaluate_all_null_floats() {
161        let test_array = PrimitiveArray::from_option_iter([None::<f32>, None, None]).into_array();
162
163        let result = test_array.clone().apply(&is_nan(root())).unwrap();
164
165        assert_eq!(result.len(), test_array.len());
166        for i in 0..result.len() {
167            assert_eq!(
168                result
169                    .execute_scalar(i, &mut SESSION.create_execution_ctx())
170                    .unwrap(),
171                Scalar::null(DType::Bool(Nullability::Nullable))
172            );
173        }
174    }
175
176    #[test]
177    fn evaluate_constant() {
178        let test_array = buffer![1.0f32, 2.0, 3.0].into_array();
179        let cases = [
180            (lit(f32::NAN), Some(true)),
181            (lit(1.0f32), Some(false)),
182            (
183                lit(Scalar::null(DType::Primitive(
184                    PType::F32,
185                    Nullability::Nullable,
186                ))),
187                None,
188            ),
189        ];
190
191        for (expr_child, expected_value) in cases {
192            let result = test_array.clone().apply(&is_nan(expr_child)).unwrap();
193            for i in 0..result.len() {
194                let expected_scalar = match expected_value {
195                    Some(value) => Scalar::bool(value, Nullability::Nullable),
196                    None => Scalar::null(DType::Bool(Nullability::Nullable)),
197                };
198                assert_eq!(
199                    result
200                        .execute_scalar(i, &mut SESSION.create_execution_ctx())
201                        .unwrap(),
202                    expected_scalar
203                );
204            }
205        }
206    }
207
208    #[test]
209    fn evaluate_rejects_non_float() {
210        let test_array = buffer![1i32, 2, 3].into_array();
211        assert!(test_array.apply(&is_nan(root())).is_err());
212    }
213
214    #[test]
215    fn evaluate_sliced() {
216        let test_array = buffer![1.0f32, f32::NAN, 2.0, f32::NAN, 3.0]
217            .into_array()
218            .slice(1..4)
219            .unwrap();
220        let expected = [true, false, true];
221
222        let result = test_array.clone().apply(&is_nan(root())).unwrap();
223
224        assert_eq!(result.len(), test_array.len());
225        for (i, expected_value) in expected.iter().enumerate() {
226            assert_eq!(
227                result
228                    .execute_scalar(i, &mut SESSION.create_execution_ctx())
229                    .unwrap(),
230                Scalar::bool(*expected_value, Nullability::NonNullable)
231            );
232        }
233    }
234
235    #[test]
236    fn test_display() {
237        let expr = is_nan(get_item("name", root()));
238        assert_eq!(expr.to_string(), "vortex.is_nan($.name)");
239
240        let expr2 = is_nan(root());
241        assert_eq!(expr2.to_string(), "vortex.is_nan($)");
242    }
243
244    #[test]
245    fn test_is_nan_is_strict() {
246        assert!(
247            is_nan(root())
248                .as_scalar()
249                .is_some_and(|f| f.signature().is_strict())
250        );
251    }
252}