|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +#include <functional> |
| 19 | +#include <memory> |
| 20 | +#include <optional> |
| 21 | +#include <utility> |
| 22 | + |
| 23 | +#include "arrow/compute/api_aggregate.h" |
| 24 | +#include "arrow/compute/api_vector.h" |
| 25 | +#include "arrow/compute/exec.h" |
| 26 | +#include "arrow/compute/function.h" |
| 27 | +#include "arrow/compute/kernel.h" |
| 28 | +#include "arrow/compute/kernels/codegen_internal.h" |
| 29 | +#include "arrow/compute/registry.h" |
| 30 | +#include "arrow/result.h" |
| 31 | +#include "arrow/scalar.h" |
| 32 | +#include "arrow/status.h" |
| 33 | +#include "arrow/util/bit_run_reader.h" |
| 34 | +#include "arrow/util/checked_cast.h" |
| 35 | +#include "arrow/util/logging.h" |
| 36 | + |
| 37 | +namespace arrow::compute::internal { |
| 38 | + |
| 39 | +using ::arrow::internal::checked_cast; |
| 40 | + |
| 41 | +namespace { |
| 42 | + |
| 43 | +Status ValidateOptions(const WinsorizeOptions& options) { |
| 44 | + if (!(options.lower_limit >= 0 && options.lower_limit <= 1) || |
| 45 | + !(options.upper_limit >= 0 && options.upper_limit <= 1)) { |
| 46 | + return Status::Invalid("winsorize limits must be between 0 and 1"); |
| 47 | + } |
| 48 | + if (options.lower_limit > options.upper_limit) { |
| 49 | + return Status::Invalid( |
| 50 | + "winsorize upper limit must be equal or greater than lower limit"); |
| 51 | + } |
| 52 | + return Status::OK(); |
| 53 | +} |
| 54 | + |
| 55 | +using WinsorizeState = internal::OptionsWrapper<WinsorizeOptions>; |
| 56 | + |
| 57 | +// We have a first unused template parameter for compatibility with GenerateNumeric. |
| 58 | +template <typename Unused, typename Type> |
| 59 | +struct Winsorize { |
| 60 | + using ArrayType = typename TypeTraits<Type>::ArrayType; |
| 61 | + using CType = typename TypeTraits<Type>::CType; |
| 62 | + |
| 63 | + static Status Exec(KernelContext* ctx, const ExecSpan& batch, ExecResult* out) { |
| 64 | + const auto& options = WinsorizeState::Get(ctx); |
| 65 | + RETURN_NOT_OK(ValidateOptions(options)); |
| 66 | + ARROW_ASSIGN_OR_RAISE(auto maybe_quantiles, |
| 67 | + GetQuantileValues(ctx, batch.ToExecBatch(), options)); |
| 68 | + auto data = batch.values[0].array.ToArrayData(); |
| 69 | + auto out_data = out->array_data_mutable(); |
| 70 | + if (!maybe_quantiles.has_value()) { |
| 71 | + // Only nulls and NaNs => return input as-is |
| 72 | + out_data->null_count = data->null_count.load(); |
| 73 | + out_data->length = data->length; |
| 74 | + out_data->buffers = data->buffers; |
| 75 | + return Status::OK(); |
| 76 | + } |
| 77 | + return ClipValues(*data, maybe_quantiles.value(), out_data, ctx); |
| 78 | + } |
| 79 | + |
| 80 | + static Status ExecChunked(KernelContext* ctx, const ExecBatch& batch, Datum* out) { |
| 81 | + const auto& options = WinsorizeState::Get(ctx); |
| 82 | + RETURN_NOT_OK(ValidateOptions(options)); |
| 83 | + ARROW_ASSIGN_OR_RAISE(auto maybe_quantiles, GetQuantileValues(ctx, batch, options)); |
| 84 | + const auto& chunked_array = batch.values[0].chunked_array(); |
| 85 | + if (!maybe_quantiles.has_value()) { |
| 86 | + // Only nulls and NaNs => return input as-is |
| 87 | + *out = chunked_array; |
| 88 | + return Status::OK(); |
| 89 | + } |
| 90 | + ArrayVector out_chunks; |
| 91 | + out_chunks.reserve(chunked_array->num_chunks()); |
| 92 | + for (const auto& chunk : chunked_array->chunks()) { |
| 93 | + auto out_data = chunk->data()->Copy(); |
| 94 | + RETURN_NOT_OK( |
| 95 | + ClipValues(*chunk->data(), maybe_quantiles.value(), out_data.get(), ctx)); |
| 96 | + out_chunks.push_back(MakeArray(out_data)); |
| 97 | + } |
| 98 | + return ChunkedArray::Make(std::move(out_chunks)).Value(out); |
| 99 | + } |
| 100 | + |
| 101 | + struct QuantileValues { |
| 102 | + CType lower_bound, upper_bound; |
| 103 | + }; |
| 104 | + |
| 105 | + static Result<std::optional<QuantileValues>> GetQuantileValues( |
| 106 | + KernelContext* ctx, const ExecBatch& batch, const WinsorizeOptions& options) { |
| 107 | + // We use "nearest" to avoid the conversion of quantile values to double. |
| 108 | + QuantileOptions quantile_options(/*q=*/{options.lower_limit, options.upper_limit}, |
| 109 | + QuantileOptions::NEAREST); |
| 110 | + ARROW_ASSIGN_OR_RAISE( |
| 111 | + auto quantile, |
| 112 | + CallFunction("quantile", batch, &quantile_options, ctx->exec_context())); |
| 113 | + auto quantile_array = quantile.array_as<ArrayType>(); |
| 114 | + DCHECK_EQ(quantile_array->length(), 2); |
| 115 | + if (quantile_array->null_count() == 2) { |
| 116 | + return std::nullopt; |
| 117 | + } |
| 118 | + DCHECK_EQ(quantile_array->null_count(), 0); |
| 119 | + return QuantileValues{CType(quantile_array->Value(0)), |
| 120 | + CType(quantile_array->Value(1))}; |
| 121 | + } |
| 122 | + |
| 123 | + static Status ClipValues(const ArrayData& data, QuantileValues quantiles, |
| 124 | + ArrayData* out, KernelContext* ctx) { |
| 125 | + DCHECK_EQ(out->buffers.size(), data.buffers.size()); |
| 126 | + out->null_count = data.null_count.load(); |
| 127 | + out->length = data.length; |
| 128 | + out->buffers[0] = data.buffers[0]; |
| 129 | + ARROW_ASSIGN_OR_RAISE(out->buffers[1], ctx->Allocate(out->length * sizeof(CType))); |
| 130 | + // Avoid leaving uninitialized memory under null entries |
| 131 | + std::memset(out->buffers[1]->mutable_data(), 0, out->length * sizeof(CType)); |
| 132 | + |
| 133 | + const CType* in_values = data.GetValues<CType>(1); |
| 134 | + CType* out_values = out->GetMutableValues<CType>(1); |
| 135 | + |
| 136 | + auto visit = [&](int64_t position, int64_t length) { |
| 137 | + for (int64_t i = position; i < position + length; ++i) { |
| 138 | + if (in_values[i] < quantiles.lower_bound) { |
| 139 | + out_values[i] = quantiles.lower_bound; |
| 140 | + } else if (in_values[i] > quantiles.upper_bound) { |
| 141 | + out_values[i] = quantiles.upper_bound; |
| 142 | + } else { |
| 143 | + // NaNs also fall here |
| 144 | + out_values[i] = in_values[i]; |
| 145 | + } |
| 146 | + } |
| 147 | + }; |
| 148 | + arrow::internal::VisitSetBitRunsVoid(data.buffers[0], data.offset, data.length, |
| 149 | + visit); |
| 150 | + return Status::OK(); |
| 151 | + } |
| 152 | +}; |
| 153 | + |
| 154 | +template <typename Unused, typename Type> |
| 155 | +struct WinsorizeChunked { |
| 156 | + static Status Exec(KernelContext* ctx, const ExecBatch& batch, Datum* out) { |
| 157 | + return Winsorize<Unused, Type>::ExecChunked(ctx, batch, out); |
| 158 | + } |
| 159 | +}; |
| 160 | + |
| 161 | +Result<TypeHolder> ResolveWinsorizeOutput(KernelContext* ctx, |
| 162 | + const std::vector<TypeHolder>& in_types) { |
| 163 | + DCHECK_EQ(in_types.size(), 1); |
| 164 | + return in_types[0]; |
| 165 | +} |
| 166 | + |
| 167 | +const FunctionDoc winsorize_doc( |
| 168 | + "Winsorize an array", |
| 169 | + ("This function applies a winsorization transform to the input array\n" |
| 170 | + "so as to reduce the influence of potential outliers.\n" |
| 171 | + "NaNs and nulls in the input are ignored for the purpose of computing\n" |
| 172 | + "the lower and upper quantiles.\n" |
| 173 | + "The quantile limits can be changed in WinsorizeOptions."), |
| 174 | + {"array"}, "WinsorizeOptions", /*options_required=*/true); |
| 175 | + |
| 176 | +} // namespace |
| 177 | + |
| 178 | +void RegisterVectorStatistics(FunctionRegistry* registry) { |
| 179 | + const static auto default_winsorize_options = WinsorizeOptions(); |
| 180 | + |
| 181 | + auto winsorize = std::make_shared<VectorFunction>( |
| 182 | + "winsorize", Arity::Unary(), winsorize_doc, &default_winsorize_options); |
| 183 | + |
| 184 | + VectorKernel base; |
| 185 | + base.init = WinsorizeState::Init; |
| 186 | + base.mem_allocation = MemAllocation::NO_PREALLOCATE; |
| 187 | + base.null_handling = NullHandling::COMPUTED_NO_PREALLOCATE; |
| 188 | + base.can_execute_chunkwise = false; |
| 189 | + // The variable is ill-named, but since we output a ChunkedArray ourselves, |
| 190 | + // the function execution logic shouldn't try to wrap it again. |
| 191 | + base.output_chunked = false; |
| 192 | + |
| 193 | + for (const auto& ty : NumericTypes()) { |
| 194 | + base.signature = KernelSignature::Make({ty->id()}, &ResolveWinsorizeOutput); |
| 195 | + base.exec = GenerateNumeric<Winsorize, /*Unused*/ void>(ty->id()); |
| 196 | + base.exec_chunked = GenerateNumeric<WinsorizeChunked, /*Unused*/ void>(ty->id()); |
| 197 | + DCHECK_OK(winsorize->AddKernel(base)); |
| 198 | + } |
| 199 | + for (auto type_id : DecimalTypeIds()) { |
| 200 | + base.signature = KernelSignature::Make({type_id}, &ResolveWinsorizeOutput); |
| 201 | + base.exec = GenerateDecimal<Winsorize, /*Unused*/ void>(type_id); |
| 202 | + base.exec_chunked = GenerateDecimal<WinsorizeChunked, /*Unused*/ void>(type_id); |
| 203 | + DCHECK_OK(winsorize->AddKernel(base)); |
| 204 | + } |
| 205 | + DCHECK_OK(registry->AddFunction(std::move(winsorize))); |
| 206 | +} |
| 207 | + |
| 208 | +} // namespace arrow::compute::internal |
0 commit comments