edponce commented on code in PR #12460:
URL: https://github.com/apache/arrow/pull/12460#discussion_r845473829


##########
cpp/src/arrow/compute/api_vector.h:
##########
@@ -188,6 +188,27 @@ class ARROW_EXPORT PartitionNthOptions : public 
FunctionOptions {
   NullPlacement null_placement;
 };
 
+/// \brief Options for cumulative sum function
+class ARROW_EXPORT CumulativeSumOptions : public FunctionOptions {
+ public:
+  explicit CumulativeSumOptions(
+      std::shared_ptr<Scalar> start = std::make_shared<Int64Scalar>(0),
+      bool skip_nulls = false, bool check_overflow = false);
+  static constexpr char const kTypeName[] = "CumulativeSumOptions";
+  static CumulativeSumOptions Defaults() { return CumulativeSumOptions(); }
+
+  /// Optional starting value for cumulative operation computation
+  std::shared_ptr<Scalar> start;
+
+  /// If true, nulls in the input are ignored and produce a corresponding null 
output.
+  /// When false, the first null/NaN encountered is propagated through the 
remaining

Review Comment:
   This flag does not controls the behavior of NaNs, so remove NaN from comment.
   The NaN propagation occurs naturally due to C++ arithmetic rules. 



##########
cpp/src/arrow/compute/kernels/vector_cumulative_ops.cc:
##########
@@ -0,0 +1,185 @@
+// 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/array/array_base.h"
+#include "arrow/compute/api_scalar.h"
+#include "arrow/compute/api_vector.h"
+#include "arrow/compute/cast.h"
+#include "arrow/compute/kernels/base_arithmetic_internal.h"
+#include "arrow/compute/kernels/codegen_internal.h"
+#include "arrow/compute/kernels/common.h"
+#include "arrow/result.h"
+#include "arrow/util/bit_util.h"
+#include "arrow/visit_type_inline.h"
+
+namespace arrow {
+namespace compute {
+namespace internal {
+
+// Base class for all cumulative compute functions. Op can be any binary 
associative
+// operation (+, *, min, etc.) and OptionsType the options type corresponding 
to Op.
+// ArgType and OutType are the input and output types, which will normally be 
the
+// same (e.g. the cumulative sum of an array of Int64Type will result in an 
array of
+// Int64Type).
+template <typename OutType, typename ArgType, typename Op, typename 
OptionsType>
+struct CumulativeGeneric {
+  using OutValue = typename GetOutputType<OutType>::T;
+  using ArgValue = typename GetViewType<ArgType>::T;
+
+  static Status Exec(KernelContext* ctx, const ExecBatch& batch, Datum* out) {
+    const auto& options = OptionsWrapper<OptionsType>::Get(ctx);
+    auto skip_nulls = options.skip_nulls;
+
+    auto out_type = batch.GetDescriptors()[0].type;
+    ARROW_ASSIGN_OR_RAISE(
+        auto cast_value,
+        Cast(Datum(options.start), out_type, CastOptions::Safe(), 
ctx->exec_context()));
+    auto start = UnboxScalar<OutType>::Unbox(*cast_value.scalar());

Review Comment:
   I think this cast operation can be moved to the `Init` method of a derived 
`OptionsWrapper`.



##########
cpp/src/arrow/compute/kernels/vector_cumulative_ops.cc:
##########
@@ -0,0 +1,185 @@
+// 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/array/array_base.h"
+#include "arrow/compute/api_scalar.h"
+#include "arrow/compute/api_vector.h"
+#include "arrow/compute/cast.h"
+#include "arrow/compute/kernels/base_arithmetic_internal.h"
+#include "arrow/compute/kernels/codegen_internal.h"
+#include "arrow/compute/kernels/common.h"
+#include "arrow/result.h"
+#include "arrow/util/bit_util.h"
+#include "arrow/visit_type_inline.h"
+
+namespace arrow {
+namespace compute {
+namespace internal {
+
+// Base class for all cumulative compute functions. Op can be any binary 
associative
+// operation (+, *, min, etc.) and OptionsType the options type corresponding 
to Op.
+// ArgType and OutType are the input and output types, which will normally be 
the
+// same (e.g. the cumulative sum of an array of Int64Type will result in an 
array of
+// Int64Type).
+template <typename OutType, typename ArgType, typename Op, typename 
OptionsType>
+struct CumulativeGeneric {
+  using OutValue = typename GetOutputType<OutType>::T;
+  using ArgValue = typename GetViewType<ArgType>::T;
+
+  static Status Exec(KernelContext* ctx, const ExecBatch& batch, Datum* out) {
+    const auto& options = OptionsWrapper<OptionsType>::Get(ctx);
+    auto skip_nulls = options.skip_nulls;
+
+    auto out_type = batch.GetDescriptors()[0].type;
+    ARROW_ASSIGN_OR_RAISE(
+        auto cast_value,
+        Cast(Datum(options.start), out_type, CastOptions::Safe(), 
ctx->exec_context()));
+    auto start = UnboxScalar<OutType>::Unbox(*cast_value.scalar());
+
+    int64_t base_output_offset = 0;
+    bool encountered_null = false;
+    ArrayData* out_arr = out->mutable_array();
+
+    switch (batch[0].kind()) {
+      case Datum::ARRAY: {
+        auto st = Call(ctx, base_output_offset, *batch[0].array(), out_arr, 
&start,
+                       skip_nulls, &encountered_null);
+        out_arr->SetNullCount(arrow::kUnknownNullCount);
+        return st;
+      }
+      case Datum::CHUNKED_ARRAY: {
+        const auto& input = batch[0].chunked_array();
+
+        for (const auto& chunk : input->chunks()) {
+          RETURN_NOT_OK(Call(ctx, base_output_offset, *chunk->data(), out_arr, 
&start,
+                             skip_nulls, &encountered_null));
+          base_output_offset += chunk->length();
+        }
+        out_arr->SetNullCount(arrow::kUnknownNullCount);
+        return Status::OK();
+      }
+      default:
+        return Status::NotImplemented(
+            "Unsupported input type for function 'cumulative_<operator>': ",
+            batch[0].ToString());
+    }
+  }
+
+  static Status Call(KernelContext* ctx, int64_t base_output_offset,
+                     const ArrayData& input, ArrayData* output, ArgValue* 
accumulator,
+                     bool skip_nulls, bool* encountered_null) {
+    Status st = Status::OK();
+    auto out_bitmap = output->GetMutableValues<uint8_t>(0);
+    auto out_data = output->GetMutableValues<OutValue>(1) + base_output_offset;
+    int64_t curr = base_output_offset;
+
+    auto null_func = [&]() {
+      *out_data++ = OutValue{};
+      *encountered_null = true;
+      arrow::bit_util::SetBitTo(out_bitmap, curr, false);
+      ++curr;
+    };
+
+    if (skip_nulls) {
+      VisitArrayValuesInline<ArgType>(
+          input,
+          [&](ArgValue v) {
+            *accumulator = Op::template Call<OutValue, ArgValue, ArgValue>(
+                ctx, v, *accumulator, &st);
+            *out_data++ = *accumulator;
+            ++curr;
+          },
+          null_func);
+    } else {
+      auto start_null_idx = 0;
+      VisitArrayValuesInline<ArgType>(
+          input,
+          [&](ArgValue v) {
+            if (*encountered_null) {
+              *out_data++ = OutValue{};
+            } else {
+              *accumulator = Op::template Call<OutValue, ArgValue, ArgValue>(
+                  ctx, v, *accumulator, &st);
+              *out_data++ = *accumulator;

Review Comment:
   There is a lot of indirections here, maybe use local variables for visitor 
and update at the end the output parameter ones.



##########
cpp/src/arrow/compute/kernels/vector_cumulative_ops.cc:
##########
@@ -0,0 +1,185 @@
+// 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/array/array_base.h"
+#include "arrow/compute/api_scalar.h"
+#include "arrow/compute/api_vector.h"
+#include "arrow/compute/cast.h"
+#include "arrow/compute/kernels/base_arithmetic_internal.h"
+#include "arrow/compute/kernels/codegen_internal.h"
+#include "arrow/compute/kernels/common.h"
+#include "arrow/result.h"
+#include "arrow/util/bit_util.h"
+#include "arrow/visit_type_inline.h"
+
+namespace arrow {
+namespace compute {
+namespace internal {
+
+// Base class for all cumulative compute functions. Op can be any binary 
associative
+// operation (+, *, min, etc.) and OptionsType the options type corresponding 
to Op.
+// ArgType and OutType are the input and output types, which will normally be 
the
+// same (e.g. the cumulative sum of an array of Int64Type will result in an 
array of
+// Int64Type).

Review Comment:
   Some comments on this text:
   * `CumulativeGeneric` is not really a base class (no class derives from it, 
nor should) but the driver kernel for binary cumulative operations.
   * `Op` represents a compute kernel.
   * `(+, *, min, etc.)` --> `(add, product, min, max, etc.)` or `(+, x, <, >, 
etc.)`



##########
docs/source/python/api/compute.rst:
##########
@@ -45,6 +45,21 @@ Aggregations
    tdigest
    variance
 
+Cumulative Functions
+--------------------
+
+Cumulative functions are vector functions that perform a running total on its
+input and outputs an array containing the corresponding intermediate running 
values.

Review Comment:
   We captured the behavior of cumsum for Pandas, R, numpy in 
[JIRA](https://issues.apache.org/jira/browse/ARROW-13530) and there are 
differences among them. Current implementation default behavior is consistent 
with Python and R.
   
   Also, the only inputs supported in this PR are `Array` and `ChunkedArray`. 
Support for `RecordBatch` and `Table` inputs can be added in this PR or as a 
follow-up one. I agree that if inputs are limited, it should be stated explicit 
in the wordings.



##########
cpp/src/arrow/compute/kernels/vector_cumulative_ops_test.cc:
##########
@@ -0,0 +1,266 @@
+// 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 <string>
+#include <vector>
+
+#include <gtest/gtest.h>
+
+#include "arrow/array.h"
+#include "arrow/chunked_array.h"
+#include "arrow/compute/api_vector.h"
+#include "arrow/testing/gtest_util.h"
+#include "arrow/testing/util.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+
+#include "arrow/compute/api.h"
+#include "arrow/compute/kernels/test_util.h"
+

Review Comment:
   * IWYU and order lexicographically.
   * `arrow/compute/api.h` includes `arrow/compute/api_vector.h`
   * Remove `arrow/type_fwd.h`, generally type-forwarding is applied to header 
files.
   * Add `<memory>` for smart pointers



##########
cpp/src/arrow/compute/kernels/vector_cumulative_ops.cc:
##########
@@ -0,0 +1,185 @@
+// 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/array/array_base.h"
+#include "arrow/compute/api_scalar.h"
+#include "arrow/compute/api_vector.h"
+#include "arrow/compute/cast.h"
+#include "arrow/compute/kernels/base_arithmetic_internal.h"
+#include "arrow/compute/kernels/codegen_internal.h"
+#include "arrow/compute/kernels/common.h"
+#include "arrow/result.h"
+#include "arrow/util/bit_util.h"
+#include "arrow/visit_type_inline.h"
+
+namespace arrow {
+namespace compute {
+namespace internal {
+
+// Base class for all cumulative compute functions. Op can be any binary 
associative
+// operation (+, *, min, etc.) and OptionsType the options type corresponding 
to Op.
+// ArgType and OutType are the input and output types, which will normally be 
the
+// same (e.g. the cumulative sum of an array of Int64Type will result in an 
array of
+// Int64Type).
+template <typename OutType, typename ArgType, typename Op, typename 
OptionsType>
+struct CumulativeGeneric {
+  using OutValue = typename GetOutputType<OutType>::T;
+  using ArgValue = typename GetViewType<ArgType>::T;
+
+  static Status Exec(KernelContext* ctx, const ExecBatch& batch, Datum* out) {
+    const auto& options = OptionsWrapper<OptionsType>::Get(ctx);
+    auto skip_nulls = options.skip_nulls;
+
+    auto out_type = batch.GetDescriptors()[0].type;
+    ARROW_ASSIGN_OR_RAISE(
+        auto cast_value,
+        Cast(Datum(options.start), out_type, CastOptions::Safe(), 
ctx->exec_context()));
+    auto start = UnboxScalar<OutType>::Unbox(*cast_value.scalar());
+
+    int64_t base_output_offset = 0;
+    bool encountered_null = false;
+    ArrayData* out_arr = out->mutable_array();
+
+    switch (batch[0].kind()) {
+      case Datum::ARRAY: {
+        auto st = Call(ctx, base_output_offset, *batch[0].array(), out_arr, 
&start,
+                       skip_nulls, &encountered_null);
+        out_arr->SetNullCount(arrow::kUnknownNullCount);
+        return st;
+      }
+      case Datum::CHUNKED_ARRAY: {
+        const auto& input = batch[0].chunked_array();
+
+        for (const auto& chunk : input->chunks()) {
+          RETURN_NOT_OK(Call(ctx, base_output_offset, *chunk->data(), out_arr, 
&start,
+                             skip_nulls, &encountered_null));
+          base_output_offset += chunk->length();
+        }
+        out_arr->SetNullCount(arrow::kUnknownNullCount);
+        return Status::OK();
+      }
+      default:
+        return Status::NotImplemented(
+            "Unsupported input type for function 'cumulative_<operator>': ",
+            batch[0].ToString());
+    }
+  }
+
+  static Status Call(KernelContext* ctx, int64_t base_output_offset,
+                     const ArrayData& input, ArrayData* output, ArgValue* 
accumulator,
+                     bool skip_nulls, bool* encountered_null) {
+    Status st = Status::OK();
+    auto out_bitmap = output->GetMutableValues<uint8_t>(0);
+    auto out_data = output->GetMutableValues<OutValue>(1) + base_output_offset;
+    int64_t curr = base_output_offset;
+
+    auto null_func = [&]() {
+      *out_data++ = OutValue{};
+      *encountered_null = true;
+      arrow::bit_util::SetBitTo(out_bitmap, curr, false);

Review Comment:
   Do we know why null-handling with `INTERSECTION` is not working correctly 
for `ChunkedArrays`?



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

Reply via email to