-
Notifications
You must be signed in to change notification settings - Fork 4k
ARROW-6947: [Rust] [DataFusion] Scalar UDF support #6749
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
14c72e8
Implement Scalar UDF support (WIP)
andygrove 967da36
remove panic
andygrove 13305ac
rebase
andygrove 905cd64
unit test passes
andygrove 16d9a53
remove unwrap from test
andygrove a4d7631
implement sqrt as first built-in scalar function
andygrove b7bacbd
code cleanup
andygrove 2e440ce
rebase
andygrove fee950a
implement some common unary math expressions
andygrove d490521
Implement type coercion for scalar function arguments
andygrove 32496a6
add convenience methods for creating logical unary math expressions
andygrove 08bd701
code cleanup
andygrove 8250e90
formatting
andygrove File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
114 changes: 114 additions & 0 deletions
114
rust/datafusion/src/execution/physical_plan/math_expressions.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| // Licensed to the Apache Software Foundation (ASF) under one | ||
| // or more contributor license agreements. See the NOTICE file | ||
| // distributed with this work for additional information | ||
| // regarding copyright ownership. The ASF licenses this file | ||
| // to you under the Apache License, Version 2.0 (the | ||
| // "License"); you may not use this file except in compliance | ||
| // with the License. You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, | ||
| // software distributed under the License is distributed on an | ||
| // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| // KIND, either express or implied. See the License for the | ||
| // specific language governing permissions and limitations | ||
| // under the License. | ||
|
|
||
| //! Math expressions | ||
|
|
||
| use crate::error::ExecutionError; | ||
| use crate::execution::context::ExecutionContext; | ||
| use crate::execution::physical_plan::udf::ScalarFunction; | ||
|
|
||
| use arrow::array::{Array, ArrayRef, Float64Array, Float64Builder}; | ||
| use arrow::datatypes::{DataType, Field}; | ||
|
|
||
| use std::sync::Arc; | ||
|
|
||
| macro_rules! math_unary_function { | ||
| ($NAME:expr, $FUNC:ident) => { | ||
| ScalarFunction::new( | ||
| $NAME, | ||
| vec![Field::new("n", DataType::Float64, true)], | ||
| DataType::Float64, | ||
| |args: &Vec<ArrayRef>| { | ||
| let n = &args[0].as_any().downcast_ref::<Float64Array>(); | ||
| match n { | ||
| Some(array) => { | ||
| let mut builder = Float64Builder::new(array.len()); | ||
| for i in 0..array.len() { | ||
| if array.is_null(i) { | ||
| builder.append_null()?; | ||
| } else { | ||
| builder.append_value(array.value(i).$FUNC())?; | ||
| } | ||
| } | ||
| Ok(Arc::new(builder.finish())) | ||
| } | ||
| _ => Err(ExecutionError::General(format!( | ||
| "Invalid data type for {}", | ||
| $NAME | ||
| ))), | ||
| } | ||
| }, | ||
| ) | ||
| }; | ||
| } | ||
|
|
||
| /// Register math scalar functions with the context | ||
| pub fn register_math_functions(ctx: &mut ExecutionContext) { | ||
| ctx.register_udf(math_unary_function!("sqrt", sqrt)); | ||
| ctx.register_udf(math_unary_function!("sin", sin)); | ||
| ctx.register_udf(math_unary_function!("cos", cos)); | ||
| ctx.register_udf(math_unary_function!("tan", tan)); | ||
| ctx.register_udf(math_unary_function!("asin", asin)); | ||
| ctx.register_udf(math_unary_function!("acos", acos)); | ||
| ctx.register_udf(math_unary_function!("atan", atan)); | ||
| ctx.register_udf(math_unary_function!("floor", floor)); | ||
| ctx.register_udf(math_unary_function!("ceil", ceil)); | ||
| ctx.register_udf(math_unary_function!("round", round)); | ||
| ctx.register_udf(math_unary_function!("trunc", trunc)); | ||
| ctx.register_udf(math_unary_function!("abs", abs)); | ||
| ctx.register_udf(math_unary_function!("signum", signum)); | ||
| ctx.register_udf(math_unary_function!("exp", exp)); | ||
| ctx.register_udf(math_unary_function!("log", ln)); | ||
| ctx.register_udf(math_unary_function!("log2", log2)); | ||
| ctx.register_udf(math_unary_function!("log10", log10)); | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use crate::error::Result; | ||
| use crate::logicalplan::{sqrt, Expr, LogicalPlanBuilder}; | ||
| use arrow::datatypes::Schema; | ||
|
|
||
| #[test] | ||
| fn cast_i8_input() -> Result<()> { | ||
| let schema = Schema::new(vec![Field::new("c0", DataType::Int8, true)]); | ||
| let plan = LogicalPlanBuilder::scan("", "", &schema, None)? | ||
| .project(vec![sqrt(Expr::UnresolvedColumn("c0".to_owned()))])? | ||
| .build()?; | ||
| let ctx = ExecutionContext::new(); | ||
| let plan = ctx.optimize(&plan)?; | ||
| let expected = "Projection: sqrt(CAST(#0 AS Float64))\ | ||
| \n TableScan: projection=Some([0])"; | ||
| assert_eq!(format!("{:?}", plan), expected); | ||
| Ok(()) | ||
| } | ||
|
|
||
| #[test] | ||
| fn no_cast_f64_input() -> Result<()> { | ||
| let schema = Schema::new(vec![Field::new("c0", DataType::Float64, true)]); | ||
| let plan = LogicalPlanBuilder::scan("", "", &schema, None)? | ||
| .project(vec![sqrt(Expr::UnresolvedColumn("c0".to_owned()))])? | ||
| .build()?; | ||
| let ctx = ExecutionContext::new(); | ||
| let plan = ctx.optimize(&plan)?; | ||
| let expected = "Projection: sqrt(#0)\ | ||
| \n TableScan: projection=Some([0])"; | ||
| assert_eq!(format!("{:?}", plan), expected); | ||
| Ok(()) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This looks great, I'll try and do a proper review soon. Are there any considerations we need to make here for the fact that
math_unary_functionassumesf64, will this panic onf32input?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That's a great point. We need the type coercion optimizer rule to take care of this by automatically casting expressions to the required type where possible or failing at that stage if types are not compatible. I will work on this today.