Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cpp/src/arrow/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -420,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
Expand Down
30 changes: 30 additions & 0 deletions cpp/src/arrow/compute/api_scalar.cc
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,23 @@ struct EnumTraits<compute::Utf8NormalizeOptions::Form>
}
};

template <>
struct EnumTraits<compute::RandomOptions::Initializer>
: BasicEnumTraits<compute::RandomOptions::Initializer,
compute::RandomOptions::Initializer::SystemRandom,
compute::RandomOptions::Initializer::Seed> {
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 "<INVALID>";
}
};

} // namespace internal

namespace compute {
Expand Down Expand Up @@ -280,6 +297,10 @@ static auto kWeekOptionsType = GetFunctionOptionsType<WeekOptions>(
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<RandomOptions>(
DataMember("length", &RandomOptions::length),
DataMember("initializer", &RandomOptions::initializer),
DataMember("seed", &RandomOptions::seed));
} // namespace
} // namespace internal

Expand Down Expand Up @@ -467,6 +488,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(int64_t length, Initializer initializer, uint64_t seed)
: FunctionOptions(internal::kRandomOptionsType),
length(length),
initializer(initializer),
seed(seed) {}
RandomOptions::RandomOptions() : RandomOptions(0, SystemRandom, 0) {}
constexpr char RandomOptions::kTypeName[];

namespace internal {
void RegisterScalarOptions(FunctionRegistry* registry) {
DCHECK_OK(registry->AddFunctionOptionsType(kArithmeticOptionsType));
Expand All @@ -493,6 +522,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

Expand Down
24 changes: 24 additions & 0 deletions cpp/src/arrow/compute/api_scalar.h
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,30 @@ 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{length, SystemRandom, 0};
}
static RandomOptions FromSeed(int64_t length, uint64_t seed) {
return RandomOptions{length, Seed, seed};
}

RandomOptions(int64_t length, Initializer initializer, uint64_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.
uint64_t seed;
};

/// @}

/// \brief Get the absolute value of a value.
Expand Down
4 changes: 3 additions & 1 deletion cpp/src/arrow/compute/kernels/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,21 @@ add_arrow_compute_test(scalar_test
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")
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")

Expand Down
13 changes: 7 additions & 6 deletions cpp/src/arrow/compute/kernels/scalar_compare_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1211,18 +1211,19 @@ class TestVarArgsCompareParametricTemporal : public TestVarArgsCompare<T> {
Datum array(const std::string& value) { return ArrayFromJSON(type_singleton(), value); }
};

using NumericBasedTypes =
using CompareNumericBasedTypes =
::testing::Types<UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int8Type, Int16Type,
Int32Type, Int64Type, FloatType, DoubleType, Date32Type, Date64Type>;
using ParametricTemporalTypes = ::testing::Types<TimestampType, Time32Type, Time64Type>;
using FixedSizeBinaryTypes = ::testing::Types<FixedSizeBinaryType>;
using CompareParametricTemporalTypes =
::testing::Types<TimestampType, Time32Type, Time64Type>;
using CompareFixedSizeBinaryTypes = ::testing::Types<FixedSizeBinaryType>;

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, {});
Expand Down
10 changes: 5 additions & 5 deletions cpp/src/arrow/compute/kernels/scalar_if_else_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,12 @@ class TestIfElseKernel : public ::testing::Test {};
template <typename Type>
class TestIfElsePrimitive : public ::testing::Test {};

using NumericBasedTypes =
using IfElseNumericBasedTypes =
::testing::Types<UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int8Type, Int16Type,
Int32Type, Int64Type, FloatType, DoubleType, Date32Type, Date64Type,
Time32Type, Time64Type, TimestampType, MonthIntervalType>;

TYPED_TEST_SUITE(TestIfElsePrimitive, NumericBasedTypes);
TYPED_TEST_SUITE(TestIfElsePrimitive, IfElseNumericBasedTypes);

TYPED_TEST(TestIfElsePrimitive, IfElseFixedSizeRand) {
using ArrayType = typename TypeTraits<TypeParam>::ArrayType;
Expand Down Expand Up @@ -960,7 +960,7 @@ TYPED_TEST(TestIfElseDict, DifferentDictionaries) {
template <typename Type>
class TestCaseWhenNumeric : public ::testing::Test {};

TYPED_TEST_SUITE(TestCaseWhenNumeric, NumericBasedTypes);
TYPED_TEST_SUITE(TestCaseWhenNumeric, IfElseNumericBasedTypes);

Datum MakeStruct(const std::vector<Datum>& conds) {
EXPECT_OK_AND_ASSIGN(auto result, CallFunction("make_struct", conds));
Expand Down Expand Up @@ -2176,7 +2176,7 @@ class TestCoalesceBinary : public ::testing::Test {};
template <typename Type>
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);

Expand Down Expand Up @@ -2929,7 +2929,7 @@ class TestChooseNumeric : public ::testing::Test {};
template <typename Type>
class TestChooseBinary : public ::testing::Test {};

TYPED_TEST_SUITE(TestChooseNumeric, NumericBasedTypes);
TYPED_TEST_SUITE(TestChooseNumeric, IfElseNumericBasedTypes);
TYPED_TEST_SUITE(TestChooseBinary, BaseBinaryArrowTypes);

TYPED_TEST(TestChooseNumeric, FixedSize) {
Expand Down
35 changes: 18 additions & 17 deletions cpp/src/arrow/compute/kernels/scalar_nested_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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) {
Expand All @@ -284,16 +285,16 @@ 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]),
field("s", utf8(), /*nullable=*/false, nullptr),
}));

// 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));
}

Expand All @@ -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) {
Expand Down Expand Up @@ -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
Expand Down
105 changes: 105 additions & 0 deletions cpp/src/arrow/compute/kernels/scalar_random.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// 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 <memory>
#include <mutex>
#include <random>

#include "arrow/compute/api_scalar.h"
#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_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);
}

using RandomState = OptionsWrapper<RandomOptions>;

random::pcg64_fast MakeSeedGenerator() {
arrow_vendored::pcg_extras::seed_seq_from<std::random_device> 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 = MakeSeedGenerator();
static std::mutex seed_gen_mutex;

random::pcg64_fast gen;
const RandomOptions& options = RandomState::Get(ctx);
if (options.length < 0) {
return Status::Invalid("Negative number of elements");
}

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<double>(1);

if (options.initializer == RandomOptions::Seed) {
gen.seed(options.seed);
} else {
std::lock_guard<std::mutex> seed_gen_lock(seed_gen_mutex);
gen.seed(seed_gen());
}
for (int64_t i = 0; i < options.length; ++i) {
out_buffer[i] = generate_uniform(&gen);
}
*out = std::move(out_data);
return Status::OK();
}

const FunctionDoc random_doc{
"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."),
{},
"RandomOptions"};

} // namespace

void RegisterScalarRandom(FunctionRegistry* registry) {
static auto random_options = RandomOptions::Defaults();

auto random_func = std::make_shared<ScalarFunction>("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)));
}

} // namespace internal
} // namespace compute
} // namespace arrow
Loading