You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2021/01/25 06:04:20 UTC

[GitHub] [arrow] nevi-me opened a new pull request #9313: [Rust] [Experiment] Trigonometry kernels

nevi-me opened a new pull request #9313:
URL: https://github.com/apache/arrow/pull/9313


   This is on top of #9297
   
   I was curious if (ab)using the `compute::unary` kernel would perform better on slightly complex functions.
   
   I implemented the Haversine function, which calculates the distance between two geographic coordinates.
   I then benchmarked an implementation that I tried to simplify and optimise with unary kernels, vs one that I'd have to write if I couldn't use the unary kernels for things like:
   - arithmetics with scalars
   - functions that would otherwise require generating intermediate arrays (e.g. `sin(x) * cos(x)` would be `multiply(sin(x), cos(x))`)
   
   The function that uses unary kernels for the above, is slightly faster.
   
   I ran this on an M1 CPU, with the below options
   
   ```sh
   cargo bench --bench trigonometry_kernels
   cargo bench --bench trigonometry_kernels --features simd
   RUSTFLAGS="-C target-cpu=native" cargo bench --bench trigonometry_kernels
   RUSTFLAGS="-C target-cpu=native" cargo bench --bench trigonometry_kernels --features simd
   ```
   
   ```rust
   haversine_no_unary 512  time:   [14.074 us 14.140 us 14.216 us]
   
   haversine_unary 512     time:   [11.191 us 11.308 us 11.436 us]
   haversine_no_unary_nulls 512                                                                             
                           time:   [15.902 us 15.985 us 16.083 us]
   
   haversine_unary_nulls 512                                                                             
                           time:   [12.486 us 12.552 us 12.625 us]
   ```
   
   The biggest benefit is from setting the `RUSTFLAGS`, the non-null benches go 3-10% faster.


----------------------------------------------------------------
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.

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



[GitHub] [arrow] nevi-me commented on a change in pull request #9313: [Rust] [Experiment] Trigonometry kernels

Posted by GitBox <gi...@apache.org>.
nevi-me commented on a change in pull request #9313:
URL: https://github.com/apache/arrow/pull/9313#discussion_r571739666



##########
File path: rust/arrow/src/compute/kernels/math.rs
##########
@@ -0,0 +1,51 @@
+// 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.
+
+//! Defines basic math kernels for `PrimitiveArrays`.
+
+use num::Float;
+
+use crate::datatypes::ArrowNumericType;
+use crate::{array::*, float_unary};
+
+use super::arity::unary;
+
+float_unary!(sqrt);
+
+pub fn powf<T>(array: &PrimitiveArray<T>, n: T::Native) -> PrimitiveArray<T>
+where
+    T: ArrowNumericType,

Review comment:
       This constraint might be incorrect. A `i32` shouldn't have `powf({float})`. I'll validate it when adding tests.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] nevi-me commented on pull request #9313: [Rust] [Experiment] Trigonometry kernels

Posted by GitBox <gi...@apache.org>.
nevi-me commented on pull request #9313:
URL: https://github.com/apache/arrow/pull/9313#issuecomment-768780454


   I've rebased.
   
   Ideas for the PR before I work more on it:
   
   - Are the trig kernels fine (is the direction good)?
   - Should I remove Haversine? I was using it to evaluate the performance benefit of using `unary`


----------------------------------------------------------------
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.

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



[GitHub] [arrow] nevi-me commented on a change in pull request #9313: [Rust] [Experiment] Trigonometry kernels

Posted by GitBox <gi...@apache.org>.
nevi-me commented on a change in pull request #9313:
URL: https://github.com/apache/arrow/pull/9313#discussion_r563480506



