cyb70289 commented on a change in pull request #8269:
URL: https://github.com/apache/arrow/pull/8269#discussion_r497254422



##########
File path: docs/source/cpp/compute.rst
##########
@@ -140,8 +140,12 @@ Aggregations
 
+--------------------------+------------+--------------------+-----------------------+--------------------------------------------+
 | mode                     | Unary      | Numeric            | Scalar Struct  
(2)    |                                            |
 
+--------------------------+------------+--------------------+-----------------------+--------------------------------------------+
+| std                      | Unary      | Numeric            | Scalar Float64  
      | :struct:`VarStdOptions`                    |
++--------------------------+------------+--------------------+-----------------------+--------------------------------------------+
 | sum                      | Unary      | Numeric            | Scalar Numeric 
(3)    |                                            |
 
+--------------------------+------------+--------------------+-----------------------+--------------------------------------------+
+| var                      | Unary      | Numeric            | Scalar Float64  
      | :struct:`VarStdOptions`                    |

Review comment:
       done

##########
File path: cpp/src/arrow/compute/kernels/aggregate_var_std.cc
##########
@@ -0,0 +1,200 @@
+// 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.
+
+#include "arrow/compute/kernels/aggregate_basic_internal.h"
+
+namespace arrow {
+namespace compute {
+namespace aggregate {
+
+namespace {
+
+// Based on https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
+template <typename ArrowType>
+struct VarStdState {
+  using ArrayType = typename TypeTraits<ArrowType>::ArrayType;
+  using c_type = typename ArrowType::c_type;
+  using ThisType = VarStdState<ArrowType>;
+
+  // Calculate variance of one chunk with `two pass algorithm`
+  // Always use `double` to calculate variance for any array type
+  void Consume(const ArrayType& array) {
+    int64_t count = array.length() - array.null_count();
+    if (count == 0) {
+      return;
+    }
+
+    double sum = 0;
+    VisitArrayDataInline<ArrowType>(
+        *array.data(), [&sum](c_type value) { sum += 
static_cast<double>(value); },
+        []() {});
+
+    double mean = sum / count, m2 = 0;
+    VisitArrayDataInline<ArrowType>(
+        *array.data(),
+        [mean, &m2](c_type value) {
+          double v = static_cast<double>(value);
+          m2 += (v - mean) * (v - mean);
+        },
+        []() {});
+
+    this->count = count;
+    this->sum = sum;
+    this->m2 = m2;
+  }
+
+  // Combine variance from two chunks
+  void MergeFrom(const ThisType& state) {
+    if (state.count == 0) {
+      return;
+    }
+    if (this->count == 0) {
+      this->count = state.count;
+      this->sum = state.sum;
+      this->m2 = state.m2;
+      return;
+    }
+    double delta = this->sum / this->count - state.sum / state.count;
+    this->m2 += state.m2 +
+                delta * delta * this->count * state.count / (this->count + 
state.count);

Review comment:
       done

##########
File path: cpp/src/arrow/compute/kernels/aggregate_test.cc
##########
@@ -914,5 +914,127 @@ TEST_F(TestInt32ModeKernel, LargeValueRange) {
   CheckModeWithRange<ArrowType>(-10000000, 10000000);
 }
 
+//
+// Var/Std
+//
+
+template <typename ArrowType>
+class TestPrimitiveVarStdKernel : public ::testing::Test {
+ public:
+  using Traits = TypeTraits<ArrowType>;
+  using ScalarType = typename TypeTraits<DoubleType>::ScalarType;
+
+  void AssertVarStdIs(const Datum& array, const VarStdOptions& options,
+                      double expected_var, double diff = 0) {
+    ASSERT_OK_AND_ASSIGN(Datum out_var, Var(array, options));
+    ASSERT_OK_AND_ASSIGN(Datum out_std, Std(array, options));
+    auto var = checked_cast<const ScalarType*>(out_var.scalar().get());
+    auto std = checked_cast<const ScalarType*>(out_std.scalar().get());
+    ASSERT_TRUE(var->is_valid && std->is_valid);
+    ASSERT_DOUBLE_EQ(std->value * std->value, var->value);
+    if (diff == 0) {
+      ASSERT_DOUBLE_EQ(var->value, expected_var);  // < 4ULP
+    } else {
+      ASSERT_NEAR(var->value, expected_var, diff);
+    }
+  }
+
+  void AssertVarStdIs(const std::string& json, const VarStdOptions& options,
+                      double expected_var) {
+    auto array = ArrayFromJSON(type_singleton(), json);
+    AssertVarStdIs(array, options, expected_var);
+  }
+
+  void AssertVarStdIs(const std::vector<std::string>& json, const 
VarStdOptions& options,
+                      double expected_var) {
+    auto chunked = ChunkedArrayFromJSON(type_singleton(), json);
+    AssertVarStdIs(chunked, options, expected_var);
+  }
+
+  void AssertVarStdIsInvalid(const Datum& array, const VarStdOptions& options) 
{
+    ASSERT_OK_AND_ASSIGN(Datum out_var, Var(array, options));
+    ASSERT_OK_AND_ASSIGN(Datum out_std, Std(array, options));
+    auto var = checked_cast<const ScalarType*>(out_var.scalar().get());
+    auto std = checked_cast<const ScalarType*>(out_std.scalar().get());
+    ASSERT_FALSE(var->is_valid || std->is_valid);
+  }
+
+  void AssertVarStdIsInvalid(const std::string& json, const VarStdOptions& 
options) {
+    auto array = ArrayFromJSON(type_singleton(), json);
+    AssertVarStdIsInvalid(array, options);
+  }
+
+  std::shared_ptr<DataType> type_singleton() { return 
Traits::type_singleton(); }
+};
+
+template <typename ArrowType>
+class TestNumericVarStdKernel : public TestPrimitiveVarStdKernel<ArrowType> {};
+
+// Reference value from numpy.var
+TYPED_TEST_SUITE(TestNumericVarStdKernel, NumericArrowTypes);
+TYPED_TEST(TestNumericVarStdKernel, Basics) {
+  VarStdOptions options;  // ddof = 0, population var/std
+
+  this->AssertVarStdIs("[100]", options, 0);
+  this->AssertVarStdIs("[1, 2, 3]", options, 0.6666666666666666);
+  this->AssertVarStdIs("[null, 1, 2, null, 3]", options, 0.6666666666666666);
+
+  this->AssertVarStdIs({"[]", "[1]", "[2]", "[null]", "[3]"}, options,
+                       0.6666666666666666);
+  this->AssertVarStdIs({"[1, 2, 3]", "[4, 5, 6]", "[7, 8]"}, options, 5.25);
+
+  this->AssertVarStdIsInvalid("[null, null, null]", options);
+  this->AssertVarStdIsInvalid("[]", options);
+
+  options.ddof = 1;  // sample var/std
+
+  this->AssertVarStdIs("[1, 2]", options, 0.5);
+  this->AssertVarStdIs({"[1, 2, 3]", "[4, 5, 6]", "[7, 8]"}, options, 6.0);
+
+  this->AssertVarStdIsInvalid("[100]", options);
+  this->AssertVarStdIsInvalid("[100, null, null]", options);
+}
+
+class TestVarStdKernelStability : public TestPrimitiveVarStdKernel<DoubleType> 
{};
+
+// Test numerical stability
+TEST_F(TestVarStdKernelStability, Basics) {
+  VarStdOptions options{1};  // ddof = 1
+  this->AssertVarStdIs("[100000004, 100000007, 100000013, 100000016]", 
options, 30.0);
+  this->AssertVarStdIs("[1000000004, 1000000007, 1000000013, 1000000016]", 
options, 30.0);
+}
+
+// Calculate reference variance with welford online algorithm
+double WelfordVar(const Array& array) {
+  const auto& array_numeric = reinterpret_cast<const DoubleArray&>(array);
+  const auto values = array_numeric.raw_values();
+  internal::BitmapReader reader(array.null_bitmap_data(), array.offset(), 
array.length());
+  double count = 0, mean = 0, m2 = 0;
+  for (int64_t i = 0; i < array.length(); ++i) {
+    if (reader.IsSet()) {
+      ++count;
+      double delta = values[i] - mean;
+      mean += delta / count;
+      double delta2 = values[i] - mean;
+      m2 += delta * delta2;
+    }
+    reader.Next();
+  }
+  return m2 / count;
+}
+
+class TestVarStdKernelRandom : public TestPrimitiveVarStdKernel<DoubleType> {};
+
+TEST_F(TestVarStdKernelRandom, Basics) {
+  auto rand = random::RandomArrayGenerator(0x5487656);
+  auto array = rand.Numeric<DoubleType>(40000, -10000.0, 100000.0, 0.1);

Review comment:
       done




----------------------------------------------------------------
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:
[email protected]


Reply via email to