You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by "alamb (via GitHub)" <gi...@apache.org> on 2023/06/29 19:25:00 UTC

[GitHub] [arrow-rs] alamb commented on a diff in pull request #4465: Add Datum based arithmetic kernels (#3999)

alamb commented on code in PR #4465:
URL: https://github.com/apache/arrow-rs/pull/4465#discussion_r1247018083


##########
arrow-arith/src/operation.rs:
##########
@@ -0,0 +1,419 @@
+// 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.
+
+//! Arrow arithmetic operations
+
+use crate::arity::{binary, try_binary};
+use arrow_array::cast::AsArray;
+use arrow_array::types::*;
+use arrow_array::*;
+use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
+use std::sync::Arc;
+
+/// Perform addition between two `Datum`

Review Comment:
   ```suggestion
   /// Perform addition between two [`Datum`]
   ```



##########
arrow-arith/src/operation.rs:
##########
@@ -0,0 +1,419 @@
+// 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.
+
+//! Arrow arithmetic operations
+
+use crate::arity::{binary, try_binary};
+use arrow_array::cast::AsArray;
+use arrow_array::types::*;
+use arrow_array::*;
+use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
+use std::sync::Arc;
+
+/// Perform addition between two `Datum`
+///
+/// An error will be returned if this results in overflow
+pub fn add(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Add, lhs, rhs)
+}
+
+/// Perform addition between two `Datum`
+///
+/// Unlike [`add`] this will not return an error for integer overflow
+pub fn add_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::AddWrapping, lhs, rhs)
+}
+
+/// Perform addition between two `Datum`
+///
+/// An error will be returned if this results in overflow
+pub fn sub(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Sub, lhs, rhs)
+}
+
+/// Perform subtraction between two `Datum`
+///
+/// Unlike [`sub`] this will not return an error for integer overflow
+pub fn sub_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::SubWrapping, lhs, rhs)
+}
+
+/// Perform multiplication between two `Datum`
+///
+/// An error will be returned if this results in overflow
+pub fn mul(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Mul, lhs, rhs)
+}
+
+/// Perform multiplication between two `Datum`
+///
+/// Unlike [`mul`] this will not return an error for integer overflow
+pub fn mul_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::MulWrapping, lhs, rhs)
+}
+
+/// Perform division between two `Datum`
+///
+/// An error will be returned if this results in overflow or would divide by zero
+pub fn div(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Div, lhs, rhs)
+}
+
+/// Compute the remainder of division of two `Datum`
+///
+/// An error will be returned if this results in overflow or would divide by zero
+pub fn rem(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Rem, lhs, rhs)
+}
+
+/// An enumeration of arithmetic operations
+///
+/// This allows sharing the type dispatch logic across the various kernels
+#[derive(Debug, Copy, Clone)]
+enum Op {
+    AddWrapping,
+    Add,
+    SubWrapping,
+    Sub,
+    MulWrapping,
+    Mul,
+    Div,
+    Rem,
+}
+
+/// Dispatch the given `op` to the appropriate specialized kernel
+fn arithmetic_op(
+    op: Op,
+    lhs: &dyn Datum,
+    rhs: &dyn Datum,
+) -> Result<ArrayRef, ArrowError> {
+    use DataType::*;
+    use TimeUnit::*;
+
+    macro_rules! integer_helper {
+        ($t:ty, $op:ident, $l:ident, $l_scalar:ident, $r:ident, $r_scalar:ident) => {
+            integer_op::<$t>($op, $l, $l_scalar, $r, $r_scalar)
+        };
+    }
+
+    let (l, l_scalar) = lhs.get();
+    let (r, r_scalar) = rhs.get();
+    downcast_integer! {
+        l.data_type(), r.data_type() => (integer_helper, op, l, l_scalar, r, r_scalar),
+        (Float16, Float16) => float_op::<Float16Type>(op, l, l_scalar, r, r_scalar),
+        (Float32, Float32) => float_op::<Float32Type>(op, l, l_scalar, r, r_scalar),
+        (Float64, Float64) => float_op::<Float64Type>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Second, _), _) => timestamp_op::<TimestampSecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Millisecond, _), _) => timestamp_op::<TimestampMillisecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Microsecond, _), _) => timestamp_op::<TimestampMicrosecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Nanosecond, _), _) => timestamp_op::<TimestampNanosecondType>(op, l, l_scalar, r, r_scalar),
+        (Date32, _) => date_op::<Date32Type>(op, l, l_scalar, r, r_scalar),
+        (Date64, _) => date_op::<Date64Type>(op, l, l_scalar, r, r_scalar),
+        (l_t, r_t) => Err(ArrowError::InvalidArgumentError(
+            format!("Invalid arithmetic operation: {l_t} {op:?} {r_t}")
+        ))
+    }
+}
+
+/// Perform an infallible binary operation on potentially scalar inputs

