datafusion_functions/math/
signum.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::any::Any;
19use std::sync::Arc;
20
21use arrow::array::{ArrayRef, AsArray};
22use arrow::datatypes::DataType::{Float32, Float64};
23use arrow::datatypes::{DataType, Float32Type, Float64Type};
24
25use datafusion_common::{exec_err, Result};
26use datafusion_expr::sort_properties::{ExprProperties, SortProperties};
27use datafusion_expr::{
28    ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
29    Volatility,
30};
31use datafusion_macros::user_doc;
32
33use crate::utils::make_scalar_function;
34
35#[user_doc(
36    doc_section(label = "Math Functions"),
37    description = r#"Returns the sign of a number.
38Negative numbers return `-1`.
39Zero and positive numbers return `1`."#,
40    syntax_example = "signum(numeric_expression)",
41    standard_argument(name = "numeric_expression", prefix = "Numeric")
42)]
43#[derive(Debug)]
44pub struct SignumFunc {
45    signature: Signature,
46}
47
48impl Default for SignumFunc {
49    fn default() -> Self {
50        SignumFunc::new()
51    }
52}
53
54impl SignumFunc {
55    pub fn new() -> Self {
56        use DataType::*;
57        Self {
58            signature: Signature::uniform(
59                1,
60                vec![Float64, Float32],
61                Volatility::Immutable,
62            ),
63        }
64    }
65}
66
67impl ScalarUDFImpl for SignumFunc {
68    fn as_any(&self) -> &dyn Any {
69        self
70    }
71
72    fn name(&self) -> &str {
73        "signum"
74    }
75
76    fn signature(&self) -> &Signature {
77        &self.signature
78    }
79
80    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
81        match &arg_types[0] {
82            Float32 => Ok(Float32),
83            _ => Ok(Float64),
84        }
85    }
86
87    fn output_ordering(&self, input: &[ExprProperties]) -> Result<SortProperties> {
88        // Non-decreasing for all real numbers x.
89        Ok(input[0].sort_properties)
90    }
91
92    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
93        make_scalar_function(signum, vec![])(&args.args)
94    }
95
96    fn documentation(&self) -> Option<&Documentation> {
97        self.doc()
98    }
99}
100
101/// signum SQL function
102pub fn signum(args: &[ArrayRef]) -> Result<ArrayRef> {
103    match args[0].data_type() {
104        Float64 => Ok(Arc::new(
105            args[0]
106                .as_primitive::<Float64Type>()
107                .unary::<_, Float64Type>(
108                    |x: f64| {
109                        if x == 0_f64 {
110                            0_f64
111                        } else {
112                            x.signum()
113                        }
114                    },
115                ),
116        ) as ArrayRef),
117
118        Float32 => Ok(Arc::new(
119            args[0]
120                .as_primitive::<Float32Type>()
121                .unary::<_, Float32Type>(
122                    |x: f32| {
123                        if x == 0_f32 {
124                            0_f32
125                        } else {
126                            x.signum()
127                        }
128                    },
129                ),
130        ) as ArrayRef),
131
132        other => exec_err!("Unsupported data type {other:?} for function signum"),
133    }
134}
135
136#[cfg(test)]
137mod test {
138    use std::sync::Arc;
139
140    use arrow::array::{ArrayRef, Float32Array, Float64Array};
141    use arrow::datatypes::{DataType, Field};
142    use datafusion_common::cast::{as_float32_array, as_float64_array};
143    use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl};
144
145    use crate::math::signum::SignumFunc;
146
147    #[test]
148    fn test_signum_f32() {
149        let array = Arc::new(Float32Array::from(vec![
150            -1.0,
151            -0.0,
152            0.0,
153            1.0,
154            -0.01,
155            0.01,
156            f32::NAN,
157            f32::INFINITY,
158            f32::NEG_INFINITY,
159        ]));
160        let arg_fields = vec![Field::new("a", DataType::Float32, false).into()];
161        let args = ScalarFunctionArgs {
162            args: vec![ColumnarValue::Array(Arc::clone(&array) as ArrayRef)],
163            arg_fields,
164            number_rows: array.len(),
165            return_field: Field::new("f", DataType::Float32, true).into(),
166        };
167        let result = SignumFunc::new()
168            .invoke_with_args(args)
169            .expect("failed to initialize function signum");
170
171        match result {
172            ColumnarValue::Array(arr) => {
173                let floats = as_float32_array(&arr)
174                    .expect("failed to convert result to a Float32Array");
175
176                assert_eq!(floats.len(), 9);
177                assert_eq!(floats.value(0), -1.0);
178                assert_eq!(floats.value(1), 0.0);
179                assert_eq!(floats.value(2), 0.0);
180                assert_eq!(floats.value(3), 1.0);
181                assert_eq!(floats.value(4), -1.0);
182                assert_eq!(floats.value(5), 1.0);
183                assert!(floats.value(6).is_nan());
184                assert_eq!(floats.value(7), 1.0);
185                assert_eq!(floats.value(8), -1.0);
186            }
187            ColumnarValue::Scalar(_) => {
188                panic!("Expected an array value")
189            }
190        }
191    }
192
193    #[test]
194    fn test_signum_f64() {
195        let array = Arc::new(Float64Array::from(vec![
196            -1.0,
197            -0.0,
198            0.0,
199            1.0,
200            -0.01,
201            0.01,
202            f64::NAN,
203            f64::INFINITY,
204            f64::NEG_INFINITY,
205        ]));
206        let arg_fields = vec![Field::new("a", DataType::Float64, false).into()];
207        let args = ScalarFunctionArgs {
208            args: vec![ColumnarValue::Array(Arc::clone(&array) as ArrayRef)],
209            arg_fields,
210            number_rows: array.len(),
211            return_field: Field::new("f", DataType::Float64, true).into(),
212        };
213        let result = SignumFunc::new()
214            .invoke_with_args(args)
215            .expect("failed to initialize function signum");
216
217        match result {
218            ColumnarValue::Array(arr) => {
219                let floats = as_float64_array(&arr)
220                    .expect("failed to convert result to a Float32Array");
221
222                assert_eq!(floats.len(), 9);
223                assert_eq!(floats.value(0), -1.0);
224                assert_eq!(floats.value(1), 0.0);
225                assert_eq!(floats.value(2), 0.0);
226                assert_eq!(floats.value(3), 1.0);
227                assert_eq!(floats.value(4), -1.0);
228                assert_eq!(floats.value(5), 1.0);
229                assert!(floats.value(6).is_nan());
230                assert_eq!(floats.value(7), 1.0);
231                assert_eq!(floats.value(8), -1.0);
232            }
233            ColumnarValue::Scalar(_) => {
234                panic!("Expected an array value")
235            }
236        }
237    }
238}