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::{Result, exec_err};
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    sql_example = r#"```sql
43> SELECT signum(-42);
44+-------------+
45| signum(-42) |
46+-------------+
47| -1          |
48+-------------+
49```"#
50)]
51#[derive(Debug, PartialEq, Eq, Hash)]
52pub struct SignumFunc {
53    signature: Signature,
54}
55
56impl Default for SignumFunc {
57    fn default() -> Self {
58        SignumFunc::new()
59    }
60}
61
62impl SignumFunc {
63    pub fn new() -> Self {
64        use DataType::*;
65        Self {
66            signature: Signature::uniform(
67                1,
68                vec![Float64, Float32],
69                Volatility::Immutable,
70            ),
71        }
72    }
73}
74
75impl ScalarUDFImpl for SignumFunc {
76    fn as_any(&self) -> &dyn Any {
77        self
78    }
79
80    fn name(&self) -> &str {
81        "signum"
82    }
83
84    fn signature(&self) -> &Signature {
85        &self.signature
86    }
87
88    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
89        match &arg_types[0] {
90            Float32 => Ok(Float32),
91            _ => Ok(Float64),
92        }
93    }
94
95    fn output_ordering(&self, input: &[ExprProperties]) -> Result<SortProperties> {
96        // Non-decreasing for all real numbers x.
97        Ok(input[0].sort_properties)
98    }
99
100    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
101        make_scalar_function(signum, vec![])(&args.args)
102    }
103
104    fn documentation(&self) -> Option<&Documentation> {
105        self.doc()
106    }
107}
108
109/// signum SQL function
110fn signum(args: &[ArrayRef]) -> Result<ArrayRef> {
111    match args[0].data_type() {
112        Float64 => Ok(Arc::new(
113            args[0]
114                .as_primitive::<Float64Type>()
115                .unary::<_, Float64Type>(
116                    |x: f64| {
117                        if x == 0_f64 { 0_f64 } else { x.signum() }
118                    },
119                ),
120        ) as ArrayRef),
121
122        Float32 => Ok(Arc::new(
123            args[0]
124                .as_primitive::<Float32Type>()
125                .unary::<_, Float32Type>(
126                    |x: f32| {
127                        if x == 0_f32 { 0_f32 } else { x.signum() }
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_common::config::ConfigOptions;
144    use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl};
145
146    use crate::math::signum::SignumFunc;
147
148    #[test]
149    fn test_signum_f32() {
150        let array = Arc::new(Float32Array::from(vec![
151            -1.0,
152            -0.0,
153            0.0,
154            1.0,
155            -0.01,
156            0.01,
157            f32::NAN,
158            f32::INFINITY,
159            f32::NEG_INFINITY,
160        ]));
161        let arg_fields = vec![Field::new("a", DataType::Float32, false).into()];
162        let args = ScalarFunctionArgs {
163            args: vec![ColumnarValue::Array(Arc::clone(&array) as ArrayRef)],
164            arg_fields,
165            number_rows: array.len(),
166            return_field: Field::new("f", DataType::Float32, true).into(),
167            config_options: Arc::new(ConfigOptions::default()),
168        };
169        let result = SignumFunc::new()
170            .invoke_with_args(args)
171            .expect("failed to initialize function signum");
172
173        match result {
174            ColumnarValue::Array(arr) => {
175                let floats = as_float32_array(&arr)
176                    .expect("failed to convert result to a Float32Array");
177
178                assert_eq!(floats.len(), 9);
179                assert_eq!(floats.value(0), -1.0);
180                assert_eq!(floats.value(1), 0.0);
181                assert_eq!(floats.value(2), 0.0);
182                assert_eq!(floats.value(3), 1.0);
183                assert_eq!(floats.value(4), -1.0);
184                assert_eq!(floats.value(5), 1.0);
185                assert!(floats.value(6).is_nan());
186                assert_eq!(floats.value(7), 1.0);
187                assert_eq!(floats.value(8), -1.0);
188            }
189            ColumnarValue::Scalar(_) => {
190                panic!("Expected an array value")
191            }
192        }
193    }
194
195    #[test]
196    fn test_signum_f64() {
197        let array = Arc::new(Float64Array::from(vec![
198            -1.0,
199            -0.0,
200            0.0,
201            1.0,
202            -0.01,
203            0.01,
204            f64::NAN,
205            f64::INFINITY,
206            f64::NEG_INFINITY,
207        ]));
208        let arg_fields = vec![Field::new("a", DataType::Float64, false).into()];
209        let args = ScalarFunctionArgs {
210            args: vec![ColumnarValue::Array(Arc::clone(&array) as ArrayRef)],
211            arg_fields,
212            number_rows: array.len(),
213            return_field: Field::new("f", DataType::Float64, true).into(),
214            config_options: Arc::new(ConfigOptions::default()),
215        };
216        let result = SignumFunc::new()
217            .invoke_with_args(args)
218            .expect("failed to initialize function signum");
219
220        match result {
221            ColumnarValue::Array(arr) => {
222                let floats = as_float64_array(&arr)
223                    .expect("failed to convert result to a Float32Array");
224
225                assert_eq!(floats.len(), 9);
226                assert_eq!(floats.value(0), -1.0);
227                assert_eq!(floats.value(1), 0.0);
228                assert_eq!(floats.value(2), 0.0);
229                assert_eq!(floats.value(3), 1.0);
230                assert_eq!(floats.value(4), -1.0);
231                assert_eq!(floats.value(5), 1.0);
232                assert!(floats.value(6).is_nan());
233                assert_eq!(floats.value(7), 1.0);
234                assert_eq!(floats.value(8), -1.0);
235            }
236            ColumnarValue::Scalar(_) => {
237                panic!("Expected an array value")
238            }
239        }
240    }
241}