| 58 | // We have a first unused template parameter for compatibility with GenerateNumeric. |
| 59 | template <typename Unused, typename Type> |
| 60 | struct Winsorize { |
| 61 | using ArrayType = typename TypeTraits<Type>::ArrayType; |
| 62 | using CType = typename TypeTraits<Type>::CType; |
| 63 | |
| 64 | static Status Exec(KernelContext* ctx, const ExecSpan& batch, ExecResult* out) { |
| 65 | const auto& options = WinsorizeState::Get(ctx); |
| 66 | RETURN_NOT_OK(ValidateOptions(options)); |
| 67 | auto data = batch.values[0].array.ToArrayData(); |
| 68 | ARROW_ASSIGN_OR_RAISE(auto maybe_quantiles, GetQuantileValues(ctx, data, options)); |
| 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 | const auto& chunked_array = batch.values[0].chunked_array(); |
| 84 | ARROW_ASSIGN_OR_RAISE(auto maybe_quantiles, |
| 85 | GetQuantileValues(ctx, chunked_array, options)); |
| 86 | if (!maybe_quantiles.has_value()) { |
| 87 | // Only nulls and NaNs => return input as-is |
| 88 | *out = chunked_array; |
| 89 | return Status::OK(); |
| 90 | } |
| 91 | ArrayVector out_chunks; |
| 92 | out_chunks.reserve(chunked_array->num_chunks()); |
| 93 | for (const auto& chunk : chunked_array->chunks()) { |
| 94 | auto out_data = chunk->data()->Copy(); |
| 95 | RETURN_NOT_OK( |
| 96 | ClipValues(*chunk->data(), maybe_quantiles.value(), out_data.get(), ctx)); |
| 97 | out_chunks.push_back(MakeArray(out_data)); |
| 98 | } |
| 99 | return ChunkedArray::Make(std::move(out_chunks)).Value(out); |
| 100 | } |
| 101 | |
| 102 | struct QuantileValues { |
| 103 | CType lower_bound, upper_bound; |
| 104 | }; |
| 105 | |
| 106 | static Result<std::optional<QuantileValues>> GetQuantileValues( |
| 107 | KernelContext* ctx, const Datum& input, const WinsorizeOptions& options) { |
| 108 | // We use "nearest" to avoid the conversion of quantile values to double. |
| 109 | QuantileOptions quantile_options(/*q=*/{options.lower_limit, options.upper_limit}, |
| 110 | QuantileOptions::NEAREST); |
| 111 | ARROW_ASSIGN_OR_RAISE( |
| 112 | auto quantile, |
| 113 | CallFunction("quantile", {input}, &quantile_options, ctx->exec_context())); |
| 114 | auto quantile_array = quantile.array_as<ArrayType>(); |
| 115 | DCHECK_EQ(quantile_array->length(), 2); |
| 116 | // The quantile function outputs either all nulls or no nulls at all. |
| 117 | if (quantile_array->null_count() == 2) { |
no test coverage detected