From 49fa7babf9a10717344ae8039cf14b4425f02e9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alex=20=C5=9Euhan?= Date: Sun, 5 Dec 2021 22:06:47 -0800 Subject: [PATCH 01/15] ARROW-12404: [C++] Implement "random" nullary function that generates uniform random between 0 and 1 --- cpp/src/arrow/CMakeLists.txt | 1 + cpp/src/arrow/compute/kernels/CMakeLists.txt | 1 + cpp/src/arrow/compute/kernels/random.cc | 60 +++++++++++++++++++ .../compute/kernels/scalar_random_test.cc | 49 +++++++++++++++ cpp/src/arrow/compute/registry.cc | 3 + cpp/src/arrow/compute/registry_internal.h | 3 + docs/source/cpp/compute.rst | 11 ++++ python/pyarrow/tests/test_compute.py | 4 +- 8 files changed, 130 insertions(+), 2 deletions(-) create mode 100644 cpp/src/arrow/compute/kernels/random.cc create mode 100644 cpp/src/arrow/compute/kernels/scalar_random_test.cc diff --git a/cpp/src/arrow/CMakeLists.txt b/cpp/src/arrow/CMakeLists.txt index cc979a22e09f..26e7fc8c41e5 100644 --- a/cpp/src/arrow/CMakeLists.txt +++ b/cpp/src/arrow/CMakeLists.txt @@ -407,6 +407,7 @@ if(ARROW_COMPUTE) compute/kernels/aggregate_var_std.cc compute/kernels/codegen_internal.cc compute/kernels/hash_aggregate.cc + compute/kernels/random.cc compute/kernels/row_encoder.cc compute/kernels/scalar_arithmetic.cc compute/kernels/scalar_boolean.cc diff --git a/cpp/src/arrow/compute/kernels/CMakeLists.txt b/cpp/src/arrow/compute/kernels/CMakeLists.txt index 28686a9cafa9..65baa1d5fba9 100644 --- a/cpp/src/arrow/compute/kernels/CMakeLists.txt +++ b/cpp/src/arrow/compute/kernels/CMakeLists.txt @@ -20,6 +20,7 @@ add_arrow_compute_test(scalar_test SOURCES + scalar_random_test.cc scalar_arithmetic_test.cc scalar_boolean_test.cc scalar_cast_test.cc diff --git a/cpp/src/arrow/compute/kernels/random.cc b/cpp/src/arrow/compute/kernels/random.cc new file mode 100644 index 000000000000..fcab69f81e48 --- /dev/null +++ b/cpp/src/arrow/compute/kernels/random.cc @@ -0,0 +1,60 @@ +// 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 +#include + +#include "arrow/compute/kernel.h" +#include "arrow/compute/kernels/common.h" +#include "arrow/compute/registry.h" +#include "arrow/util/pcg_random.h" + +namespace arrow { +namespace compute { +namespace internal { +namespace { + +// Generates a random floating point number in range [0, 1). +double generate_uniform(random::pcg64& rng) { + return (rng() >> 11) * (1.0 / 9007199254740992.0); +} + +Status ExecRandom(KernelContext* ctx, const ExecBatch& batch, Datum* out) { + static thread_local std::random_device rd; + static thread_local random::pcg64 gen(rd()); + double value = generate_uniform(gen); + BoxScalar::Box(value, out->scalar().get()); + return Status::OK(); +} + +const FunctionDoc random_doc{ + "Generates a number between 0 and 1", + "Generates an uniformly-distributed double-precision number between 0 and 1.", + {}}; + +} // namespace + +void RegisterRandom(FunctionRegistry* registry) { + auto random_func = + std::make_shared("random", Arity::Nullary(), &random_doc); + DCHECK_OK(random_func->AddKernel({}, float64(), ExecRandom)); + DCHECK_OK(registry->AddFunction(std::move(random_func))); +} + +} // namespace internal +} // namespace compute +} // namespace arrow diff --git a/cpp/src/arrow/compute/kernels/scalar_random_test.cc b/cpp/src/arrow/compute/kernels/scalar_random_test.cc new file mode 100644 index 000000000000..38b3aa80eef2 --- /dev/null +++ b/cpp/src/arrow/compute/kernels/scalar_random_test.cc @@ -0,0 +1,49 @@ +// 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 + +#include + +#include "arrow/compute/api.h" +#include "arrow/testing/gtest_util.h" + +namespace arrow { +namespace compute { + +TEST(TestRandom, Basic) { + const int kCount = 100000; + double sum = 0; + double square_sum = 0; + for (int i = 0; i < kCount; ++i) { + ASSERT_OK_AND_ASSIGN(Datum result, CallFunction("random", {})); + const auto& result_scalar = result.scalar_as(); + ASSERT_GE(result_scalar.value, 0); + ASSERT_LT(result_scalar.value, 1); + sum += result_scalar.value; + square_sum += result_scalar.value * result_scalar.value; + } + + // verify E(X), E(X^2) is near theory + const double E_X = 0.5; + const double E_X2 = 1.0 / 12 + E_X * E_X; + ASSERT_NEAR(sum / kCount, E_X, std::abs(E_X) * 0.02); + ASSERT_NEAR(square_sum / kCount, E_X2, E_X2 * 0.02); +} + +} // namespace compute +} // namespace arrow diff --git a/cpp/src/arrow/compute/registry.cc b/cpp/src/arrow/compute/registry.cc index c6455874dbc9..c3f702170b9e 100644 --- a/cpp/src/arrow/compute/registry.cc +++ b/cpp/src/arrow/compute/registry.cc @@ -188,6 +188,9 @@ static std::unique_ptr CreateBuiltInRegistry() { RegisterScalarAggregateTDigest(registry.get()); RegisterScalarAggregateVariance(registry.get()); + // Random generator function + RegisterRandom(registry.get()); + RegisterAggregateOptions(registry.get()); return registry; diff --git a/cpp/src/arrow/compute/registry_internal.h b/cpp/src/arrow/compute/registry_internal.h index 98f61185f7bb..3a1fa613c13a 100644 --- a/cpp/src/arrow/compute/registry_internal.h +++ b/cpp/src/arrow/compute/registry_internal.h @@ -59,6 +59,9 @@ void RegisterScalarAggregateVariance(FunctionRegistry* registry); void RegisterAggregateOptions(FunctionRegistry* registry); +// Uniform random generator +void RegisterRandom(FunctionRegistry* registry); + } // namespace internal } // namespace compute } // namespace arrow diff --git a/docs/source/cpp/compute.rst b/docs/source/cpp/compute.rst index 8699f9134a01..a6038cfeba80 100644 --- a/docs/source/cpp/compute.rst +++ b/docs/source/cpp/compute.rst @@ -1659,3 +1659,14 @@ replaced, based on the remaining inputs. results in a corresponding null in the output. Also see: :ref:`if_else `. + +Random number generation +~~~~~~~~~~~~~~~~~~~~~~~~ + +This function generates an uniformly-distributed double-precision number between 0 and 1. + ++--------------------+------------+---------------+ +| Function name | Arity | Output type | ++====================+============+===============+ +| random | Nullary | Double | ++--------------------+------------+---------------+ diff --git a/python/pyarrow/tests/test_compute.py b/python/pyarrow/tests/test_compute.py index cacc40decea8..9e26208e127e 100644 --- a/python/pyarrow/tests/test_compute.py +++ b/python/pyarrow/tests/test_compute.py @@ -91,6 +91,8 @@ def test_exported_functions(): # message if we don't pass an options instance. continue arity = desc['arity'] + if arity == 0: + continue if arity is Ellipsis: args = [object()] * 3 else: @@ -274,8 +276,6 @@ def test_function_attributes(): kernels = func.kernels assert func.num_kernels == len(kernels) assert all(isinstance(ker, pc.Kernel) for ker in kernels) - if func.arity is not Ellipsis: - assert func.arity >= 1 repr(func) for ker in kernels: repr(ker) From e58335c2fe4e21dd6673917c2f58a932fb8990ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alex=20=C5=9Euhan?= Date: Sun, 5 Dec 2021 22:06:47 -0800 Subject: [PATCH 02/15] ARROW-12404: Add option to set the seed --- cpp/src/arrow/compute/api_scalar.cc | 11 +++++ cpp/src/arrow/compute/api_scalar.h | 24 +++++++++ cpp/src/arrow/compute/kernels/random.cc | 37 +++++++++++--- .../compute/kernels/scalar_random_test.cc | 49 ++++++++++++++----- docs/source/cpp/compute.rst | 17 ++++--- 5 files changed, 114 insertions(+), 24 deletions(-) diff --git a/cpp/src/arrow/compute/api_scalar.cc b/cpp/src/arrow/compute/api_scalar.cc index 24a5a1ee77e1..8ecb30c9eab7 100644 --- a/cpp/src/arrow/compute/api_scalar.cc +++ b/cpp/src/arrow/compute/api_scalar.cc @@ -280,6 +280,8 @@ static auto kWeekOptionsType = GetFunctionOptionsType( DataMember("week_starts_monday", &WeekOptions::week_starts_monday), DataMember("count_from_zero", &WeekOptions::count_from_zero), DataMember("first_week_is_fully_in_year", &WeekOptions::first_week_is_fully_in_year)); +static auto kRandomOptionsType = + GetFunctionOptionsType(DataMember("seed", &RandomOptions::seed)); } // namespace } // namespace internal @@ -467,6 +469,14 @@ WeekOptions::WeekOptions(bool week_starts_monday, bool count_from_zero, first_week_is_fully_in_year(first_week_is_fully_in_year) {} constexpr char WeekOptions::kTypeName[]; +RandomOptions::RandomOptions(Initializer initializer, int64_t length, int64_t seed) + : FunctionOptions(internal::kRandomOptionsType), + initializer(initializer), + length(length), + seed(seed) {} +RandomOptions::RandomOptions() : RandomOptions(SystemRandom, -1, 0) {} +constexpr char RandomOptions::kTypeName[]; + namespace internal { void RegisterScalarOptions(FunctionRegistry* registry) { DCHECK_OK(registry->AddFunctionOptionsType(kArithmeticOptionsType)); @@ -493,6 +503,7 @@ void RegisterScalarOptions(FunctionRegistry* registry) { DCHECK_OK(registry->AddFunctionOptionsType(kTrimOptionsType)); DCHECK_OK(registry->AddFunctionOptionsType(kUtf8NormalizeOptionsType)); DCHECK_OK(registry->AddFunctionOptionsType(kWeekOptionsType)); + DCHECK_OK(registry->AddFunctionOptionsType(kRandomOptionsType)); } } // namespace internal diff --git a/cpp/src/arrow/compute/api_scalar.h b/cpp/src/arrow/compute/api_scalar.h index 6e1c1ac74e8a..c319226ebfbc 100644 --- a/cpp/src/arrow/compute/api_scalar.h +++ b/cpp/src/arrow/compute/api_scalar.h @@ -28,6 +28,7 @@ #include "arrow/datum.h" #include "arrow/result.h" #include "arrow/util/macros.h" +#include "arrow/util/optional.h" #include "arrow/util/visibility.h" namespace arrow { @@ -420,6 +421,29 @@ struct ARROW_EXPORT Utf8NormalizeOptions : public FunctionOptions { Form form; }; +class ARROW_EXPORT RandomOptions : public FunctionOptions { + public: + enum Initializer { SystemRandom, Seed }; + + static RandomOptions FromSystemRandom(int64_t length) { + return RandomOptions{SystemRandom, length, 0}; + } + static RandomOptions FromSeed(int64_t length, int64_t seed) { + return RandomOptions{Seed, length, seed}; + } + + RandomOptions(Initializer initializer, int64_t length, int64_t seed); + // Default constructor creates an invalid options struct, but is required for Python + RandomOptions(); + constexpr static char const kTypeName[] = "RandomOptions"; + static RandomOptions Defaults() { return RandomOptions(); } + + Initializer initializer; + int64_t length; // negative means invalid + /// The seed value used to initialize the random number generation. + int64_t seed; +}; + /// @} /// \brief Get the absolute value of a value. diff --git a/cpp/src/arrow/compute/kernels/random.cc b/cpp/src/arrow/compute/kernels/random.cc index fcab69f81e48..26a5c809a200 100644 --- a/cpp/src/arrow/compute/kernels/random.cc +++ b/cpp/src/arrow/compute/kernels/random.cc @@ -18,6 +18,8 @@ #include #include +#include "arrow/builder.h" +#include "arrow/compute/api_scalar.h" #include "arrow/compute/kernel.h" #include "arrow/compute/kernels/common.h" #include "arrow/compute/registry.h" @@ -33,11 +35,28 @@ double generate_uniform(random::pcg64& rng) { return (rng() >> 11) * (1.0 / 9007199254740992.0); } +using RandomState = OptionsWrapper; + Status ExecRandom(KernelContext* ctx, const ExecBatch& batch, Datum* out) { static thread_local std::random_device rd; - static thread_local random::pcg64 gen(rd()); - double value = generate_uniform(gen); - BoxScalar::Box(value, out->scalar().get()); + static thread_local random::pcg64 gen; + const RandomOptions& options = RandomState::Get(ctx); + DoubleBuilder builder(ctx->memory_pool()); + if (options.length < 0) { + return Status::Invalid("Negative number of elements"); + } + RETURN_NOT_OK(builder.Reserve(options.length)); + if (options.initializer == RandomOptions::Seed) { + gen.seed(options.seed); + } else { + gen.seed(rd()); + } + for (int i = 0; i < options.length; ++i) { + builder.UnsafeAppend(generate_uniform(gen)); + } + std::shared_ptr double_array; + RETURN_NOT_OK(builder.Finish(&double_array)); + *out = *double_array->data(); return Status::OK(); } @@ -49,9 +68,15 @@ const FunctionDoc random_doc{ } // namespace void RegisterRandom(FunctionRegistry* registry) { - auto random_func = - std::make_shared("random", Arity::Nullary(), &random_doc); - DCHECK_OK(random_func->AddKernel({}, float64(), ExecRandom)); + static auto random_options = RandomOptions::Defaults(); + + auto random_func = std::make_shared("random", Arity::Nullary(), + &random_doc, &random_options); + ScalarKernel kernel{ + {}, ValueDescr(float64(), ValueDescr::Shape::ARRAY), ExecRandom, RandomState::Init}; + kernel.null_handling = NullHandling::OUTPUT_NOT_NULL; + kernel.mem_allocation = MemAllocation::NO_PREALLOCATE; + DCHECK_OK(random_func->AddKernel(kernel)); DCHECK_OK(registry->AddFunction(std::move(random_func))); } diff --git a/cpp/src/arrow/compute/kernels/scalar_random_test.cc b/cpp/src/arrow/compute/kernels/scalar_random_test.cc index 38b3aa80eef2..43eaf67e850d 100644 --- a/cpp/src/arrow/compute/kernels/scalar_random_test.cc +++ b/cpp/src/arrow/compute/kernels/scalar_random_test.cc @@ -21,28 +21,55 @@ #include "arrow/compute/api.h" #include "arrow/testing/gtest_util.h" +#include "arrow/util/checked_cast.h" namespace arrow { namespace compute { +namespace { -TEST(TestRandom, Basic) { - const int kCount = 100000; +void TestRandomWithOptions(const RandomOptions& random_options) { + using arrow::internal::checked_cast; double sum = 0; double square_sum = 0; - for (int i = 0; i < kCount; ++i) { - ASSERT_OK_AND_ASSIGN(Datum result, CallFunction("random", {})); - const auto& result_scalar = result.scalar_as(); - ASSERT_GE(result_scalar.value, 0); - ASSERT_LT(result_scalar.value, 1); - sum += result_scalar.value; - square_sum += result_scalar.value * result_scalar.value; + ASSERT_OK_AND_ASSIGN(Datum result, CallFunction("random", {}, &random_options)); + auto result_array = result.make_array(); + ASSERT_EQ(result_array->length(), random_options.length); + for (int i = 0; i < random_options.length; ++i) { + ASSERT_OK_AND_ASSIGN(auto result_scalar, result_array->GetScalar(i)); + const auto& double_scalar = checked_cast(*result_scalar); + ASSERT_GE(double_scalar.value, 0); + ASSERT_LT(double_scalar.value, 1); + sum += double_scalar.value; + square_sum += double_scalar.value * double_scalar.value; } // verify E(X), E(X^2) is near theory const double E_X = 0.5; const double E_X2 = 1.0 / 12 + E_X * E_X; - ASSERT_NEAR(sum / kCount, E_X, std::abs(E_X) * 0.02); - ASSERT_NEAR(square_sum / kCount, E_X2, E_X2 * 0.02); + ASSERT_NEAR(sum / random_options.length, E_X, std::abs(E_X) * 0.02); + ASSERT_NEAR(square_sum / random_options.length, E_X2, E_X2 * 0.02); +} + +} // namespace + +TEST(TestRandom, Seed) { + const int kCount = 100000; + auto random_options = RandomOptions::FromSeed(/*length=*/kCount, /*seed=*/0); + TestRandomWithOptions(random_options); +} + +TEST(TestRandom, SystemRandom) { + const int kCount = 100000; + auto random_options = RandomOptions::FromSystemRandom(/*length=*/kCount); + TestRandomWithOptions(random_options); +} + +TEST(TestRandom, SeedIsDeterministic) { + const int kCount = 100; + auto random_options = RandomOptions::FromSeed(/*length=*/kCount, /*seed=*/0); + ASSERT_OK_AND_ASSIGN(Datum first_call, CallFunction("random", {}, &random_options)); + ASSERT_OK_AND_ASSIGN(Datum second_call, CallFunction("random", {}, &random_options)); + AssertDatumsEqual(first_call, second_call); } } // namespace compute diff --git a/docs/source/cpp/compute.rst b/docs/source/cpp/compute.rst index a6038cfeba80..797db0468e39 100644 --- a/docs/source/cpp/compute.rst +++ b/docs/source/cpp/compute.rst @@ -1663,10 +1663,13 @@ replaced, based on the remaining inputs. Random number generation ~~~~~~~~~~~~~~~~~~~~~~~~ -This function generates an uniformly-distributed double-precision number between 0 and 1. - -+--------------------+------------+---------------+ -| Function name | Arity | Output type | -+====================+============+===============+ -| random | Nullary | Double | -+--------------------+------------+---------------+ +This function generates an array of uniformly-distributed double-precision numbers +between 0 and 1. The options provide the length of the output and the algorithm for +generating the random numbers, using either a seed or a system-provided, platform-specific +random generator. + ++--------------------+------------+---------------+-------------------------+ +| Function name | Arity | Output type | Options class | ++====================+============+===============+=========================+ +| random | Nullary | Double | :struct:`RandomOptions` | ++--------------------+------------+---------------+-------------------------+ From ef044303e07283bc358db77ca92115178d7938c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alex=20=C5=9Euhan?= Date: Wed, 15 Dec 2021 22:19:17 -0800 Subject: [PATCH 03/15] ARROW-12404: Add NullaryOptions base class for RandomOptions --- cpp/src/arrow/compute/api_scalar.cc | 8 ++++---- cpp/src/arrow/compute/api_scalar.h | 12 ++++++++++-- cpp/src/arrow/compute/exec/expression.cc | 4 ++++ 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/cpp/src/arrow/compute/api_scalar.cc b/cpp/src/arrow/compute/api_scalar.cc index 8ecb30c9eab7..201fba42e7d0 100644 --- a/cpp/src/arrow/compute/api_scalar.cc +++ b/cpp/src/arrow/compute/api_scalar.cc @@ -469,11 +469,11 @@ WeekOptions::WeekOptions(bool week_starts_monday, bool count_from_zero, first_week_is_fully_in_year(first_week_is_fully_in_year) {} constexpr char WeekOptions::kTypeName[]; +NullaryOptions::NullaryOptions(int64_t length) + : FunctionOptions(internal::kRandomOptionsType), length(length) {} + RandomOptions::RandomOptions(Initializer initializer, int64_t length, int64_t seed) - : FunctionOptions(internal::kRandomOptionsType), - initializer(initializer), - length(length), - seed(seed) {} + : NullaryOptions(length), initializer(initializer), seed(seed) {} RandomOptions::RandomOptions() : RandomOptions(SystemRandom, -1, 0) {} constexpr char RandomOptions::kTypeName[]; diff --git a/cpp/src/arrow/compute/api_scalar.h b/cpp/src/arrow/compute/api_scalar.h index c319226ebfbc..f66fc01f52f3 100644 --- a/cpp/src/arrow/compute/api_scalar.h +++ b/cpp/src/arrow/compute/api_scalar.h @@ -421,7 +421,15 @@ struct ARROW_EXPORT Utf8NormalizeOptions : public FunctionOptions { Form form; }; -class ARROW_EXPORT RandomOptions : public FunctionOptions { +class ARROW_EXPORT NullaryOptions : public FunctionOptions { + public: + explicit NullaryOptions(int64_t length); + + /// The length of the array returned by the nullary function. Negative is invalid. + int64_t length; +}; + +class ARROW_EXPORT RandomOptions : public NullaryOptions { public: enum Initializer { SystemRandom, Seed }; @@ -438,8 +446,8 @@ class ARROW_EXPORT RandomOptions : public FunctionOptions { constexpr static char const kTypeName[] = "RandomOptions"; static RandomOptions Defaults() { return RandomOptions(); } + /// The type of initialization for random number generation - system or provided seed. Initializer initializer; - int64_t length; // negative means invalid /// The seed value used to initialize the random number generation. int64_t seed; }; diff --git a/cpp/src/arrow/compute/exec/expression.cc b/cpp/src/arrow/compute/exec/expression.cc index 4249179e1bf8..51bd45388a96 100644 --- a/cpp/src/arrow/compute/exec/expression.cc +++ b/cpp/src/arrow/compute/exec/expression.cc @@ -541,6 +541,10 @@ Result ExecuteScalarExpression(const Expression& expr, const ExecBatch& i auto kernel = call->kernel; auto descrs = GetDescriptors(arguments); auto options = call->options.get(); + if (arguments.size() == 0 && dynamic_cast(options)) { + auto nullary_options = static_cast(options); + nullary_options->length = input.length; + } RETURN_NOT_OK(executor->Init(&kernel_context, {kernel, descrs, options})); compute::detail::DatumAccumulator listener; From ec7fbb057cf13f2ed60673f6c0573e29f405b586 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alex=20=C5=9Euhan?= Date: Thu, 16 Dec 2021 18:58:50 -0800 Subject: [PATCH 04/15] ARROW-12404: Use pcg64_fast and improve documentation --- cpp/src/arrow/compute/kernels/random.cc | 14 ++++++++----- docs/source/cpp/compute.rst | 28 ++++++++++++------------- 2 files changed, 23 insertions(+), 19 deletions(-) diff --git a/cpp/src/arrow/compute/kernels/random.cc b/cpp/src/arrow/compute/kernels/random.cc index 26a5c809a200..f4d7c1652cc8 100644 --- a/cpp/src/arrow/compute/kernels/random.cc +++ b/cpp/src/arrow/compute/kernels/random.cc @@ -31,7 +31,9 @@ namespace internal { namespace { // Generates a random floating point number in range [0, 1). -double generate_uniform(random::pcg64& rng) { +double generate_uniform(random::pcg64_fast& rng) { + // This equation is copied from numpy. It calculates `rng() / 2^64` and + // the return value is strictly less than 1. return (rng() >> 11) * (1.0 / 9007199254740992.0); } @@ -39,7 +41,7 @@ using RandomState = OptionsWrapper; Status ExecRandom(KernelContext* ctx, const ExecBatch& batch, Datum* out) { static thread_local std::random_device rd; - static thread_local random::pcg64 gen; + static thread_local random::pcg64_fast gen; const RandomOptions& options = RandomState::Get(ctx); DoubleBuilder builder(ctx->memory_pool()); if (options.length < 0) { @@ -61,9 +63,11 @@ Status ExecRandom(KernelContext* ctx, const ExecBatch& batch, Datum* out) { } const FunctionDoc random_doc{ - "Generates a number between 0 and 1", - "Generates an uniformly-distributed double-precision number between 0 and 1.", - {}}; + "Generates a number in range [0, 1)", + ("Generated values are uniformly-distributed, double-precision in range [0, 1).\n" + "Length of generated data, algorithm and seed can be changed via RandomOptions."), + {}, + "RandomOptions"}; } // namespace diff --git a/docs/source/cpp/compute.rst b/docs/source/cpp/compute.rst index 797db0468e39..6e3944ab11fd 100644 --- a/docs/source/cpp/compute.rst +++ b/docs/source/cpp/compute.rst @@ -1489,6 +1489,20 @@ An error is returned if the timestamps already have the timezone metadata set. allows choosing the behaviour when a timestamp is ambiguous or nonexistent in the given timezone (because of DST shifts). +Random number generation +~~~~~~~~~~~~~~~~~~~~~~~~ + +This function generates an array of uniformly-distributed double-precision numbers +in range [0, 1). The options provide the length of the output and the algorithm for +generating the random numbers, using either a seed or a system-provided, platform-specific +random generator. + ++--------------------+------------+---------------+-------------------------+ +| Function name | Arity | Output type | Options class | ++====================+============+===============+=========================+ +| random | Nullary | Double | :struct:`RandomOptions` | ++--------------------+------------+---------------+-------------------------+ + Array-wise ("vector") functions ------------------------------- @@ -1659,17 +1673,3 @@ replaced, based on the remaining inputs. results in a corresponding null in the output. Also see: :ref:`if_else `. - -Random number generation -~~~~~~~~~~~~~~~~~~~~~~~~ - -This function generates an array of uniformly-distributed double-precision numbers -between 0 and 1. The options provide the length of the output and the algorithm for -generating the random numbers, using either a seed or a system-provided, platform-specific -random generator. - -+--------------------+------------+---------------+-------------------------+ -| Function name | Arity | Output type | Options class | -+====================+============+===============+=========================+ -| random | Nullary | Double | :struct:`RandomOptions` | -+--------------------+------------+---------------+-------------------------+ From 5dba8b68a7d0f7596d9ce903e2b0ca154226c2f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alex=20=C5=9Euhan?= Date: Fri, 17 Dec 2021 22:44:02 -0800 Subject: [PATCH 05/15] ARROW-12404: Allocate random_device and pcg64_fast on stack --- cpp/src/arrow/compute/kernels/random.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cpp/src/arrow/compute/kernels/random.cc b/cpp/src/arrow/compute/kernels/random.cc index f4d7c1652cc8..6b0f0a8fcbb7 100644 --- a/cpp/src/arrow/compute/kernels/random.cc +++ b/cpp/src/arrow/compute/kernels/random.cc @@ -40,8 +40,7 @@ double generate_uniform(random::pcg64_fast& rng) { using RandomState = OptionsWrapper; Status ExecRandom(KernelContext* ctx, const ExecBatch& batch, Datum* out) { - static thread_local std::random_device rd; - static thread_local random::pcg64_fast gen; + random::pcg64_fast gen; const RandomOptions& options = RandomState::Get(ctx); DoubleBuilder builder(ctx->memory_pool()); if (options.length < 0) { @@ -51,6 +50,7 @@ Status ExecRandom(KernelContext* ctx, const ExecBatch& batch, Datum* out) { if (options.initializer == RandomOptions::Seed) { gen.seed(options.seed); } else { + std::random_device rd; gen.seed(rd()); } for (int i = 0; i < options.length; ++i) { From 941e8751201665fe647be8bc33dd59954be61033 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alex=20=C5=9Euhan?= Date: Fri, 17 Dec 2021 22:34:02 -0800 Subject: [PATCH 06/15] ARROW-12404: Rename and move RegisterRandom --- cpp/src/arrow/compute/kernels/random.cc | 2 +- cpp/src/arrow/compute/registry.cc | 6 +++--- cpp/src/arrow/compute/registry_internal.h | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/cpp/src/arrow/compute/kernels/random.cc b/cpp/src/arrow/compute/kernels/random.cc index 6b0f0a8fcbb7..4b279ef58fb6 100644 --- a/cpp/src/arrow/compute/kernels/random.cc +++ b/cpp/src/arrow/compute/kernels/random.cc @@ -71,7 +71,7 @@ const FunctionDoc random_doc{ } // namespace -void RegisterRandom(FunctionRegistry* registry) { +void RegisterNullaryRandom(FunctionRegistry* registry) { static auto random_options = RandomOptions::Defaults(); auto random_func = std::make_shared("random", Arity::Nullary(), diff --git a/cpp/src/arrow/compute/registry.cc b/cpp/src/arrow/compute/registry.cc index c3f702170b9e..e94c5b072184 100644 --- a/cpp/src/arrow/compute/registry.cc +++ b/cpp/src/arrow/compute/registry.cc @@ -188,11 +188,11 @@ static std::unique_ptr CreateBuiltInRegistry() { RegisterScalarAggregateTDigest(registry.get()); RegisterScalarAggregateVariance(registry.get()); - // Random generator function - RegisterRandom(registry.get()); - RegisterAggregateOptions(registry.get()); + // Random generator function + RegisterNullaryRandom(registry.get()); + return registry; } diff --git a/cpp/src/arrow/compute/registry_internal.h b/cpp/src/arrow/compute/registry_internal.h index 3a1fa613c13a..853d2088f4bf 100644 --- a/cpp/src/arrow/compute/registry_internal.h +++ b/cpp/src/arrow/compute/registry_internal.h @@ -60,7 +60,7 @@ void RegisterScalarAggregateVariance(FunctionRegistry* registry); void RegisterAggregateOptions(FunctionRegistry* registry); // Uniform random generator -void RegisterRandom(FunctionRegistry* registry); +void RegisterNullaryRandom(FunctionRegistry* registry); } // namespace internal } // namespace compute From 879505526778722bdb53151ca9544bdc21f07e74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alex=20=C5=9Euhan?= Date: Mon, 20 Dec 2021 18:08:16 -0800 Subject: [PATCH 07/15] ARROW-12404: Use a static seed generator --- cpp/src/arrow/compute/kernels/random.cc | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/cpp/src/arrow/compute/kernels/random.cc b/cpp/src/arrow/compute/kernels/random.cc index 4b279ef58fb6..9c7fe83a4707 100644 --- a/cpp/src/arrow/compute/kernels/random.cc +++ b/cpp/src/arrow/compute/kernels/random.cc @@ -16,6 +16,7 @@ // under the License. #include +#include #include #include "arrow/builder.h" @@ -40,6 +41,9 @@ double generate_uniform(random::pcg64_fast& rng) { using RandomState = OptionsWrapper; Status ExecRandom(KernelContext* ctx, const ExecBatch& batch, Datum* out) { + static random::pcg64_fast seed_gen((std::random_device{})()); + static std::mutex seed_gen_mutex; + random::pcg64_fast gen; const RandomOptions& options = RandomState::Get(ctx); DoubleBuilder builder(ctx->memory_pool()); @@ -50,8 +54,8 @@ Status ExecRandom(KernelContext* ctx, const ExecBatch& batch, Datum* out) { if (options.initializer == RandomOptions::Seed) { gen.seed(options.seed); } else { - std::random_device rd; - gen.seed(rd()); + std::lock_guard seed_gen_lock(seed_gen_mutex); + gen.seed(seed_gen()); } for (int i = 0; i < options.length; ++i) { builder.UnsafeAppend(generate_uniform(gen)); From 320874da93e6110cf3cc44cfa47bbac64a7a4652 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alex=20=C5=9Euhan?= Date: Mon, 20 Dec 2021 18:56:13 -0800 Subject: [PATCH 08/15] ARROW-12404: Fill values directly in the underlying buffer Bypass array builder API. --- cpp/src/arrow/compute/api_scalar.h | 1 - cpp/src/arrow/compute/kernels/random.cc | 19 +++++++++++-------- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/cpp/src/arrow/compute/api_scalar.h b/cpp/src/arrow/compute/api_scalar.h index f66fc01f52f3..3c9053ac1578 100644 --- a/cpp/src/arrow/compute/api_scalar.h +++ b/cpp/src/arrow/compute/api_scalar.h @@ -28,7 +28,6 @@ #include "arrow/datum.h" #include "arrow/result.h" #include "arrow/util/macros.h" -#include "arrow/util/optional.h" #include "arrow/util/visibility.h" namespace arrow { diff --git a/cpp/src/arrow/compute/kernels/random.cc b/cpp/src/arrow/compute/kernels/random.cc index 9c7fe83a4707..1b8a6978cd72 100644 --- a/cpp/src/arrow/compute/kernels/random.cc +++ b/cpp/src/arrow/compute/kernels/random.cc @@ -19,7 +19,6 @@ #include #include -#include "arrow/builder.h" #include "arrow/compute/api_scalar.h" #include "arrow/compute/kernel.h" #include "arrow/compute/kernels/common.h" @@ -46,23 +45,27 @@ Status ExecRandom(KernelContext* ctx, const ExecBatch& batch, Datum* out) { random::pcg64_fast gen; const RandomOptions& options = RandomState::Get(ctx); - DoubleBuilder builder(ctx->memory_pool()); if (options.length < 0) { return Status::Invalid("Negative number of elements"); } - RETURN_NOT_OK(builder.Reserve(options.length)); + + auto out_data = ArrayData::Make(float64(), options.length, 0); + out_data->buffers.resize(2, nullptr); + + ARROW_ASSIGN_OR_RAISE(out_data->buffers[1], + ctx->Allocate(options.length * sizeof(double))); + double* out_buffer = out_data->template GetMutableValues(1); + if (options.initializer == RandomOptions::Seed) { gen.seed(options.seed); } else { std::lock_guard seed_gen_lock(seed_gen_mutex); gen.seed(seed_gen()); } - for (int i = 0; i < options.length; ++i) { - builder.UnsafeAppend(generate_uniform(gen)); + for (int64_t i = 0; i < options.length; ++i) { + out_buffer[i] = generate_uniform(gen); } - std::shared_ptr double_array; - RETURN_NOT_OK(builder.Finish(&double_array)); - *out = *double_array->data(); + *out = std::move(out_data); return Status::OK(); } From 97387f2508443ddd7a242a23da53c886973791a9 Mon Sep 17 00:00:00 2001 From: Yibo Cai Date: Mon, 20 Dec 2021 05:09:04 +0000 Subject: [PATCH 09/15] code refine, add bench --- cpp/src/arrow/CMakeLists.txt | 2 +- cpp/src/arrow/compute/api_scalar.cc | 35 +++++++++--- cpp/src/arrow/compute/api_scalar.h | 23 +++----- cpp/src/arrow/compute/exec/expression.cc | 4 -- cpp/src/arrow/compute/kernels/CMakeLists.txt | 5 +- .../kernels/{random.cc => scalar_random.cc} | 5 +- .../kernels/scalar_random_benchmark.cc | 56 +++++++++++++++++++ .../compute/kernels/scalar_random_test.cc | 50 ++++++++++------- cpp/src/arrow/compute/registry.cc | 4 +- cpp/src/arrow/compute/registry_internal.h | 4 +- 10 files changed, 131 insertions(+), 57 deletions(-) rename cpp/src/arrow/compute/kernels/{random.cc => scalar_random.cc} (95%) create mode 100644 cpp/src/arrow/compute/kernels/scalar_random_benchmark.cc diff --git a/cpp/src/arrow/CMakeLists.txt b/cpp/src/arrow/CMakeLists.txt index 26e7fc8c41e5..12d5f4120fa3 100644 --- a/cpp/src/arrow/CMakeLists.txt +++ b/cpp/src/arrow/CMakeLists.txt @@ -407,7 +407,6 @@ if(ARROW_COMPUTE) compute/kernels/aggregate_var_std.cc compute/kernels/codegen_internal.cc compute/kernels/hash_aggregate.cc - compute/kernels/random.cc compute/kernels/row_encoder.cc compute/kernels/scalar_arithmetic.cc compute/kernels/scalar_boolean.cc @@ -421,6 +420,7 @@ if(ARROW_COMPUTE) compute/kernels/scalar_compare.cc compute/kernels/scalar_if_else.cc compute/kernels/scalar_nested.cc + compute/kernels/scalar_random.cc compute/kernels/scalar_set_lookup.cc compute/kernels/scalar_string.cc compute/kernels/scalar_temporal_binary.cc diff --git a/cpp/src/arrow/compute/api_scalar.cc b/cpp/src/arrow/compute/api_scalar.cc index 201fba42e7d0..1d1906bc968e 100644 --- a/cpp/src/arrow/compute/api_scalar.cc +++ b/cpp/src/arrow/compute/api_scalar.cc @@ -197,6 +197,23 @@ struct EnumTraits } }; +template <> +struct EnumTraits + : BasicEnumTraits { + static std::string name() { return "RandomOptions::Initializer"; } + static std::string value_name(compute::RandomOptions::Initializer value) { + switch (value) { + case compute::RandomOptions::Initializer::SystemRandom: + return "SystemRandom"; + case compute::RandomOptions::Initializer::Seed: + return "Seed"; + } + return ""; + } +}; + } // namespace internal namespace compute { @@ -280,8 +297,10 @@ static auto kWeekOptionsType = GetFunctionOptionsType( DataMember("week_starts_monday", &WeekOptions::week_starts_monday), DataMember("count_from_zero", &WeekOptions::count_from_zero), DataMember("first_week_is_fully_in_year", &WeekOptions::first_week_is_fully_in_year)); -static auto kRandomOptionsType = - GetFunctionOptionsType(DataMember("seed", &RandomOptions::seed)); +static auto kRandomOptionsType = GetFunctionOptionsType( + DataMember("length", &RandomOptions::length), + DataMember("initializer", &RandomOptions::initializer), + DataMember("seed", &RandomOptions::seed)); } // namespace } // namespace internal @@ -469,12 +488,12 @@ WeekOptions::WeekOptions(bool week_starts_monday, bool count_from_zero, first_week_is_fully_in_year(first_week_is_fully_in_year) {} constexpr char WeekOptions::kTypeName[]; -NullaryOptions::NullaryOptions(int64_t length) - : FunctionOptions(internal::kRandomOptionsType), length(length) {} - -RandomOptions::RandomOptions(Initializer initializer, int64_t length, int64_t seed) - : NullaryOptions(length), initializer(initializer), seed(seed) {} -RandomOptions::RandomOptions() : RandomOptions(SystemRandom, -1, 0) {} +RandomOptions::RandomOptions(int64_t length, Initializer initializer, uint32_t seed) + : FunctionOptions(internal::kRandomOptionsType), + length(length), + initializer(initializer), + seed(seed) {} +RandomOptions::RandomOptions() : RandomOptions(0, SystemRandom, 0) {} constexpr char RandomOptions::kTypeName[]; namespace internal { diff --git a/cpp/src/arrow/compute/api_scalar.h b/cpp/src/arrow/compute/api_scalar.h index 3c9053ac1578..43f18e0d2d1d 100644 --- a/cpp/src/arrow/compute/api_scalar.h +++ b/cpp/src/arrow/compute/api_scalar.h @@ -420,35 +420,28 @@ struct ARROW_EXPORT Utf8NormalizeOptions : public FunctionOptions { Form form; }; -class ARROW_EXPORT NullaryOptions : public FunctionOptions { - public: - explicit NullaryOptions(int64_t length); - - /// The length of the array returned by the nullary function. Negative is invalid. - int64_t length; -}; - -class ARROW_EXPORT RandomOptions : public NullaryOptions { +class ARROW_EXPORT RandomOptions : public FunctionOptions { public: enum Initializer { SystemRandom, Seed }; static RandomOptions FromSystemRandom(int64_t length) { - return RandomOptions{SystemRandom, length, 0}; + return RandomOptions{length, SystemRandom, 0}; } - static RandomOptions FromSeed(int64_t length, int64_t seed) { - return RandomOptions{Seed, length, seed}; + static RandomOptions FromSeed(int64_t length, uint32_t seed) { + return RandomOptions{length, Seed, seed}; } - RandomOptions(Initializer initializer, int64_t length, int64_t seed); - // Default constructor creates an invalid options struct, but is required for Python + RandomOptions(int64_t length, Initializer initializer, uint32_t seed); RandomOptions(); constexpr static char const kTypeName[] = "RandomOptions"; static RandomOptions Defaults() { return RandomOptions(); } + /// The length of the array returned. Negative is invalid. + int64_t length; /// The type of initialization for random number generation - system or provided seed. Initializer initializer; /// The seed value used to initialize the random number generation. - int64_t seed; + uint32_t seed; }; /// @} diff --git a/cpp/src/arrow/compute/exec/expression.cc b/cpp/src/arrow/compute/exec/expression.cc index 51bd45388a96..4249179e1bf8 100644 --- a/cpp/src/arrow/compute/exec/expression.cc +++ b/cpp/src/arrow/compute/exec/expression.cc @@ -541,10 +541,6 @@ Result ExecuteScalarExpression(const Expression& expr, const ExecBatch& i auto kernel = call->kernel; auto descrs = GetDescriptors(arguments); auto options = call->options.get(); - if (arguments.size() == 0 && dynamic_cast(options)) { - auto nullary_options = static_cast(options); - nullary_options->length = input.length; - } RETURN_NOT_OK(executor->Init(&kernel_context, {kernel, descrs, options})); compute::detail::DatumAccumulator listener; diff --git a/cpp/src/arrow/compute/kernels/CMakeLists.txt b/cpp/src/arrow/compute/kernels/CMakeLists.txt index 65baa1d5fba9..93a02cdb1f1d 100644 --- a/cpp/src/arrow/compute/kernels/CMakeLists.txt +++ b/cpp/src/arrow/compute/kernels/CMakeLists.txt @@ -20,17 +20,17 @@ add_arrow_compute_test(scalar_test SOURCES - scalar_random_test.cc scalar_arithmetic_test.cc scalar_boolean_test.cc scalar_cast_test.cc scalar_compare_test.cc + scalar_if_else_test.cc scalar_nested_test.cc + scalar_random_test.cc scalar_set_lookup_test.cc scalar_string_test.cc scalar_temporal_test.cc scalar_validity_test.cc - scalar_if_else_test.cc test_util.cc) add_arrow_benchmark(scalar_arithmetic_benchmark PREFIX "arrow-compute") @@ -38,6 +38,7 @@ add_arrow_benchmark(scalar_boolean_benchmark PREFIX "arrow-compute") add_arrow_benchmark(scalar_cast_benchmark PREFIX "arrow-compute") add_arrow_benchmark(scalar_compare_benchmark PREFIX "arrow-compute") add_arrow_benchmark(scalar_if_else_benchmark PREFIX "arrow-compute") +add_arrow_benchmark(scalar_random_benchmark PREFIX "arrow-compute") add_arrow_benchmark(scalar_set_lookup_benchmark PREFIX "arrow-compute") add_arrow_benchmark(scalar_string_benchmark PREFIX "arrow-compute") diff --git a/cpp/src/arrow/compute/kernels/random.cc b/cpp/src/arrow/compute/kernels/scalar_random.cc similarity index 95% rename from cpp/src/arrow/compute/kernels/random.cc rename to cpp/src/arrow/compute/kernels/scalar_random.cc index 1b8a6978cd72..125789510346 100644 --- a/cpp/src/arrow/compute/kernels/random.cc +++ b/cpp/src/arrow/compute/kernels/scalar_random.cc @@ -28,12 +28,15 @@ namespace arrow { namespace compute { namespace internal { + namespace { // Generates a random floating point number in range [0, 1). double generate_uniform(random::pcg64_fast& rng) { // This equation is copied from numpy. It calculates `rng() / 2^64` and // the return value is strictly less than 1. + static_assert(random::pcg64_fast::min() == 0ULL, ""); + static_assert(random::pcg64_fast::max() == ~0ULL, ""); return (rng() >> 11) * (1.0 / 9007199254740992.0); } @@ -78,7 +81,7 @@ const FunctionDoc random_doc{ } // namespace -void RegisterNullaryRandom(FunctionRegistry* registry) { +void RegisterScalarRandom(FunctionRegistry* registry) { static auto random_options = RandomOptions::Defaults(); auto random_func = std::make_shared("random", Arity::Nullary(), diff --git a/cpp/src/arrow/compute/kernels/scalar_random_benchmark.cc b/cpp/src/arrow/compute/kernels/scalar_random_benchmark.cc new file mode 100644 index 000000000000..51dbd08a2d3e --- /dev/null +++ b/cpp/src/arrow/compute/kernels/scalar_random_benchmark.cc @@ -0,0 +1,56 @@ +// 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 "benchmark/benchmark.h" + +#include "arrow/compute/api_scalar.h" +#include "arrow/compute/kernels/test_util.h" +#include "arrow/testing/gtest_util.h" +#include "arrow/util/benchmark_util.h" + +namespace arrow { +namespace compute { + +static void RandomKernel(benchmark::State& state, bool is_seed) { + const int64_t length = state.range(0); + const auto options = is_seed ? RandomOptions::FromSeed(length, 42) + : RandomOptions::FromSystemRandom(length); + for (auto _ : state) { + ABORT_NOT_OK(CallFunction("random", {}, &options).status()); + } + state.SetItemsProcessed(state.iterations() * length); +} + +static void RandomKernelSystem(benchmark::State& state) { + RandomKernel(state, /*is_seed=*/false); +} + +static void RandomKernelSeed(benchmark::State& state) { + RandomKernel(state, /*is_seed=*/true); +} + +void SetArgs(benchmark::internal::Benchmark* bench) { + for (int64_t length : {1, 64, 1024, 65536}) { + bench->Arg(length); + } +} + +BENCHMARK(RandomKernelSystem)->Apply(SetArgs); +BENCHMARK(RandomKernelSeed)->Apply(SetArgs); + +} // namespace compute +} // namespace arrow diff --git a/cpp/src/arrow/compute/kernels/scalar_random_test.cc b/cpp/src/arrow/compute/kernels/scalar_random_test.cc index 43eaf67e850d..4eea1543b75b 100644 --- a/cpp/src/arrow/compute/kernels/scalar_random_test.cc +++ b/cpp/src/arrow/compute/kernels/scalar_random_test.cc @@ -17,37 +17,39 @@ #include -#include - #include "arrow/compute/api.h" +#include "arrow/compute/kernels/test_util.h" #include "arrow/testing/gtest_util.h" -#include "arrow/util/checked_cast.h" namespace arrow { namespace compute { + namespace { void TestRandomWithOptions(const RandomOptions& random_options) { - using arrow::internal::checked_cast; - double sum = 0; - double square_sum = 0; ASSERT_OK_AND_ASSIGN(Datum result, CallFunction("random", {}, &random_options)); - auto result_array = result.make_array(); + const auto result_array = result.make_array(); + ValidateOutput(*result_array); ASSERT_EQ(result_array->length(), random_options.length); - for (int i = 0; i < random_options.length; ++i) { - ASSERT_OK_AND_ASSIGN(auto result_scalar, result_array->GetScalar(i)); - const auto& double_scalar = checked_cast(*result_scalar); - ASSERT_GE(double_scalar.value, 0); - ASSERT_LT(double_scalar.value, 1); - sum += double_scalar.value; - square_sum += double_scalar.value * double_scalar.value; - } + ASSERT_EQ(result_array->null_count(), 0); + AssertTypeEqual(result_array->type(), float64()); - // verify E(X), E(X^2) is near theory - const double E_X = 0.5; - const double E_X2 = 1.0 / 12 + E_X * E_X; - ASSERT_NEAR(sum / random_options.length, E_X, std::abs(E_X) * 0.02); - ASSERT_NEAR(square_sum / random_options.length, E_X2, E_X2 * 0.02); + if (random_options.length > 0) { + // verify E(X), E(X^2) is near theory + double sum = 0, square_sum = 0; + const double* values = result_array->data()->GetValues(1); + for (int64_t i = 0; i < random_options.length; ++i) { + const double value = values[i]; + ASSERT_GE(value, 0); + ASSERT_LT(value, 1); + sum += value; + square_sum += value * value; + } + const double E_X = 0.5; + const double E_X2 = 1.0 / 12 + E_X * E_X; + ASSERT_NEAR(sum / random_options.length, E_X, E_X * 0.02); + ASSERT_NEAR(square_sum / random_options.length, E_X2, E_X2 * 0.02); + } } } // namespace @@ -72,5 +74,13 @@ TEST(TestRandom, SeedIsDeterministic) { AssertDatumsEqual(first_call, second_call); } +TEST(TestRandom, Length) { + auto random_options = RandomOptions::FromSystemRandom(/*length=*/0); + TestRandomWithOptions(random_options); + + random_options = RandomOptions::FromSystemRandom(/*length=*/-1); + ASSERT_RAISES(Invalid, CallFunction("random", {}, &random_options)); +} + } // namespace compute } // namespace arrow diff --git a/cpp/src/arrow/compute/registry.cc b/cpp/src/arrow/compute/registry.cc index e94c5b072184..600251c8ad3f 100644 --- a/cpp/src/arrow/compute/registry.cc +++ b/cpp/src/arrow/compute/registry.cc @@ -162,6 +162,7 @@ static std::unique_ptr CreateBuiltInRegistry() { RegisterScalarComparison(registry.get()); RegisterScalarIfElse(registry.get()); RegisterScalarNested(registry.get()); + RegisterScalarRandom(registry.get()); // Nullary RegisterScalarSetLookup(registry.get()); RegisterScalarStringAscii(registry.get()); RegisterScalarTemporalBinary(registry.get()); @@ -190,9 +191,6 @@ static std::unique_ptr CreateBuiltInRegistry() { RegisterAggregateOptions(registry.get()); - // Random generator function - RegisterNullaryRandom(registry.get()); - return registry; } diff --git a/cpp/src/arrow/compute/registry_internal.h b/cpp/src/arrow/compute/registry_internal.h index 853d2088f4bf..3a70ff9b3a7e 100644 --- a/cpp/src/arrow/compute/registry_internal.h +++ b/cpp/src/arrow/compute/registry_internal.h @@ -31,6 +31,7 @@ void RegisterScalarCast(FunctionRegistry* registry); void RegisterScalarComparison(FunctionRegistry* registry); void RegisterScalarIfElse(FunctionRegistry* registry); void RegisterScalarNested(FunctionRegistry* registry); +void RegisterScalarRandom(FunctionRegistry* registry); // Nullary void RegisterScalarSetLookup(FunctionRegistry* registry); void RegisterScalarStringAscii(FunctionRegistry* registry); void RegisterScalarTemporalBinary(FunctionRegistry* registry); @@ -59,9 +60,6 @@ void RegisterScalarAggregateVariance(FunctionRegistry* registry); void RegisterAggregateOptions(FunctionRegistry* registry); -// Uniform random generator -void RegisterNullaryRandom(FunctionRegistry* registry); - } // namespace internal } // namespace compute } // namespace arrow From 49f3fedf6b4a3ca2289e580af9015cc98c21c5e5 Mon Sep 17 00:00:00 2001 From: Yibo Cai Date: Mon, 20 Dec 2021 10:15:03 +0000 Subject: [PATCH 10/15] fix conflicted symbol names in unity build --- .../compute/kernels/scalar_compare_test.cc | 13 +++---- .../compute/kernels/scalar_if_else_test.cc | 10 +++--- .../compute/kernels/scalar_nested_test.cc | 35 ++++++++++--------- 3 files changed, 30 insertions(+), 28 deletions(-) diff --git a/cpp/src/arrow/compute/kernels/scalar_compare_test.cc b/cpp/src/arrow/compute/kernels/scalar_compare_test.cc index 64abb9fb6907..0fa97e17303c 100644 --- a/cpp/src/arrow/compute/kernels/scalar_compare_test.cc +++ b/cpp/src/arrow/compute/kernels/scalar_compare_test.cc @@ -1211,18 +1211,19 @@ class TestVarArgsCompareParametricTemporal : public TestVarArgsCompare { Datum array(const std::string& value) { return ArrayFromJSON(type_singleton(), value); } }; -using NumericBasedTypes = +using CompareNumericBasedTypes = ::testing::Types; -using ParametricTemporalTypes = ::testing::Types; -using FixedSizeBinaryTypes = ::testing::Types; +using CompareParametricTemporalTypes = + ::testing::Types; +using CompareFixedSizeBinaryTypes = ::testing::Types; -TYPED_TEST_SUITE(TestVarArgsCompareNumeric, NumericBasedTypes); +TYPED_TEST_SUITE(TestVarArgsCompareNumeric, CompareNumericBasedTypes); TYPED_TEST_SUITE(TestVarArgsCompareDecimal, DecimalArrowTypes); TYPED_TEST_SUITE(TestVarArgsCompareFloating, RealArrowTypes); -TYPED_TEST_SUITE(TestVarArgsCompareParametricTemporal, ParametricTemporalTypes); +TYPED_TEST_SUITE(TestVarArgsCompareParametricTemporal, CompareParametricTemporalTypes); TYPED_TEST_SUITE(TestVarArgsCompareBinary, BaseBinaryArrowTypes); -TYPED_TEST_SUITE(TestVarArgsCompareFixedSizeBinary, FixedSizeBinaryTypes); +TYPED_TEST_SUITE(TestVarArgsCompareFixedSizeBinary, CompareFixedSizeBinaryTypes); TYPED_TEST(TestVarArgsCompareNumeric, MinElementWise) { this->AssertNullScalar(MinElementWise, {}); diff --git a/cpp/src/arrow/compute/kernels/scalar_if_else_test.cc b/cpp/src/arrow/compute/kernels/scalar_if_else_test.cc index 6f219afa3c1e..711b318feb74 100644 --- a/cpp/src/arrow/compute/kernels/scalar_if_else_test.cc +++ b/cpp/src/arrow/compute/kernels/scalar_if_else_test.cc @@ -61,12 +61,12 @@ class TestIfElseKernel : public ::testing::Test {}; template class TestIfElsePrimitive : public ::testing::Test {}; -using NumericBasedTypes = +using IfElseNumericBasedTypes = ::testing::Types; -TYPED_TEST_SUITE(TestIfElsePrimitive, NumericBasedTypes); +TYPED_TEST_SUITE(TestIfElsePrimitive, IfElseNumericBasedTypes); TYPED_TEST(TestIfElsePrimitive, IfElseFixedSizeRand) { using ArrayType = typename TypeTraits::ArrayType; @@ -960,7 +960,7 @@ TYPED_TEST(TestIfElseDict, DifferentDictionaries) { template class TestCaseWhenNumeric : public ::testing::Test {}; -TYPED_TEST_SUITE(TestCaseWhenNumeric, NumericBasedTypes); +TYPED_TEST_SUITE(TestCaseWhenNumeric, IfElseNumericBasedTypes); Datum MakeStruct(const std::vector& conds) { EXPECT_OK_AND_ASSIGN(auto result, CallFunction("make_struct", conds)); @@ -2176,7 +2176,7 @@ class TestCoalesceBinary : public ::testing::Test {}; template class TestCoalesceList : public ::testing::Test {}; -TYPED_TEST_SUITE(TestCoalesceNumeric, NumericBasedTypes); +TYPED_TEST_SUITE(TestCoalesceNumeric, IfElseNumericBasedTypes); TYPED_TEST_SUITE(TestCoalesceBinary, BaseBinaryArrowTypes); TYPED_TEST_SUITE(TestCoalesceList, ListArrowTypes); @@ -2929,7 +2929,7 @@ class TestChooseNumeric : public ::testing::Test {}; template class TestChooseBinary : public ::testing::Test {}; -TYPED_TEST_SUITE(TestChooseNumeric, NumericBasedTypes); +TYPED_TEST_SUITE(TestChooseNumeric, IfElseNumericBasedTypes); TYPED_TEST_SUITE(TestChooseBinary, BaseBinaryArrowTypes); TYPED_TEST(TestChooseNumeric, FixedSize) { diff --git a/cpp/src/arrow/compute/kernels/scalar_nested_test.cc b/cpp/src/arrow/compute/kernels/scalar_nested_test.cc index 1f78fd6ce382..4640e1e22160 100644 --- a/cpp/src/arrow/compute/kernels/scalar_nested_test.cc +++ b/cpp/src/arrow/compute/kernels/scalar_nested_test.cc @@ -236,25 +236,25 @@ struct { MakeStructOptions opts{field_names, options...}; return CallFunction("make_struct", args, &opts); } -} MakeStruct; +} MakeStructor; TEST(MakeStruct, Scalar) { auto i32 = MakeScalar(1); auto f64 = MakeScalar(2.5); auto str = MakeScalar("yo"); - EXPECT_THAT(MakeStruct({i32, f64, str}, {"i", "f", "s"}), + EXPECT_THAT(MakeStructor({i32, f64, str}, {"i", "f", "s"}), ResultWith(Datum(*StructScalar::Make({i32, f64, str}, {"i", "f", "s"})))); // Names default to field_index - EXPECT_THAT(MakeStruct({i32, f64, str}), + EXPECT_THAT(MakeStructor({i32, f64, str}), ResultWith(Datum(*StructScalar::Make({i32, f64, str}, {"0", "1", "2"})))); // No field names or input values is fine - EXPECT_THAT(MakeStruct({}), ResultWith(Datum(*StructScalar::Make({}, {})))); + EXPECT_THAT(MakeStructor({}), ResultWith(Datum(*StructScalar::Make({}, {})))); // Three field names but one input value - EXPECT_THAT(MakeStruct({str}, {"i", "f", "s"}), Raises(StatusCode::Invalid)); + EXPECT_THAT(MakeStructor({str}, {"i", "f", "s"}), Raises(StatusCode::Invalid)); } TEST(MakeStruct, Array) { @@ -263,15 +263,16 @@ TEST(MakeStruct, Array) { auto i32 = ArrayFromJSON(int32(), "[42, 13, 7]"); auto str = ArrayFromJSON(utf8(), R"(["aa", "aa", "aa"])"); - EXPECT_THAT(MakeStruct({i32, str}, {"i", "s"}), + EXPECT_THAT(MakeStructor({i32, str}, {"i", "s"}), ResultWith(Datum(*StructArray::Make({i32, str}, field_names)))); // Scalars are broadcast to the length of the arrays - EXPECT_THAT(MakeStruct({i32, MakeScalar("aa")}, {"i", "s"}), + EXPECT_THAT(MakeStructor({i32, MakeScalar("aa")}, {"i", "s"}), ResultWith(Datum(*StructArray::Make({i32, str}, field_names)))); // Array length mismatch - EXPECT_THAT(MakeStruct({i32->Slice(1), str}, field_names), Raises(StatusCode::Invalid)); + EXPECT_THAT(MakeStructor({i32->Slice(1), str}, field_names), + Raises(StatusCode::Invalid)); } TEST(MakeStruct, NullableMetadataPassedThru) { @@ -284,7 +285,7 @@ TEST(MakeStruct, NullableMetadataPassedThru) { key_value_metadata({"a", "b"}, {"ALPHA", "BRAVO"}), nullptr}; ASSERT_OK_AND_ASSIGN(auto proj, - MakeStruct({i32, str}, field_names, nullability, metadata)); + MakeStructor({i32, str}, field_names, nullability, metadata)); AssertTypeEqual(*proj.type(), StructType({ field("i", int32(), /*nullable=*/true, metadata[0]), @@ -292,8 +293,8 @@ TEST(MakeStruct, NullableMetadataPassedThru) { })); // error: projecting an array containing nulls with nullable=false - EXPECT_THAT(MakeStruct({i32, ArrayFromJSON(utf8(), R"(["aa", null, "aa"])")}, - field_names, nullability, metadata), + EXPECT_THAT(MakeStructor({i32, ArrayFromJSON(utf8(), R"(["aa", null, "aa"])")}, + field_names, nullability, metadata), Raises(StatusCode::Invalid)); } @@ -317,13 +318,13 @@ TEST(MakeStruct, ChunkedArray) { ASSERT_OK_AND_ASSIGN(Datum expected, ChunkedArray::Make({expected_0, expected_1, expected_2})); - ASSERT_OK_AND_EQ(expected, MakeStruct({i32, str}, field_names)); + ASSERT_OK_AND_EQ(expected, MakeStructor({i32, str}, field_names)); // Scalars are broadcast to the length of the arrays - ASSERT_OK_AND_EQ(expected, MakeStruct({i32, MakeScalar("aa")}, field_names)); + ASSERT_OK_AND_EQ(expected, MakeStructor({i32, MakeScalar("aa")}, field_names)); // Array length mismatch - ASSERT_RAISES(Invalid, MakeStruct({i32->Slice(1), str}, field_names)); + ASSERT_RAISES(Invalid, MakeStructor({i32->Slice(1), str}, field_names)); } TEST(MakeStruct, ChunkedArrayDifferentChunking) { @@ -354,13 +355,13 @@ TEST(MakeStruct, ChunkedArrayDifferentChunking) { ASSERT_OK_AND_ASSIGN(Datum expected, ChunkedArray::Make(expected_chunks)); - ASSERT_OK_AND_EQ(expected, MakeStruct({i32, str}, field_names)); + ASSERT_OK_AND_EQ(expected, MakeStructor({i32, str}, field_names)); // Scalars are broadcast to the length of the arrays - ASSERT_OK_AND_EQ(expected, MakeStruct({i32, MakeScalar("aa")}, field_names)); + ASSERT_OK_AND_EQ(expected, MakeStructor({i32, MakeScalar("aa")}, field_names)); // Array length mismatch - ASSERT_RAISES(Invalid, MakeStruct({i32->Slice(1), str}, field_names)); + ASSERT_RAISES(Invalid, MakeStructor({i32->Slice(1), str}, field_names)); } } // namespace compute From ff2929b452a9f5af97c6868ea3133c9cdd0decd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alex=20=C5=9Euhan?= Date: Tue, 21 Dec 2021 18:40:01 -0800 Subject: [PATCH 11/15] ARROW-12404: Address minor comments --- cpp/src/arrow/compute/api_scalar.cc | 2 +- cpp/src/arrow/compute/kernels/scalar_random.cc | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/cpp/src/arrow/compute/api_scalar.cc b/cpp/src/arrow/compute/api_scalar.cc index 1d1906bc968e..021499af2289 100644 --- a/cpp/src/arrow/compute/api_scalar.cc +++ b/cpp/src/arrow/compute/api_scalar.cc @@ -488,7 +488,7 @@ WeekOptions::WeekOptions(bool week_starts_monday, bool count_from_zero, first_week_is_fully_in_year(first_week_is_fully_in_year) {} constexpr char WeekOptions::kTypeName[]; -RandomOptions::RandomOptions(int64_t length, Initializer initializer, uint32_t seed) +RandomOptions::RandomOptions(int64_t length, Initializer initializer, uint64_t seed) : FunctionOptions(internal::kRandomOptionsType), length(length), initializer(initializer), diff --git a/cpp/src/arrow/compute/kernels/scalar_random.cc b/cpp/src/arrow/compute/kernels/scalar_random.cc index 125789510346..f83fd7fbcfad 100644 --- a/cpp/src/arrow/compute/kernels/scalar_random.cc +++ b/cpp/src/arrow/compute/kernels/scalar_random.cc @@ -32,12 +32,12 @@ namespace internal { namespace { // Generates a random floating point number in range [0, 1). -double generate_uniform(random::pcg64_fast& rng) { +double generate_uniform(random::pcg64_fast* rng) { // This equation is copied from numpy. It calculates `rng() / 2^64` and // the return value is strictly less than 1. static_assert(random::pcg64_fast::min() == 0ULL, ""); static_assert(random::pcg64_fast::max() == ~0ULL, ""); - return (rng() >> 11) * (1.0 / 9007199254740992.0); + return ((*rng)() >> 11) * (1.0 / 9007199254740992.0); } using RandomState = OptionsWrapper; @@ -66,14 +66,14 @@ Status ExecRandom(KernelContext* ctx, const ExecBatch& batch, Datum* out) { gen.seed(seed_gen()); } for (int64_t i = 0; i < options.length; ++i) { - out_buffer[i] = generate_uniform(gen); + out_buffer[i] = generate_uniform(&gen); } *out = std::move(out_data); return Status::OK(); } const FunctionDoc random_doc{ - "Generates a number in range [0, 1)", + "Generate numbers in the range [0, 1)", ("Generated values are uniformly-distributed, double-precision in range [0, 1).\n" "Length of generated data, algorithm and seed can be changed via RandomOptions."), {}, From 763aa3c1f4ec596dbe9c062e89267f12a5d9bb1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alex=20=C5=9Euhan?= Date: Tue, 21 Dec 2021 19:15:30 -0800 Subject: [PATCH 12/15] ARROW-12404: Add tests for system initialized seed --- cpp/src/arrow/compute/api_scalar.h | 6 ++-- .../compute/kernels/scalar_random_test.cc | 32 +++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/cpp/src/arrow/compute/api_scalar.h b/cpp/src/arrow/compute/api_scalar.h index 43f18e0d2d1d..3d922157c9c4 100644 --- a/cpp/src/arrow/compute/api_scalar.h +++ b/cpp/src/arrow/compute/api_scalar.h @@ -427,11 +427,11 @@ class ARROW_EXPORT RandomOptions : public FunctionOptions { static RandomOptions FromSystemRandom(int64_t length) { return RandomOptions{length, SystemRandom, 0}; } - static RandomOptions FromSeed(int64_t length, uint32_t seed) { + static RandomOptions FromSeed(int64_t length, uint64_t seed) { return RandomOptions{length, Seed, seed}; } - RandomOptions(int64_t length, Initializer initializer, uint32_t seed); + RandomOptions(int64_t length, Initializer initializer, uint64_t seed); RandomOptions(); constexpr static char const kTypeName[] = "RandomOptions"; static RandomOptions Defaults() { return RandomOptions(); } @@ -441,7 +441,7 @@ class ARROW_EXPORT RandomOptions : public FunctionOptions { /// The type of initialization for random number generation - system or provided seed. Initializer initializer; /// The seed value used to initialize the random number generation. - uint32_t seed; + uint64_t seed; }; /// @} diff --git a/cpp/src/arrow/compute/kernels/scalar_random_test.cc b/cpp/src/arrow/compute/kernels/scalar_random_test.cc index 4eea1543b75b..72c11db36eb1 100644 --- a/cpp/src/arrow/compute/kernels/scalar_random_test.cc +++ b/cpp/src/arrow/compute/kernels/scalar_random_test.cc @@ -21,6 +21,8 @@ #include "arrow/compute/kernels/test_util.h" #include "arrow/testing/gtest_util.h" +#include + namespace arrow { namespace compute { @@ -74,6 +76,36 @@ TEST(TestRandom, SeedIsDeterministic) { AssertDatumsEqual(first_call, second_call); } +TEST(TestRandom, SystemRandomDifferentResultsSingleThreaded) { + const int kCount = 100; + auto random_options = RandomOptions::FromSystemRandom(/*length=*/kCount); + ASSERT_OK_AND_ASSIGN(Datum first_datum, CallFunction("random", {}, &random_options)); + ASSERT_OK_AND_ASSIGN(Datum second_datum, CallFunction("random", {}, &random_options)); + ASSERT_FALSE(first_datum.Equals(second_datum)); +} + +TEST(TestRandom, SystemRandomDifferentResultsMultiThreaded) { + const int kCount = 100000; + const int kThreadCount = 8; + auto random_options = RandomOptions::FromSystemRandom(/*length=*/kCount); + std::vector> futures; + for (int i = 0; i < kThreadCount; ++i) { + futures.push_back(std::async(std::launch::async, [&random_options] { + auto maybe_result = CallFunction("random", {}, &random_options); + return maybe_result.ValueOrDie(); + })); + } + std::vector call_results; + for (int i = 0; i < kThreadCount; ++i) { + call_results.push_back(futures[i].get()); + } + for (int i = 0; i < kThreadCount - 1; ++i) { + for (int j = i + 1; j < kThreadCount; ++j) { + ASSERT_FALSE(call_results[i].Equals(call_results[j])); + } + } +} + TEST(TestRandom, Length) { auto random_options = RandomOptions::FromSystemRandom(/*length=*/0); TestRandomWithOptions(random_options); From 7cb703121d6715e781f92846a52a79c8909d7156 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alex=20=C5=9Euhan?= Date: Wed, 22 Dec 2021 09:11:19 -0800 Subject: [PATCH 13/15] ARROW-12404: Use seed_seq_from to initialize seed generator --- cpp/src/arrow/compute/kernels/scalar_random.cc | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/cpp/src/arrow/compute/kernels/scalar_random.cc b/cpp/src/arrow/compute/kernels/scalar_random.cc index f83fd7fbcfad..f4f026fa16c3 100644 --- a/cpp/src/arrow/compute/kernels/scalar_random.cc +++ b/cpp/src/arrow/compute/kernels/scalar_random.cc @@ -42,8 +42,14 @@ double generate_uniform(random::pcg64_fast* rng) { using RandomState = OptionsWrapper; +random::pcg64_fast MakeSeedGenerator() { + arrow_vendored::pcg_extras::seed_seq_from seed_source; + random::pcg64_fast seed_gen(seed_source); + return seed_gen; +} + Status ExecRandom(KernelContext* ctx, const ExecBatch& batch, Datum* out) { - static random::pcg64_fast seed_gen((std::random_device{})()); + static random::pcg64_fast seed_gen = MakeSeedGenerator(); static std::mutex seed_gen_mutex; random::pcg64_fast gen; From b06ebd0399becb67137c01ed90e1d835bfe77a67 Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Thu, 30 Dec 2021 11:49:50 +0100 Subject: [PATCH 14/15] Use our own thread pool facilities --- .../compute/kernels/scalar_random_test.cc | 29 +++++++++++-------- 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/cpp/src/arrow/compute/kernels/scalar_random_test.cc b/cpp/src/arrow/compute/kernels/scalar_random_test.cc index 72c11db36eb1..b4003fcbcbfb 100644 --- a/cpp/src/arrow/compute/kernels/scalar_random_test.cc +++ b/cpp/src/arrow/compute/kernels/scalar_random_test.cc @@ -20,10 +20,12 @@ #include "arrow/compute/api.h" #include "arrow/compute/kernels/test_util.h" #include "arrow/testing/gtest_util.h" - -#include +#include "arrow/util/thread_pool.h" namespace arrow { + +using internal::ThreadPool; + namespace compute { namespace { @@ -85,19 +87,22 @@ TEST(TestRandom, SystemRandomDifferentResultsSingleThreaded) { } TEST(TestRandom, SystemRandomDifferentResultsMultiThreaded) { - const int kCount = 100000; + const int kCount = 100; const int kThreadCount = 8; + const int kCallCount = 200; + + ASSERT_OK_AND_ASSIGN(auto pool, ThreadPool::Make(kThreadCount)); + auto random_options = RandomOptions::FromSystemRandom(/*length=*/kCount); - std::vector> futures; - for (int i = 0; i < kThreadCount; ++i) { - futures.push_back(std::async(std::launch::async, [&random_options] { - auto maybe_result = CallFunction("random", {}, &random_options); - return maybe_result.ValueOrDie(); - })); + std::vector> futures; + + for (int i = 0; i < kCallCount; ++i) { + futures.push_back(DeferNotOk( + pool->Submit([&]() { return CallFunction("random", {}, &random_options); }))); } - std::vector call_results; - for (int i = 0; i < kThreadCount; ++i) { - call_results.push_back(futures[i].get()); + std::vector call_results(kCallCount); + for (int i = 0; i < kCallCount; ++i) { + ASSERT_OK_AND_ASSIGN(call_results[i], futures[i].result()); } for (int i = 0; i < kThreadCount - 1; ++i) { for (int j = i + 1; j < kThreadCount; ++j) { From 4af29786c4ec88c444557f78dda0b9908b53b452 Mon Sep 17 00:00:00 2001 From: Antoine Pitrou Date: Thu, 30 Dec 2021 11:50:03 +0100 Subject: [PATCH 15/15] Standardize compute docs around "Float64" --- docs/source/cpp/compute.rst | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/source/cpp/compute.rst b/docs/source/cpp/compute.rst index 6e3944ab11fd..e88bd4a7ec9b 100644 --- a/docs/source/cpp/compute.rst +++ b/docs/source/cpp/compute.rst @@ -1388,7 +1388,7 @@ For timestamps inputs with non-empty timezone, localized timestamp components wi +--------------------+------------+-------------------+---------------+----------------------------+-------+ | second | Unary | Timestamp, Time | Int64 | | | +--------------------+------------+-------------------+---------------+----------------------------+-------+ -| subsecond | Unary | Timestamp, Time | Double | | | +| subsecond | Unary | Timestamp, Time | Float64 | | | +--------------------+------------+-------------------+---------------+----------------------------+-------+ | us_week | Unary | Temporal | Int64 | | \(4) | +--------------------+------------+-------------------+---------------+----------------------------+-------+ @@ -1500,9 +1500,10 @@ random generator. +--------------------+------------+---------------+-------------------------+ | Function name | Arity | Output type | Options class | +====================+============+===============+=========================+ -| random | Nullary | Double | :struct:`RandomOptions` | +| random | Nullary | Float64 | :struct:`RandomOptions` | +--------------------+------------+---------------+-------------------------+ + Array-wise ("vector") functions -------------------------------