##########
File path: rust/arrow/src/compute/kernels/trigonometry.rs
##########
@@ -0,0 +1,248 @@
+// 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.
+
+//! Defines trigonometry kernels for `PrimitiveArrays` that are
+//! floats, restricted by the [num::Float] trait.
+
+use std::{iter::FromIterator, ops::Div};
+
+use num::{Float, Zero};
+
+use super::math::*;
+use crate::buffer::Buffer;
+use crate::datatypes::ArrowNumericType;
+use crate::error::Result;
+use crate::{
+    array::*,
+    compute::{add, math_op, multiply, subtract},
+    datatypes::ArrowPrimitiveType,
+    error::ArrowError,
+    float_unary,
+};
+
+use super::unary::{into_primitive_array_data, unary};
+
+float_unary!(to_degrees);
+float_unary!(to_radians);
+float_unary!(sin);
+float_unary!(cos);
+float_unary!(tan);
+float_unary!(asin);
+float_unary!(acos);
+float_unary!(atan);
+float_unary!(sinh);
+float_unary!(cosh);
+float_unary!(tanh);
+float_unary!(asinh);
+float_unary!(acosh);
+float_unary!(atanh);
+
+pub fn atan2<T>(
+    left: &PrimitiveArray<T>,
+    right: &PrimitiveArray<T>,
+) -> Result<PrimitiveArray<T>>
+where
+    T: ArrowNumericType,
+    T::Native: num::traits::Float,
+{
+    math_op(left, right, |x, y| x.atan2(y))
+}
+
+/// Perform `left * right` operation on two arrays. If either left or right value is null
+/// then the result is also null.
+pub fn sin_cos<T>(array: &PrimitiveArray<T>) -> (PrimitiveArray<T>, PrimitiveArray<T>)
+where
+    T: ArrowNumericType,
+    T::Native: num::traits::Float,
+{
+    let (sin, cos): (Vec<T::Native>, Vec<T::Native>) =
+        array.values().iter().map(|v| v.sin_cos()).unzip();
+    // NOTE: due to `unzip` collecting and splitting the arrays,
+    // this might be slower than Buffer::from_trusted_len_iter
+    let sin_buffer = Buffer::from_iter(sin);
+    let cos_buffer = Buffer::from_iter(cos);
+
+    let sin_data = into_primitive_array_data::<_, T>(array, sin_buffer);
+    let cos_data = into_primitive_array_data::<_, T>(array, cos_buffer);
+    (
+        PrimitiveArray::<T>::from(std::sync::Arc::new(sin_data)),
+        PrimitiveArray::<T>::from(std::sync::Arc::new(cos_data)),
+    )
+}
+
+/// Calculate the Haversine distance between two geographic coordinates.
+/// Based on the haversine crate.
+///
+/// The distance returned is in meters, and the radius must be specified in meters.
+pub fn haversine<T>(
+    lat_a: &PrimitiveArray<T>,
+    lng_a: &PrimitiveArray<T>,
+    lat_b: &PrimitiveArray<T>,
+    lng_b: &PrimitiveArray<T>,
+    radius: impl num::traits::Float,
+) -> Result<PrimitiveArray<T>>
+where
+    T: ArrowPrimitiveType + ArrowNumericType,
+    T::Native: num::traits::Float + Div<Output = T::Native> + Zero + num::NumCast,
+{
+    // Check array lengths, must all equal
+    let len = lat_a.len();
+    if lat_b.len() != len || lng_a.len() != len || lng_b.len() != len {
+        return Err(ArrowError::ComputeError(
+            "Cannot perform math operation on arrays of different length".to_string(),
+        ));
+    }
+    // These casts normally get optimized to f64 as f64
+    let one = num::cast::<_, T::Native>(1.0).unwrap();

Review comment:
       @jorgecarleitao I had to convert the floats to `T::Native` in order to use them in the unary kernel as part of `Fn(_)` expressions.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] github-actions[bot] commented on pull request #9313: [Rust] [Experiment] Trigonometry kernels

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on pull request #9313:
URL: https://github.com/apache/arrow/pull/9313#issuecomment-766567197


   <!--
     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.
   -->
   
   Thanks for opening a pull request!
   
   Could you open an issue for this pull request on JIRA?
   https://issues.apache.org/jira/browse/ARROW
   
   Then could you also rename pull request title in the following format?
   
       ARROW-${JIRA_ID}: [${COMPONENT}] ${SUMMARY}
   
   See also:
   
     * [Other pull requests](https://github.com/apache/arrow/pulls/)
     * [Contribution Guidelines - How to contribute patches](https://arrow.apache.org/docs/developers/contributing.html#how-to-contribute-patches)
   


----------------------------------------------------------------
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.

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



[GitHub] [arrow] nevi-me commented on a change in pull request #9313: [Rust] [Experiment] Trigonometry kernels

Posted by GitBox <gi...@apache.org>.
nevi-me commented on a change in pull request #9313:
URL: https://github.com/apache/arrow/pull/9313#discussion_r571739666



##########
File path: rust/arrow/src/compute/kernels/math.rs
##########
@@ -0,0 +1,51 @@
+// 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.
+
+//! Defines basic math kernels for `PrimitiveArrays`.
+
+use num::Float;
+
+use crate::datatypes::ArrowNumericType;
+use crate::{array::*, float_unary};
+
+use super::arity::unary;
+
+float_unary!(sqrt);
+
+pub fn powf<T>(array: &PrimitiveArray<T>, n: T::Native) -> PrimitiveArray<T>
+where
+    T: ArrowNumericType,

Review comment:
       This constraint might be incorrect. A `i32` shouldn't have `powf({float})`




----------------------------------------------------------------
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.

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



[GitHub] [arrow] nevi-me commented on pull request #9313: [Rust] [Experiment] Trigonometry kernels

Posted by GitBox <gi...@apache.org>.
nevi-me commented on pull request #9313:
URL: https://github.com/apache/arrow/pull/9313#issuecomment-773663233


   Thanks @jorgecarleitao, I'm currently constrained with time during the week. I'll finish this up over the weekend


----------------------------------------------------------------
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.

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



[GitHub] [arrow] codecov-io commented on pull request #9313: [Rust] [Experiment] Trigonometry kernels

Posted by GitBox <gi...@apache.org>.
codecov-io commented on pull request #9313:
URL: https://github.com/apache/arrow/pull/9313#issuecomment-768795748


   # [Codecov](https://codecov.io/gh/apache/arrow/pull/9313?src=pr&el=h1) Report
   > Merging [#9313](https://codecov.io/gh/apache/arrow/pull/9313?src=pr&el=desc) (ef36a3d) into [master](https://codecov.io/gh/apache/arrow/commit/53d392c1a7fe6229a4e642fedeaaccb4e0a0b8d1?el=desc) (53d392c) will **increase** coverage by `0.00%`.
   > The diff coverage is `87.01%`.
   
   [![Impacted file tree graph](https://codecov.io/gh/apache/arrow/pull/9313/graphs/tree.svg?width=650&height=150&src=pr&token=LpTCFbqVT1)](https://codecov.io/gh/apache/arrow/pull/9313?src=pr&el=tree)
   
   ```diff
   @@           Coverage Diff           @@
   ##           master    #9313   +/-   ##
   =======================================
     Coverage   81.90%   81.91%           
   =======================================
     Files         216      217    +1     
     Lines       52990    53066   +76     
   =======================================
   + Hits        43402    43468   +66     
   - Misses       9588     9598   +10     
   ```
   
   
   | [Impacted Files](https://codecov.io/gh/apache/arrow/pull/9313?src=pr&el=tree) | Coverage Δ | |
   |---|---|---|
   | [rust/arrow/src/compute/kernels/trigonometry.rs](https://codecov.io/gh/apache/arrow/pull/9313/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy9zcmMvY29tcHV0ZS9rZXJuZWxzL3RyaWdvbm9tZXRyeS5ycw==) | `86.48% <86.48%> (ø)` | |
   | [rust/arrow/src/compute/kernels/arity.rs](https://codecov.io/gh/apache/arrow/pull/9313/diff?src=pr&el=tree#diff-cnVzdC9hcnJvdy9zcmMvY29tcHV0ZS9rZXJuZWxzL2FyaXR5LnJz) | `92.85% <100.00%> (+1.19%)` | :arrow_up: |
   
   ------
   
   [Continue to review full report at Codecov](https://codecov.io/gh/apache/arrow/pull/9313?src=pr&el=continue).
   > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
   > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
   > Powered by [Codecov](https://codecov.io/gh/apache/arrow/pull/9313?src=pr&el=footer). Last update [53d392c...ef36a3d](https://codecov.io/gh/apache/arrow/pull/9313?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
   


----------------------------------------------------------------
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.

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



[GitHub] [arrow] jorgecarleitao commented on a change in pull request #9313: [Rust] [Experiment] Trigonometry kernels

Posted by GitBox <gi...@apache.org>.
jorgecarleitao commented on a change in pull request #9313:
URL: https://github.com/apache/arrow/pull/9313#discussion_r564708601



##########
File path: rust/arrow/src/compute/kernels/trigonometry.rs
##########
@@ -0,0 +1,248 @@
+// 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.
+
+//! Defines trigonometry kernels for `PrimitiveArrays` that are
+//! floats, restricted by the [num::Float] trait.
+
+use std::{iter::FromIterator, ops::Div};
+
+use num::{Float, Zero};
+
+use super::math::*;
+use crate::buffer::Buffer;
+use crate::datatypes::ArrowNumericType;
+use crate::error::Result;
+use crate::{
+    array::*,
+    compute::{add, math_op, multiply, subtract},
+    datatypes::ArrowPrimitiveType,
+    error::ArrowError,
+    float_unary,
+};
+
+use super::unary::{into_primitive_array_data, unary};
+
+float_unary!(to_degrees);
+float_unary!(to_radians);
+float_unary!(sin);
+float_unary!(cos);
+float_unary!(tan);
+float_unary!(asin);
+float_unary!(acos);
+float_unary!(atan);
+float_unary!(sinh);
+float_unary!(cosh);
+float_unary!(tanh);
+float_unary!(asinh);
+float_unary!(acosh);
+float_unary!(atanh);
+
+pub fn atan2<T>(
+    left: &PrimitiveArray<T>,
+    right: &PrimitiveArray<T>,
+) -> Result<PrimitiveArray<T>>
+where
+    T: ArrowNumericType,
+    T::Native: num::traits::Float,
+{
+    math_op(left, right, |x, y| x.atan2(y))
+}
+
+/// Perform `left * right` operation on two arrays. If either left or right value is null
+/// then the result is also null.
+pub fn sin_cos<T>(array: &PrimitiveArray<T>) -> (PrimitiveArray<T>, PrimitiveArray<T>)
+where
+    T: ArrowNumericType,
+    T::Native: num::traits::Float,
+{
+    let (sin, cos): (Vec<T::Native>, Vec<T::Native>) =
+        array.values().iter().map(|v| v.sin_cos()).unzip();
+    // NOTE: due to `unzip` collecting and splitting the arrays,
+    // this might be slower than Buffer::from_trusted_len_iter
+    let sin_buffer = Buffer::from_iter(sin);
+    let cos_buffer = Buffer::from_iter(cos);
+
+    let sin_data = into_primitive_array_data::<_, T>(array, sin_buffer);
+    let cos_data = into_primitive_array_data::<_, T>(array, cos_buffer);
+    (
+        PrimitiveArray::<T>::from(std::sync::Arc::new(sin_data)),
+        PrimitiveArray::<T>::from(std::sync::Arc::new(cos_data)),
+    )
+}
+
+/// Calculate the Haversine distance between two geographic coordinates.
+/// Based on the haversine crate.
+///
+/// The distance returned is in meters, and the radius must be specified in meters.
+pub fn haversine<T>(
+    lat_a: &PrimitiveArray<T>,
+    lng_a: &PrimitiveArray<T>,
+    lat_b: &PrimitiveArray<T>,
+    lng_b: &PrimitiveArray<T>,
+    radius: impl num::traits::Float,
+) -> Result<PrimitiveArray<T>>
+where
+    T: ArrowPrimitiveType + ArrowNumericType,
+    T::Native: num::traits::Float + Div<Output = T::Native> + Zero + num::NumCast,
+{
+    // Check array lengths, must all equal
+    let len = lat_a.len();
+    if lat_b.len() != len || lng_a.len() != len || lng_b.len() != len {
+        return Err(ArrowError::ComputeError(
+            "Cannot perform math operation on arrays of different length".to_string(),
+        ));
+    }
+    // These casts normally get optimized to f64 as f64
+    let one = num::cast::<_, T::Native>(1.0).unwrap();

Review comment:
       I did not find any easy way of doing this, also. It feels like we would need a generic of a generic. It looks good to me, though.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] github-actions[bot] commented on pull request #9313: [Rust] [Experiment] Trigonometry kernels

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on pull request #9313:
URL: https://github.com/apache/arrow/pull/9313#issuecomment-766567197


   <!--
     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.
   -->
   
   Thanks for opening a pull request!
   
   Could you open an issue for this pull request on JIRA?
   https://issues.apache.org/jira/browse/ARROW
   
   Then could you also rename pull request title in the following format?
   
       ARROW-${JIRA_ID}: [${COMPONENT}] ${SUMMARY}
   
   See also:
   
     * [Other pull requests](https://github.com/apache/arrow/pulls/)
     * [Contribution Guidelines - How to contribute patches](https://arrow.apache.org/docs/developers/contributing.html#how-to-contribute-patches)
   


----------------------------------------------------------------
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.

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



[GitHub] [arrow] alamb commented on pull request #9313: [Rust] [Experiment] Trigonometry kernels

Posted by GitBox <gi...@apache.org>.
alamb commented on pull request #9313:
URL: https://github.com/apache/arrow/pull/9313#issuecomment-789647360


   @nevi-me I am closing this PR for the time being to clean up the Rust/Arrow PR backlog.  Please let me know if this is a mistake


----------------------------------------------------------------
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.

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



[GitHub] [arrow] nevi-me commented on pull request #9313: [Rust] [Experiment] Trigonometry kernels

Posted by GitBox <gi...@apache.org>.
nevi-me commented on pull request #9313:
URL: https://github.com/apache/arrow/pull/9313#issuecomment-773663233


   Thanks @jorgecarleitao, I'm currently constrained with time during the week. I'll finish this up over the weekend


----------------------------------------------------------------
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.

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



[GitHub] [arrow] alamb closed pull request #9313: [Rust] [Experiment] Trigonometry kernels

Posted by GitBox <gi...@apache.org>.
alamb closed pull request #9313:
URL: https://github.com/apache/arrow/pull/9313


   


----------------------------------------------------------------
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.

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



[GitHub] [arrow] jorgecarleitao commented on pull request #9313: [Rust] [Experiment] Trigonometry kernels

Posted by GitBox <gi...@apache.org>.
jorgecarleitao commented on pull request #9313:
URL: https://github.com/apache/arrow/pull/9313#issuecomment-767721269


   IMO looked good to me (before the rebase), however, a more through review would need a rebase xD


----------------------------------------------------------------
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.

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



[GitHub] [arrow] jorgecarleitao commented on a change in pull request #9313: [Rust] [Experiment] Trigonometry kernels

Posted by GitBox <gi...@apache.org>.
jorgecarleitao commented on a change in pull request #9313:
URL: https://github.com/apache/arrow/pull/9313#discussion_r568778663



##########
File path: rust/arrow/benches/trigonometry_kernels.rs
##########
@@ -0,0 +1,171 @@
+// 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.
+
+#[macro_use]
+extern crate criterion;
+use criterion::Criterion;
+
+use num::Zero;
+use rand::Rng;
+use std::{ops::Div, sync::Arc};
+
+extern crate arrow;
+
+use arrow::error::{ArrowError, Result};
+use arrow::util::test_util::seedable_rng;
+use arrow::{
+    array::*,
+    compute::*,
+    datatypes::{ArrowNumericType, ArrowPrimitiveType},
+};
+
+/// This computes the Haversine formula without using unary kernels
+fn haversine_no_unary<T>(

Review comment:
       I would try to get the result from the exercise, drop this code once the best option was found, and document which was was better in implementation notes on the decided approach.

##########
File path: rust/arrow/src/compute/kernels/trigonometry.rs
##########
@@ -0,0 +1,246 @@
+// 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.
+
+//! Defines trigonometry kernels for `PrimitiveArrays` that are
+//! floats, restricted by the [num::Float] trait.
+
+use std::{iter::FromIterator, ops::Div};
+
+use num::{Float, Zero};
+
+use super::math::*;
+use crate::buffer::Buffer;
+use crate::datatypes::ArrowNumericType;
+use crate::error::Result;
+use crate::{
+    array::*,
+    compute::{add, math_op, multiply, subtract},
+    datatypes::ArrowPrimitiveType,
+    error::ArrowError,
+    float_unary,
+};
+
+use super::arity::{into_primitive_array_data, unary};
+
+float_unary!(to_degrees);
+float_unary!(to_radians);
+float_unary!(sin);
+float_unary!(cos);
+float_unary!(tan);
+float_unary!(asin);
+float_unary!(acos);
+float_unary!(atan);
+float_unary!(sinh);
+float_unary!(cosh);
+float_unary!(tanh);
+float_unary!(asinh);
+float_unary!(acosh);
+float_unary!(atanh);
+
+pub fn atan2<T>(
+    left: &PrimitiveArray<T>,
+    right: &PrimitiveArray<T>,
+) -> Result<PrimitiveArray<T>>
+where
+    T: ArrowNumericType,
+    T::Native: num::traits::Float,
+{
+    math_op(left, right, |x, y| x.atan2(y))
+}
+
+/// Perform `left * right` operation on two arrays. If either left or right value is null
+/// then the result is also null.
+pub fn sin_cos<T>(array: &PrimitiveArray<T>) -> (PrimitiveArray<T>, PrimitiveArray<T>)
+where
+    T: ArrowNumericType,
+    T::Native: num::traits::Float,
+{
+    let (sin, cos): (Vec<T::Native>, Vec<T::Native>) =
+        array.values().iter().map(|v| v.sin_cos()).unzip();
+    // NOTE: due to `unzip` collecting and splitting the arrays,
+    // this might be slower than Buffer::from_trusted_len_iter
+    let sin_buffer = Buffer::from_iter(sin);
+    let cos_buffer = Buffer::from_iter(cos);
+
+    let sin_data = into_primitive_array_data::<_, T>(array, sin_buffer);
+    let cos_data = into_primitive_array_data::<_, T>(array, cos_buffer);
+    (
+        PrimitiveArray::<T>::from(std::sync::Arc::new(sin_data)),
+        PrimitiveArray::<T>::from(std::sync::Arc::new(cos_data)),
+    )
+}
+
+/// Calculate the Haversine distance between two geographic coordinates.
+/// Based on the haversine crate.
+///
+/// The distance returned is in meters, and the radius must be specified in meters.
+pub fn haversine<T>(
+    lat_a: &PrimitiveArray<T>,
+    lng_a: &PrimitiveArray<T>,
+    lat_b: &PrimitiveArray<T>,
+    lng_b: &PrimitiveArray<T>,
+    radius: impl num::traits::Float,
+) -> Result<PrimitiveArray<T>>
+where
+    T: ArrowPrimitiveType + ArrowNumericType,
+    T::Native: num::traits::Float + Div<Output = T::Native> + Zero + num::NumCast,
+{
+    // Check array lengths, must all equal
+    let len = lat_a.len();
+    if lat_b.len() != len || lng_a.len() != len || lng_b.len() != len {
+        return Err(ArrowError::ComputeError(
+            "Cannot perform math operation on arrays of different length".to_string(),
+        ));
+    }
+    // These casts normally get optimized to f64 as f64
+    let one = num::cast::<_, T::Native>(1.0).unwrap();
+    let two = num::cast::<_, T::Native>(2.0).unwrap();
+    let radius = num::cast::<_, T::Native>(radius).unwrap();
+    let two_radius = two * radius;
+
+    let lat_delta = to_radians(&subtract(lat_b, lat_a)?);
+    let lng_delta = to_radians(&subtract(lng_b, lng_a)?);
+    let lat_a_rad = to_radians(lat_a);
+    let lat_b_rad = to_radians(lat_b);
+
+    let v1: PrimitiveArray<T> = sin(&unary::<_, _, _>(&lat_delta, |x| x / two));
+    let v2: PrimitiveArray<T> = sin(&unary::<_, _, _>(&lng_delta, |x| x / two));
+
+    let a = add(
+        // powf is slower than x * x
+        &unary::<_, _, _>(&v1, |x: T::Native| x * x),
+        // This could be simplified if we had a ternary kernel that takes 3 args
+        // F(T::Native, T::Native, T::Native) -> T::Native
+        &multiply(
+            // powf is slower than x * x
+            &unary::<_, _, _>(&v2, |x: T::Native| x * x),
+            &math_op(&lat_a_rad, &lat_b_rad, |x, y| (x.cos() * y.cos()))?,
+        )?,
+    )?;
+    Ok(unary::<_, _, _>(
+        &atan2(&sqrt(&a), &sqrt(&unary::<_, _, _>(&a, |x| one - x)))?,
+        |x| x * two_radius,
+    ))
+}
+
+// only added here to test that it's accurate
+pub fn haversine_no_unary<T>(

Review comment:
       shouldn't we move this to the tests, if it is only used for testing?




----------------------------------------------------------------
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.

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



[GitHub] [arrow] nevi-me commented on a change in pull request #9313: [Rust] [Experiment] Trigonometry kernels

Posted by GitBox <gi...@apache.org>.
nevi-me commented on a change in pull request #9313:
URL: https://github.com/apache/arrow/pull/9313#discussion_r563480506



##########
File path: rust/arrow/src/compute/kernels/trigonometry.rs
##########
@@ -0,0 +1,248 @@
+// 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.
+
+//! Defines trigonometry kernels for `PrimitiveArrays` that are
+//! floats, restricted by the [num::Float] trait.
+
+use std::{iter::FromIterator, ops::Div};
+
+use num::{Float, Zero};
+
+use super::math::*;
+use crate::buffer::Buffer;
+use crate::datatypes::ArrowNumericType;
+use crate::error::Result;
+use crate::{
+    array::*,
+    compute::{add, math_op, multiply, subtract},
+    datatypes::ArrowPrimitiveType,
+    error::ArrowError,
+    float_unary,
+};
+
+use super::unary::{into_primitive_array_data, unary};
+
+float_unary!(to_degrees);
+float_unary!(to_radians);
+float_unary!(sin);
+float_unary!(cos);
+float_unary!(tan);
+float_unary!(asin);
+float_unary!(acos);
+float_unary!(atan);
+float_unary!(sinh);
+float_unary!(cosh);
+float_unary!(tanh);
+float_unary!(asinh);
+float_unary!(acosh);
+float_unary!(atanh);
+
+pub fn atan2<T>(
+    left: &PrimitiveArray<T>,
+    right: &PrimitiveArray<T>,
+) -> Result<PrimitiveArray<T>>
+where
+    T: ArrowNumericType,
+    T::Native: num::traits::Float,
+{
+    math_op(left, right, |x, y| x.atan2(y))
+}
+
+/// Perform `left * right` operation on two arrays. If either left or right value is null
+/// then the result is also null.
+pub fn sin_cos<T>(array: &PrimitiveArray<T>) -> (PrimitiveArray<T>, PrimitiveArray<T>)
+where
+    T: ArrowNumericType,
+    T::Native: num::traits::Float,
+{
+    let (sin, cos): (Vec<T::Native>, Vec<T::Native>) =
+        array.values().iter().map(|v| v.sin_cos()).unzip();
+    // NOTE: due to `unzip` collecting and splitting the arrays,
+    // this might be slower than Buffer::from_trusted_len_iter
+    let sin_buffer = Buffer::from_iter(sin);
+    let cos_buffer = Buffer::from_iter(cos);
+
+    let sin_data = into_primitive_array_data::<_, T>(array, sin_buffer);
+    let cos_data = into_primitive_array_data::<_, T>(array, cos_buffer);
+    (
+        PrimitiveArray::<T>::from(std::sync::Arc::new(sin_data)),
+        PrimitiveArray::<T>::from(std::sync::Arc::new(cos_data)),
+    )
+}
+
+/// Calculate the Haversine distance between two geographic coordinates.
+/// Based on the haversine crate.
+///
+/// The distance returned is in meters, and the radius must be specified in meters.
+pub fn haversine<T>(
+    lat_a: &PrimitiveArray<T>,
+    lng_a: &PrimitiveArray<T>,
+    lat_b: &PrimitiveArray<T>,
+    lng_b: &PrimitiveArray<T>,
+    radius: impl num::traits::Float,
+) -> Result<PrimitiveArray<T>>
+where
+    T: ArrowPrimitiveType + ArrowNumericType,
+    T::Native: num::traits::Float + Div<Output = T::Native> + Zero + num::NumCast,
+{
+    // Check array lengths, must all equal
+    let len = lat_a.len();
+    if lat_b.len() != len || lng_a.len() != len || lng_b.len() != len {
+        return Err(ArrowError::ComputeError(
+            "Cannot perform math operation on arrays of different length".to_string(),
+        ));
+    }
+    // These casts normally get optimized to f64 as f64
+    let one = num::cast::<_, T::Native>(1.0).unwrap();

Review comment:
       @jorgecarleitao I had to convert the floats to `T::Native` in order to use them in the unary kernel as part of `Fn(_)` expressions.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] nevi-me commented on a change in pull request #9313: [Rust] [Experiment] Trigonometry kernels

Posted by GitBox <gi...@apache.org>.
nevi-me commented on a change in pull request #9313:
URL: https://github.com/apache/arrow/pull/9313#discussion_r571213170



##########
File path: rust/arrow/src/compute/kernels/trigonometry.rs
##########
@@ -0,0 +1,246 @@
+// 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.
+
+//! Defines trigonometry kernels for `PrimitiveArrays` that are
+//! floats, restricted by the [num::Float] trait.
+
+use std::{iter::FromIterator, ops::Div};
+
+use num::{Float, Zero};
+
+use super::math::*;
+use crate::buffer::Buffer;
+use crate::datatypes::ArrowNumericType;
+use crate::error::Result;
+use crate::{
+    array::*,
+    compute::{add, math_op, multiply, subtract},
+    datatypes::ArrowPrimitiveType,
+    error::ArrowError,
+    float_unary,
+};
+
+use super::arity::{into_primitive_array_data, unary};
+
+float_unary!(to_degrees);
+float_unary!(to_radians);
+float_unary!(sin);
+float_unary!(cos);
+float_unary!(tan);
+float_unary!(asin);
+float_unary!(acos);
+float_unary!(atan);
+float_unary!(sinh);
+float_unary!(cosh);
+float_unary!(tanh);
+float_unary!(asinh);
+float_unary!(acosh);
+float_unary!(atanh);
+
+pub fn atan2<T>(
+    left: &PrimitiveArray<T>,
+    right: &PrimitiveArray<T>,
+) -> Result<PrimitiveArray<T>>
+where
+    T: ArrowNumericType,
+    T::Native: num::traits::Float,
+{
+    math_op(left, right, |x, y| x.atan2(y))
+}
+
+/// Perform `left * right` operation on two arrays. If either left or right value is null
+/// then the result is also null.
+pub fn sin_cos<T>(array: &PrimitiveArray<T>) -> (PrimitiveArray<T>, PrimitiveArray<T>)
+where
+    T: ArrowNumericType,
+    T::Native: num::traits::Float,
+{
+    let (sin, cos): (Vec<T::Native>, Vec<T::Native>) =
+        array.values().iter().map(|v| v.sin_cos()).unzip();
+    // NOTE: due to `unzip` collecting and splitting the arrays,
+    // this might be slower than Buffer::from_trusted_len_iter
+    let sin_buffer = Buffer::from_iter(sin);
+    let cos_buffer = Buffer::from_iter(cos);
+
+    let sin_data = into_primitive_array_data::<_, T>(array, sin_buffer);
+    let cos_data = into_primitive_array_data::<_, T>(array, cos_buffer);
+    (
+        PrimitiveArray::<T>::from(std::sync::Arc::new(sin_data)),
+        PrimitiveArray::<T>::from(std::sync::Arc::new(cos_data)),
+    )
+}
+
+/// Calculate the Haversine distance between two geographic coordinates.
+/// Based on the haversine crate.
+///
+/// The distance returned is in meters, and the radius must be specified in meters.
+pub fn haversine<T>(
+    lat_a: &PrimitiveArray<T>,
+    lng_a: &PrimitiveArray<T>,
+    lat_b: &PrimitiveArray<T>,
+    lng_b: &PrimitiveArray<T>,
+    radius: impl num::traits::Float,
+) -> Result<PrimitiveArray<T>>
+where
+    T: ArrowPrimitiveType + ArrowNumericType,
+    T::Native: num::traits::Float + Div<Output = T::Native> + Zero + num::NumCast,
+{
+    // Check array lengths, must all equal
+    let len = lat_a.len();
+    if lat_b.len() != len || lng_a.len() != len || lng_b.len() != len {
+        return Err(ArrowError::ComputeError(
+            "Cannot perform math operation on arrays of different length".to_string(),
+        ));
+    }
+    // These casts normally get optimized to f64 as f64
+    let one = num::cast::<_, T::Native>(1.0).unwrap();
+    let two = num::cast::<_, T::Native>(2.0).unwrap();
+    let radius = num::cast::<_, T::Native>(radius).unwrap();
+    let two_radius = two * radius;
+
+    let lat_delta = to_radians(&subtract(lat_b, lat_a)?);
+    let lng_delta = to_radians(&subtract(lng_b, lng_a)?);
+    let lat_a_rad = to_radians(lat_a);
+    let lat_b_rad = to_radians(lat_b);
+
+    let v1: PrimitiveArray<T> = sin(&unary::<_, _, _>(&lat_delta, |x| x / two));
+    let v2: PrimitiveArray<T> = sin(&unary::<_, _, _>(&lng_delta, |x| x / two));
+
+    let a = add(
+        // powf is slower than x * x
+        &unary::<_, _, _>(&v1, |x: T::Native| x * x),
+        // This could be simplified if we had a ternary kernel that takes 3 args
+        // F(T::Native, T::Native, T::Native) -> T::Native
+        &multiply(
+            // powf is slower than x * x
+            &unary::<_, _, _>(&v2, |x: T::Native| x * x),
+            &math_op(&lat_a_rad, &lat_b_rad, |x, y| (x.cos() * y.cos()))?,
+        )?,
+    )?;
+    Ok(unary::<_, _, _>(
+        &atan2(&sqrt(&a), &sqrt(&unary::<_, _, _>(&a, |x| one - x)))?,
+        |x| x * two_radius,
+    ))
+}
+
+// only added here to test that it's accurate
+pub fn haversine_no_unary<T>(

Review comment:
       I've removed it, as it's also in the benchmark




----------------------------------------------------------------
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.

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



[GitHub] [arrow] jorgecarleitao commented on a change in pull request #9313: [Rust] [Experiment] Trigonometry kernels

Posted by GitBox <gi...@apache.org>.
jorgecarleitao commented on a change in pull request #9313:
URL: https://github.com/apache/arrow/pull/9313#discussion_r568778663



##########
File path: rust/arrow/benches/trigonometry_kernels.rs
##########
@@ -0,0 +1,171 @@
+// 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.
+
+#[macro_use]
+extern crate criterion;
+use criterion::Criterion;
+
+use num::Zero;
+use rand::Rng;
+use std::{ops::Div, sync::Arc};
+
+extern crate arrow;
+
+use arrow::error::{ArrowError, Result};
+use arrow::util::test_util::seedable_rng;
+use arrow::{
+    array::*,
+    compute::*,
+    datatypes::{ArrowNumericType, ArrowPrimitiveType},
+};
+
+/// This computes the Haversine formula without using unary kernels
+fn haversine_no_unary<T>(

Review comment:
       I would try to get the result from the exercise, drop this code once the best option was found, and document which was was better in implementation notes on the decided approach.

##########
File path: rust/arrow/src/compute/kernels/trigonometry.rs
##########
@@ -0,0 +1,246 @@
+// 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.
+
+//! Defines trigonometry kernels for `PrimitiveArrays` that are
+//! floats, restricted by the [num::Float] trait.
+
+use std::{iter::FromIterator, ops::Div};
+
+use num::{Float, Zero};
+
+use super::math::*;
+use crate::buffer::Buffer;
+use crate::datatypes::ArrowNumericType;
+use crate::error::Result;
+use crate::{
+    array::*,
+    compute::{add, math_op, multiply, subtract},
+    datatypes::ArrowPrimitiveType,
+    error::ArrowError,
+    float_unary,
+};
+
+use super::arity::{into_primitive_array_data, unary};
+
+float_unary!(to_degrees);
+float_unary!(to_radians);
+float_unary!(sin);
+float_unary!(cos);
+float_unary!(tan);
+float_unary!(asin);
+float_unary!(acos);
+float_unary!(atan);
+float_unary!(sinh);
+float_unary!(cosh);
+float_unary!(tanh);
+float_unary!(asinh);
+float_unary!(acosh);
+float_unary!(atanh);
+
+pub fn atan2<T>(
+    left: &PrimitiveArray<T>,
+    right: &PrimitiveArray<T>,
+) -> Result<PrimitiveArray<T>>
+where
+    T: ArrowNumericType,
+    T::Native: num::traits::Float,
+{
+    math_op(left, right, |x, y| x.atan2(y))
+}
+
+/// Perform `left * right` operation on two arrays. If either left or right value is null
+/// then the result is also null.
+pub fn sin_cos<T>(array: &PrimitiveArray<T>) -> (PrimitiveArray<T>, PrimitiveArray<T>)
+where
+    T: ArrowNumericType,
+    T::Native: num::traits::Float,
+{
+    let (sin, cos): (Vec<T::Native>, Vec<T::Native>) =
+        array.values().iter().map(|v| v.sin_cos()).unzip();
+    // NOTE: due to `unzip` collecting and splitting the arrays,
+    // this might be slower than Buffer::from_trusted_len_iter
+    let sin_buffer = Buffer::from_iter(sin);
+    let cos_buffer = Buffer::from_iter(cos);
+
+    let sin_data = into_primitive_array_data::<_, T>(array, sin_buffer);
+    let cos_data = into_primitive_array_data::<_, T>(array, cos_buffer);
+    (
+        PrimitiveArray::<T>::from(std::sync::Arc::new(sin_data)),
+        PrimitiveArray::<T>::from(std::sync::Arc::new(cos_data)),
+    )
+}
+
+/// Calculate the Haversine distance between two geographic coordinates.
+/// Based on the haversine crate.
+///
+/// The distance returned is in meters, and the radius must be specified in meters.
+pub fn haversine<T>(
+    lat_a: &PrimitiveArray<T>,
+    lng_a: &PrimitiveArray<T>,
+    lat_b: &PrimitiveArray<T>,
+    lng_b: &PrimitiveArray<T>,
+    radius: impl num::traits::Float,
+) -> Result<PrimitiveArray<T>>
+where
+    T: ArrowPrimitiveType + ArrowNumericType,
+    T::Native: num::traits::Float + Div<Output = T::Native> + Zero + num::NumCast,
+{
+    // Check array lengths, must all equal
+    let len = lat_a.len();
+    if lat_b.len() != len || lng_a.len() != len || lng_b.len() != len {
+        return Err(ArrowError::ComputeError(
+            "Cannot perform math operation on arrays of different length".to_string(),
+        ));
+    }
+    // These casts normally get optimized to f64 as f64
+    let one = num::cast::<_, T::Native>(1.0).unwrap();
+    let two = num::cast::<_, T::Native>(2.0).unwrap();
+    let radius = num::cast::<_, T::Native>(radius).unwrap();
+    let two_radius = two * radius;
+
+    let lat_delta = to_radians(&subtract(lat_b, lat_a)?);
+    let lng_delta = to_radians(&subtract(lng_b, lng_a)?);
+    let lat_a_rad = to_radians(lat_a);
+    let lat_b_rad = to_radians(lat_b);
+
+    let v1: PrimitiveArray<T> = sin(&unary::<_, _, _>(&lat_delta, |x| x / two));
+    let v2: PrimitiveArray<T> = sin(&unary::<_, _, _>(&lng_delta, |x| x / two));
+
+    let a = add(
+        // powf is slower than x * x
+        &unary::<_, _, _>(&v1, |x: T::Native| x * x),
+        // This could be simplified if we had a ternary kernel that takes 3 args
+        // F(T::Native, T::Native, T::Native) -> T::Native
+        &multiply(
+            // powf is slower than x * x
+            &unary::<_, _, _>(&v2, |x: T::Native| x * x),
+            &math_op(&lat_a_rad, &lat_b_rad, |x, y| (x.cos() * y.cos()))?,
+        )?,
+    )?;
+    Ok(unary::<_, _, _>(
+        &atan2(&sqrt(&a), &sqrt(&unary::<_, _, _>(&a, |x| one - x)))?,
+        |x| x * two_radius,
+    ))
+}
+
+// only added here to test that it's accurate
+pub fn haversine_no_unary<T>(

Review comment:
       shouldn't we move this to the tests, if it is only used for testing?




----------------------------------------------------------------
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.

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