Skip to main content

promql/functions/
round.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::sync::Arc;
16
17use datafusion::error::DataFusionError;
18use datafusion_common::ScalarValue;
19use datafusion_expr::{ColumnarValue, ScalarUDF, Volatility, create_udf};
20use datatypes::arrow::array::{AsArray, Float64Array, PrimitiveArray};
21use datatypes::arrow::datatypes::{DataType, Float64Type};
22use datatypes::arrow::error::ArrowError;
23
24use crate::error;
25use crate::functions::extract_array;
26
27pub struct Round;
28
29impl Round {
30    pub const fn name() -> &'static str {
31        "prom_round"
32    }
33
34    fn input_type() -> Vec<DataType> {
35        vec![DataType::Float64, DataType::Float64]
36    }
37
38    pub fn return_type() -> DataType {
39        DataType::Float64
40    }
41
42    pub fn scalar_udf() -> ScalarUDF {
43        create_udf(
44            Self::name(),
45            Self::input_type(),
46            Self::return_type(),
47            Volatility::Volatile,
48            Arc::new(Self::round) as _,
49        )
50    }
51
52    fn round(input: &[ColumnarValue]) -> Result<ColumnarValue, DataFusionError> {
53        error::ensure(
54            input.len() == 2,
55            DataFusionError::Plan("prom_round function should have 2 inputs".to_string()),
56        )?;
57
58        let value_array = extract_array(&input[0])?;
59        let nearest_col = &input[1];
60
61        match nearest_col {
62            ColumnarValue::Scalar(nearest_scalar) => {
63                let nearest = if let ScalarValue::Float64(Some(val)) = nearest_scalar {
64                    *val
65                } else {
66                    let null_array = Float64Array::new_null(value_array.len());
67                    return Ok(ColumnarValue::Array(Arc::new(null_array)));
68                };
69                let op = |a: f64| Self::round_to_nearest(a, nearest);
70                let result: PrimitiveArray<Float64Type> =
71                    value_array.as_primitive::<Float64Type>().unary(op);
72                Ok(ColumnarValue::Array(Arc::new(result) as _))
73            }
74            ColumnarValue::Array(nearest_array) => {
75                let value_array = value_array.as_primitive::<Float64Type>();
76                let nearest_array = nearest_array.as_primitive::<Float64Type>();
77                error::ensure(
78                    value_array.len() == nearest_array.len(),
79                    DataFusionError::Execution(format!(
80                        "input arrays should have the same length, found {} and {}",
81                        value_array.len(),
82                        nearest_array.len()
83                    )),
84                )?;
85
86                let result: PrimitiveArray<Float64Type> = datatypes::arrow::compute::binary(
87                    value_array,
88                    nearest_array,
89                    Self::round_to_nearest,
90                )
91                .map_err(|err: ArrowError| DataFusionError::ArrowError(Box::new(err), None))?;
92
93                Ok(ColumnarValue::Array(Arc::new(result) as _))
94            }
95        }
96    }
97
98    /// Follows Prometheus `funcRound`: multiplying by the inverse of `nearest` and dividing by it
99    /// again (not `/ nearest` then `* nearest`) can move a `floor` result by a whole step.
100    /// `nearest == 0` gives NaN; with a positive `nearest`, ties round towards +Inf.
101    pub(crate) fn round_to_nearest(value: f64, nearest: f64) -> f64 {
102        let inverse = 1.0 / nearest;
103        (value * inverse + 0.5).floor() / inverse
104    }
105}
106
107#[cfg(test)]
108mod tests {
109    use datafusion_common::config::ConfigOptions;
110    use datafusion_expr::ScalarFunctionArgs;
111    use datatypes::arrow::array::Float64Array;
112    use datatypes::arrow::datatypes::Field;
113
114    use super::*;
115
116    fn test_round_f64(value: Vec<f64>, nearest: f64, expected: Vec<f64>) {
117        let round_udf = Round::scalar_udf();
118        let input = vec![
119            ColumnarValue::Array(Arc::new(Float64Array::from(value))),
120            ColumnarValue::Scalar(ScalarValue::Float64(Some(nearest))),
121        ];
122        let arg_fields = vec![
123            Arc::new(Field::new("a", input[0].data_type(), false)),
124            Arc::new(Field::new("b", input[1].data_type(), false)),
125        ];
126        let return_field = Arc::new(Field::new("c", DataType::Float64, false));
127        let args = ScalarFunctionArgs {
128            args: input,
129            arg_fields,
130            number_rows: 1,
131            return_field,
132            config_options: Arc::new(ConfigOptions::default()),
133        };
134        let result = round_udf.invoke_with_args(args).unwrap();
135        let result_array = extract_array(&result).unwrap();
136        assert_eq!(result_array.len(), 1);
137        assert_eq!(
138            result_array.as_primitive::<Float64Type>().values(),
139            &expected
140        );
141    }
142
143    #[test]
144    fn test_round() {
145        // Expected values are Prometheus 3.15 `round()` results.
146        test_round_f64(vec![123.456], 0.001, vec![123.456]);
147        test_round_f64(vec![123.456], 0.01, vec![123.46]);
148        test_round_f64(vec![123.456], 0.1, vec![123.5]);
149        test_round_f64(vec![123.456], 1.0, vec![123.0]);
150        test_round_f64(vec![123.456], 10.0, vec![120.0]);
151        test_round_f64(vec![123.456], 100.0, vec![100.0]);
152        test_round_f64(vec![123.456], 105.0, vec![104.99999999999999]);
153        test_round_f64(vec![123.456], 1000.0, vec![0.0]);
154    }
155
156    #[test]
157    fn test_round_ties_towards_positive_infinity() {
158        test_round_f64(vec![-0.5], 1.0, vec![0.0]);
159        test_round_f64(vec![-2.5], 1.0, vec![-2.0]);
160        test_round_f64(vec![2.5], 1.0, vec![3.0]);
161    }
162
163    #[test]
164    fn test_round_to_zero_is_nan() {
165        let round_udf = Round::scalar_udf();
166        let input = vec![
167            ColumnarValue::Array(Arc::new(Float64Array::from(vec![123.456]))),
168            ColumnarValue::Scalar(ScalarValue::Float64(Some(0.0))),
169        ];
170        let arg_fields = vec![
171            Arc::new(Field::new("a", input[0].data_type(), false)),
172            Arc::new(Field::new("b", input[1].data_type(), false)),
173        ];
174        let args = ScalarFunctionArgs {
175            args: input,
176            arg_fields,
177            number_rows: 1,
178            return_field: Arc::new(Field::new("c", DataType::Float64, false)),
179            config_options: Arc::new(ConfigOptions::default()),
180        };
181        let result = extract_array(&round_udf.invoke_with_args(args).unwrap()).unwrap();
182        assert!(result.as_primitive::<Float64Type>().value(0).is_nan());
183    }
184}