andygrove commented on code in PR #344:
URL: https://github.com/apache/datafusion-spark/pull/344#discussion_r4669575561
##########
crates/spark/src/function/math/log1p.rs:
##########
@@ -0,0 +1,117 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
+
+use crate::function::implicit_cast::{SparkInputType, SparkInputTypes};
+use arrow::array::{ArrayRef, AsArray, Float64Array};
+use arrow::datatypes::{DataType, Float64Type};
+use datafusion_common::config::ConfigOptions;
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{Result, ScalarValue, internal_err};
+use datafusion_expr::{
+ ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl,
+ Signature, Volatility,
+};
+use datafusion_macros::user_doc;
+use std::sync::Arc;
+
+/// Spark-compatible `log1p` expression.
+///
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#log1p>
+#[user_doc(
+ doc_section(label = "Math Functions"),
+ description = "Returns `ln(1 + expr)` as a DOUBLE, computed accurately
when `expr` is \
+ close to 0. Values less than or equal to -1 return NULL. NULL input
returns NULL.",
+ syntax_example = "log1p(expr)",
+ sql_example = r#"```sql
+> SELECT log1p(0);
+0
+> SELECT log1p(-1);
+NULL
+```"#,
+ argument(
+ name = "expr",
+ description = "Numeric expression evaluated as DOUBLE. Values <= -1
and NULL return NULL."
+ )
+)]
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkLog1p {
+ input_types: SparkInputTypes,
+}
+
+impl Default for SparkLog1p {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkLog1p {
+ pub fn new() -> Self {
+ Self {
+ input_types: SparkInputTypes::new(
+ vec![SparkInputType::Double],
+ Volatility::Immutable,
+ ),
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkLog1p {
+ fn name(&self) -> &str {
+ "log1p"
+ }
+
+ fn signature(&self) -> &Signature {
+ self.input_types.signature()
+ }
+
+ fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
+ self.input_types.coerce(self.name(), arg_types)
+ }
+
+ fn with_updated_config(&self, config: &ConfigOptions) -> Option<ScalarUDF>
{
+ let input_types = self.input_types.with_config(config)?;
+ Some(ScalarUDF::from(Self { input_types }))
+ }
+
+ fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
+ Ok(DataType::Float64)
+ }
+
+ fn documentation(&self) -> Option<&Documentation> {
+ self.doc()
+ }
+
+ fn invoke_with_args(&self, args: ScalarFunctionArgs) ->
Result<ColumnarValue> {
+ let [arg] = take_function_args(self.name(), args.args)?;
+
+ match arg {
+ ColumnarValue::Scalar(ScalarValue::Float64(value)) => {
+ Ok(ColumnarValue::Scalar(ScalarValue::Float64(
+ value.and_then(log1p_or_null),
+ )))
+ }
+ ColumnarValue::Array(array) => {
+ let result: Float64Array = array
+ .as_primitive::<Float64Type>()
+ .iter()
+ .map(|value| value.and_then(log1p_or_null))
+ .collect();
+
+ Ok(ColumnarValue::Array(Arc::new(result) as ArrayRef))
+ }
+ other => internal_err!(
+ "Unexpected argument type for log1p after coercion: {}",
+ other.data_type()
+ ),
+ }
+ }
+}
+
+fn log1p_or_null(value: f64) -> Option<f64> {
+ if value <= -1.0 {
+ None
+ } else {
+ Some(value.ln_1p())
Review Comment:
`ln_1p` calls the platform's C math library, while Spark uses
`StrictMath.log1p`. The two disagree in the last bit for some inputs. I
compared about 190,000 doubles against PySpark 4.2.0 on macOS and about 4%
differed by one ulp. For example, Spark returns `0.4236646458833637` for
`log1p(0.5275492379532281)` and this returns `0.42366464588336367`. The values
in `log1p.slt` happen to agree, so nothing fails.
It's the same platform libm problem as #358 for `expm1`, so I don't think it
needs solving in this PR. Could you add a short comment here that links #358?
Then the difference is recorded next to the code.
##########
crates/sqllogictest/test_files/math/log1p.slt:
##########
@@ -2,13 +2,104 @@
# SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
# SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under
one or more contributor license agreements
-# This file was originally created by a porting script from:
-#
https://github.com/lakehq/sail/tree/43b6ed8221de5c4c4adbedbb267ae1351158b43c/crates/sail-spark-connect/tests/gold_data/function
-# This file is part of the implementation of the datafusion-spark function
library.
-# For more information, please see:
-# https://github.com/apache/datafusion/issues/15914
-
-## Original Query: SELECT log1p(0);
-## PySpark 3.5.5 Result: {'LOG1P(0)': 0.0, 'typeof(LOG1P(0))': 'double',
'typeof(0)': 'int'}
-#query
-#SELECT log1p(0::int);
+# Basic values and a negative input within the domain
+query R
+SELECT log1p(0.5::DOUBLE);
+----
+0.4054651081081644
+
+query R
+SELECT log1p(1.0::DOUBLE);
+----
+0.6931471805599453
+
+query R
+SELECT log1p(-0.5::DOUBLE);
+----
+-0.6931471805599453
+
+# A value immediately greater than the boundary -1
+query R
+SELECT log1p(-0.9999999999999999::DOUBLE);
+----
+-36.7368005696771
+
+# The boundary and values outside the domain return NULL
+query R
+SELECT log1p(-1.0::DOUBLE);
+----
+NULL
+
+query R
+SELECT log1p(-2.0::DOUBLE);
+----
+NULL
+
+query R
+SELECT log1p(CAST('-Infinity' AS DOUBLE));
+----
+NULL
+
+# NULL input returns NULL
+query R
+SELECT log1p(CAST(NULL AS DOUBLE));
+----
+NULL
+
+# Evaluate multiple values in a column
+query R
+SELECT log1p(a)
+FROM (VALUES
+ (0.0::DOUBLE),
+ (0.5::DOUBLE),
+ (-0.5::DOUBLE),
+ (-1.0::DOUBLE)
+) AS t(a);
+----
+0
+0.4054651081081644
+-0.6931471805599453
+NULL
+
+# Small inputs retain precision near zero
+query T
+SELECT log1p(1e-300::DOUBLE) = 1e-300::DOUBLE;
+----
+true
+
+query T
+SELECT log1p(1e-20::DOUBLE) = 1e-20::DOUBLE;
+----
+true
+
+# NaN and positive infinity are preserved
+query R
+SELECT log1p(CAST('NaN' AS DOUBLE));
+----
+NaN
+
+query R
+SELECT log1p(CAST('Infinity' AS DOUBLE));
+----
+Infinity
+
+# Integer, float, decimal, and string inputs
+query R
+SELECT log1p(CAST(1 AS INT));
+----
+0.6931471805599453
+
+query R
+SELECT log1p(CAST(0.5 AS FLOAT));
+----
+0.4054651081081644
+
+query R
+SELECT log1p(CAST(0.5 AS DECIMAL(10, 2)));
+----
+0.4054651081081644
+
+query R
+SELECT log1p('0.5');
+----
+0.4054651081081644
Review Comment:
Following up here since these didn't make it in. I checked them against
PySpark 4.2.0 and against this branch.
`log1p(true)`, `log1p('2020-01-01'::DATE)` and `log1p(X'01')` already fail
at planning with `UNEXPECTED_INPUT_TYPE`, as in Spark with ANSI on and off. So
they can be plain `query error` tests.
`log1p('abc')` is the one that differs. Spark returns NULL with ANSI off,
but this branch errors in both modes because the cast goes through Arrow.
That's the cast gap tracked by #88, so it can carry an `xfail` marker like
`datetime/make_date.slt` does. This block passes here and in the PySpark runner:
```
# Spark rejects BOOLEAN, DATE and BINARY arguments
query error UNEXPECTED_INPUT_TYPE
SELECT log1p(true);
query error UNEXPECTED_INPUT_TYPE
SELECT log1p('2020-01-01'::DATE);
query error UNEXPECTED_INPUT_TYPE
SELECT log1p(X'01');
# xfail spark: Spark returns NULL for a malformed string with ANSI mode off,
DataFusion's cast errors (https://github.com/apache/datafusion-spark/issues/88)
query error Cannot cast string 'abc' to value of Float64 type
SELECT log1p('abc');
statement ok
set datafusion.execution.enable_ansi_mode = true;
query error Cannot cast string 'abc' to value of Float64 type
SELECT log1p('abc');
statement ok
set datafusion.execution.enable_ansi_mode = false;
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]