Review Comment:
   A nit might be to document that `$l` means the left array and `$l_s` is true f that array should be treated as a scalar (single value)



##########
arrow-arith/src/operation.rs:
##########
@@ -0,0 +1,419 @@
+// 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.
+
+//! Arrow arithmetic operations
+
+use crate::arity::{binary, try_binary};
+use arrow_array::cast::AsArray;
+use arrow_array::types::*;
+use arrow_array::*;
+use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
+use std::sync::Arc;
+
+/// Perform addition between two `Datum`
+///
+/// An error will be returned if this results in overflow
+pub fn add(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Add, lhs, rhs)
+}
+
+/// Perform addition between two `Datum`
+///
+/// Unlike [`add`] this will not return an error for integer overflow
+pub fn add_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::AddWrapping, lhs, rhs)
+}
+
+/// Perform addition between two `Datum`
+///
+/// An error will be returned if this results in overflow
+pub fn sub(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Sub, lhs, rhs)
+}
+
+/// Perform subtraction between two `Datum`
+///
+/// Unlike [`sub`] this will not return an error for integer overflow
+pub fn sub_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::SubWrapping, lhs, rhs)
+}
+
+/// Perform multiplication between two `Datum`
+///
+/// An error will be returned if this results in overflow
+pub fn mul(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Mul, lhs, rhs)
+}
+
+/// Perform multiplication between two `Datum`
+///
+/// Unlike [`mul`] this will not return an error for integer overflow
+pub fn mul_wrapping(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::MulWrapping, lhs, rhs)
+}
+
+/// Perform division between two `Datum`
+///
+/// An error will be returned if this results in overflow or would divide by zero
+pub fn div(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Div, lhs, rhs)
+}
+
+/// Compute the remainder of division of two `Datum`
+///
+/// An error will be returned if this results in overflow or would divide by zero
+pub fn rem(lhs: &dyn Datum, rhs: &dyn Datum) -> Result<ArrayRef, ArrowError> {
+    arithmetic_op(Op::Rem, lhs, rhs)
+}
+
+/// An enumeration of arithmetic operations
+///
+/// This allows sharing the type dispatch logic across the various kernels
+#[derive(Debug, Copy, Clone)]
+enum Op {
+    AddWrapping,
+    Add,
+    SubWrapping,
+    Sub,
+    MulWrapping,
+    Mul,
+    Div,
+    Rem,
+}
+
+/// Dispatch the given `op` to the appropriate specialized kernel
+fn arithmetic_op(
+    op: Op,
+    lhs: &dyn Datum,
+    rhs: &dyn Datum,
+) -> Result<ArrayRef, ArrowError> {
+    use DataType::*;
+    use TimeUnit::*;
+
+    macro_rules! integer_helper {
+        ($t:ty, $op:ident, $l:ident, $l_scalar:ident, $r:ident, $r_scalar:ident) => {
+            integer_op::<$t>($op, $l, $l_scalar, $r, $r_scalar)
+        };
+    }
+
+    let (l, l_scalar) = lhs.get();
+    let (r, r_scalar) = rhs.get();
+    downcast_integer! {
+        l.data_type(), r.data_type() => (integer_helper, op, l, l_scalar, r, r_scalar),
+        (Float16, Float16) => float_op::<Float16Type>(op, l, l_scalar, r, r_scalar),
+        (Float32, Float32) => float_op::<Float32Type>(op, l, l_scalar, r, r_scalar),
+        (Float64, Float64) => float_op::<Float64Type>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Second, _), _) => timestamp_op::<TimestampSecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Millisecond, _), _) => timestamp_op::<TimestampMillisecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Microsecond, _), _) => timestamp_op::<TimestampMicrosecondType>(op, l, l_scalar, r, r_scalar),
+        (Timestamp(Nanosecond, _), _) => timestamp_op::<TimestampNanosecondType>(op, l, l_scalar, r, r_scalar),
+        (Date32, _) => date_op::<Date32Type>(op, l, l_scalar, r, r_scalar),
+        (Date64, _) => date_op::<Date64Type>(op, l, l_scalar, r, r_scalar),
+        (l_t, r_t) => Err(ArrowError::InvalidArgumentError(
+            format!("Invalid arithmetic operation: {l_t} {op:?} {r_t}")
+        ))
+    }
+}
+
+/// Perform an infallible binary operation on potentially scalar inputs
+macro_rules! op {
+    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
+        match ($l_s, $r_s) {
+            (true, true) | (false, false) => binary($l, $r, |$l, $r| $op)?,
+            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
+                None => PrimitiveArray::new_null($r.len()),
+                Some($l) => $r.unary(|$r| $op),
+            },
+            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
+                None => PrimitiveArray::new_null($l.len()),
+                Some($r) => $l.unary(|$l| $op),
+            },
+        }
+    };
+}
+
+/// Same as `op` but with a type hint for the returned array
+macro_rules! op_ref {
+    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
+        let array: PrimitiveArray<$t> = op!($l, $l_s, $r, $r_s, $op);
+        Arc::new(array)
+    }};
+}
+
+/// Perform a fallible binary operation on potentially scalar inputs
+macro_rules! try_op {
+    ($l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {
+        match ($l_s, $r_s) {
+            (true, true) | (false, false) => try_binary($l, $r, |$l, $r| $op)?,
+            (true, false) => match ($l.null_count() == 0).then(|| $l.value(0)) {
+                None => PrimitiveArray::new_null($r.len()),
+                Some($l) => $r.try_unary(|$r| $op)?,
+            },
+            (false, true) => match ($r.null_count() == 0).then(|| $r.value(0)) {
+                None => PrimitiveArray::new_null($l.len()),
+                Some($r) => $l.try_unary(|$l| $op)?,
+            },
+        }
+    };
+}
+
+/// Same as `try_op` but with a type hint for the returned array
+macro_rules! try_op_ref {
+    ($t:ty, $l:ident, $l_s:expr, $r:ident, $r_s:expr, $op:expr) => {{
+        let array: PrimitiveArray<$t> = try_op!($l, $l_s, $r, $r_s, $op);
+        Arc::new(array)
+    }};
+}
+
+/// Perform an arithmetic operation on integers
+fn integer_op<T: ArrowPrimitiveType>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    let l = l.as_primitive::<T>();
+    let r = r.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match op {
+        Op::AddWrapping => op!(l, l_s, r, r_s, l.add_wrapping(r)),
+        Op::Add => try_op!(l, l_s, r, r_s, l.add_checked(r)),
+        Op::SubWrapping => op!(l, l_s, r, r_s, l.sub_wrapping(r)),
+        Op::Sub => try_op!(l, l_s, r, r_s, l.sub_checked(r)),
+        Op::MulWrapping => op!(l, l_s, r, r_s, l.mul_wrapping(r)),
+        Op::Mul => try_op!(l, l_s, r, r_s, l.mul_checked(r)),
+        Op::Div => try_op!(l, l_s, r, r_s, l.div_checked(r)),
+        Op::Rem => try_op!(l, l_s, r, r_s, l.div_checked(r)),
+    };
+    Ok(Arc::new(array))
+}
+
+/// Perform an arithmetic operation on floats
+fn float_op<T: ArrowPrimitiveType>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    let l = l.as_primitive::<T>();
+    let r = r.as_primitive::<T>();
+    let array: PrimitiveArray<T> = match op {
+        Op::AddWrapping | Op::Add => op!(l, l_s, r, r_s, l.add_wrapping(r)),
+        Op::SubWrapping | Op::Sub => op!(l, l_s, r, r_s, l.sub_wrapping(r)),
+        Op::MulWrapping | Op::Mul => op!(l, l_s, r, r_s, l.mul_wrapping(r)),
+        Op::Div => try_op!(l, l_s, r, r_s, l.div_checked(r)),
+        Op::Rem => try_op!(l, l_s, r, r_s, l.div_checked(r)),
+    };
+    Ok(Arc::new(array))
+}
+
+/// Arithmetic trait for timestamp arrays
+trait TimestampOp: ArrowTimestampType {
+    type Duration: ArrowPrimitiveType<Native = i64>;
+
+    fn add_year_month(timestamp: i64, delta: i32) -> Result<i64, ArrowError>;
+    fn add_day_time(timestamp: i64, delta: i64) -> Result<i64, ArrowError>;
+    fn add_month_day_nano(timestamp: i64, delta: i128) -> Result<i64, ArrowError>;
+
+    fn sub_year_month(timestamp: i64, delta: i32) -> Result<i64, ArrowError>;
+    fn sub_day_time(timestamp: i64, delta: i64) -> Result<i64, ArrowError>;
+    fn sub_month_day_nano(timestamp: i64, delta: i128) -> Result<i64, ArrowError>;
+}
+
+macro_rules! timestamp {
+    ($t:ty, $d:ty) => {
+        impl TimestampOp for $t {
+            type Duration = $d;
+
+            fn add_year_month(left: i64, right: i32) -> Result<i64, ArrowError> {
+                Self::add_year_months(left, right)
+            }
+
+            fn add_day_time(left: i64, right: i64) -> Result<i64, ArrowError> {
+                Self::add_day_time(left, right)
+            }
+
+            fn add_month_day_nano(left: i64, right: i128) -> Result<i64, ArrowError> {
+                Self::add_month_day_nano(left, right)
+            }
+
+            fn sub_year_month(left: i64, right: i32) -> Result<i64, ArrowError> {
+                Self::subtract_year_months(left, right)
+            }
+
+            fn sub_day_time(left: i64, right: i64) -> Result<i64, ArrowError> {
+                Self::subtract_day_time(left, right)
+            }
+
+            fn sub_month_day_nano(left: i64, right: i128) -> Result<i64, ArrowError> {
+                Self::subtract_month_day_nano(left, right)
+            }
+        }
+    };
+}
+timestamp!(TimestampSecondType, DurationSecondType);
+timestamp!(TimestampMillisecondType, DurationMillisecondType);
+timestamp!(TimestampMicrosecondType, DurationMicrosecondType);
+timestamp!(TimestampNanosecondType, DurationNanosecondType);
+
+/// Perform arithmetic operation on a timestamp array
+fn timestamp_op<T: TimestampOp>(
+    op: Op,
+    l: &dyn Array,
+    l_s: bool,
+    r: &dyn Array,
+    r_s: bool,
+) -> Result<ArrayRef, ArrowError> {
+    use DataType::*;
+    use IntervalUnit::*;
+
+    // Note: interval arithmetic should account for timezones (#4457)
+    let l = l.as_primitive::<T>();

Review Comment:
   this is quite beautiful 🤗 



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org