repo_id
stringlengths
21
96
file_path
stringlengths
31
155
content
stringlengths
1
92.9M
__index_level_0__
int64
0
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/scalar/factories_test.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/scalar/scalar_factories.hpp> #include <cudf/types.hpp> #include <cudf/utilities/default_stream.hpp> #include <cudf/utilities/type_dispatcher.hpp> #include <rmm/cuda_stream_view.hpp> class ScalarFactoryTest : public cudf::test::BaseFixture {}; template <typename T> struct NumericScalarFactory : public ScalarFactoryTest {}; TYPED_TEST_SUITE(NumericScalarFactory, cudf::test::NumericTypes); TYPED_TEST(NumericScalarFactory, FactoryDefault) { std::unique_ptr<cudf::scalar> s = cudf::make_numeric_scalar(cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(s->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_FALSE(s->is_valid()); } TYPED_TEST(NumericScalarFactory, TypeCast) { std::unique_ptr<cudf::scalar> s = cudf::make_numeric_scalar(cudf::data_type{cudf::type_to_id<TypeParam>()}); auto numeric_s = static_cast<cudf::scalar_type_t<TypeParam>*>(s.get()); TypeParam value(37); numeric_s->set_value(value); EXPECT_EQ(numeric_s->value(), value); EXPECT_TRUE(numeric_s->is_valid()); EXPECT_TRUE(s->is_valid()); } template <typename T> struct TimestampScalarFactory : public ScalarFactoryTest {}; TYPED_TEST_SUITE(TimestampScalarFactory, cudf::test::TimestampTypes); TYPED_TEST(TimestampScalarFactory, FactoryDefault) { std::unique_ptr<cudf::scalar> s = cudf::make_timestamp_scalar(cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(s->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_FALSE(s->is_valid()); } TYPED_TEST(TimestampScalarFactory, TypeCast) { std::unique_ptr<cudf::scalar> s = cudf::make_timestamp_scalar(cudf::data_type{cudf::type_to_id<TypeParam>()}); auto numeric_s = static_cast<cudf::scalar_type_t<TypeParam>*>(s.get()); TypeParam value(typename TypeParam::duration{37}); numeric_s->set_value(value); EXPECT_EQ(numeric_s->value(), value); EXPECT_TRUE(numeric_s->is_valid()); EXPECT_TRUE(s->is_valid()); } template <typename T> struct DefaultScalarFactory : public ScalarFactoryTest {}; using MixedTypes = cudf::test::Concat<cudf::test::AllTypes, cudf::test::StringTypes>; TYPED_TEST_SUITE(DefaultScalarFactory, MixedTypes); TYPED_TEST(DefaultScalarFactory, FactoryDefault) { std::unique_ptr<cudf::scalar> s = cudf::make_default_constructed_scalar(cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(s->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_FALSE(s->is_valid()); } TYPED_TEST(DefaultScalarFactory, TypeCast) { std::unique_ptr<cudf::scalar> s = cudf::make_default_constructed_scalar(cudf::data_type{cudf::type_to_id<TypeParam>()}); auto numeric_s = static_cast<cudf::scalar_type_t<TypeParam>*>(s.get()); EXPECT_NO_THROW((void)numeric_s->value()); EXPECT_FALSE(numeric_s->is_valid()); EXPECT_FALSE(s->is_valid()); } template <typename T> struct FixedWidthScalarFactory : public ScalarFactoryTest {}; TYPED_TEST_SUITE(FixedWidthScalarFactory, cudf::test::FixedWidthTypesWithoutFixedPoint); TYPED_TEST(FixedWidthScalarFactory, ValueProvided) { TypeParam value = cudf::test::make_type_param_scalar<TypeParam>(54); std::unique_ptr<cudf::scalar> s = cudf::make_fixed_width_scalar<TypeParam>(value); auto numeric_s = static_cast<cudf::scalar_type_t<TypeParam>*>(s.get()); EXPECT_EQ(s->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(numeric_s->value(), value); EXPECT_TRUE(numeric_s->is_valid()); EXPECT_TRUE(s->is_valid()); } template <typename T> struct FixedPointScalarFactory : public ScalarFactoryTest {}; TYPED_TEST_SUITE(FixedPointScalarFactory, cudf::test::FixedPointTypes); TYPED_TEST(FixedPointScalarFactory, ValueProvided) { using namespace numeric; using decimalXX = TypeParam; auto const rep_value = static_cast<typename decimalXX::rep>(123); auto const s = cudf::make_fixed_point_scalar<decimalXX>(123, scale_type{-2}); auto const fp_s = static_cast<cudf::scalar_type_t<decimalXX>*>(s.get()); auto const expected_dtype = cudf::data_type{cudf::type_to_id<decimalXX>(), -2}; EXPECT_EQ(s->type(), expected_dtype); EXPECT_EQ(fp_s->value(), rep_value); EXPECT_TRUE(fp_s->is_valid()); EXPECT_TRUE(s->is_valid()); } struct StructScalarFactory : public ScalarFactoryTest {}; TEST_F(StructScalarFactory, Basic) { cudf::test::fixed_width_column_wrapper<int> col0{1}; cudf::test::strings_column_wrapper col1{"abc"}; cudf::test::lists_column_wrapper<int> col2{{1, 2, 3}}; cudf::test::structs_column_wrapper struct_col({col0, col1, col2}); cudf::column_view cv = static_cast<cudf::column_view>(struct_col); std::vector<cudf::column_view> children(cv.child_begin(), cv.child_end()); // table_view constructor { auto sc = cudf::make_struct_scalar(cudf::table_view{children}); auto s = static_cast<cudf::scalar_type_t<cudf::struct_view>*>(sc.get()); EXPECT_TRUE(s->is_valid()); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(cudf::table_view{children}, s->view()); } // host_span constructor { auto sc = cudf::make_struct_scalar(cudf::host_span<cudf::column_view const>{children}); auto s = static_cast<cudf::scalar_type_t<cudf::struct_view>*>(sc.get()); EXPECT_TRUE(s->is_valid()); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(cudf::table_view{children}, s->view()); } } CUDF_TEST_PROGRAM_MAIN()
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/scalar/scalar_test.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/scalar/scalar.hpp> template <typename T> struct TypedScalarTest : public cudf::test::BaseFixture {}; template <typename T> struct TypedScalarTestWithoutFixedPoint : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(TypedScalarTest, cudf::test::FixedWidthTypes); TYPED_TEST_SUITE(TypedScalarTestWithoutFixedPoint, cudf::test::FixedWidthTypesWithoutFixedPoint); TYPED_TEST(TypedScalarTest, DefaultValidity) { using Type = cudf::device_storage_type_t<TypeParam>; Type value = static_cast<Type>(cudf::test::make_type_param_scalar<TypeParam>(7)); cudf::scalar_type_t<TypeParam> s(value); EXPECT_TRUE(s.is_valid()); EXPECT_EQ(value, s.value()); } TYPED_TEST(TypedScalarTest, ConstructNull) { TypeParam value = cudf::test::make_type_param_scalar<TypeParam>(5); cudf::scalar_type_t<TypeParam> s(value, false); EXPECT_FALSE(s.is_valid()); } TYPED_TEST(TypedScalarTestWithoutFixedPoint, SetValue) { TypeParam init = cudf::test::make_type_param_scalar<TypeParam>(0); TypeParam value = cudf::test::make_type_param_scalar<TypeParam>(9); cudf::scalar_type_t<TypeParam> s(init, true); s.set_value(value); EXPECT_TRUE(s.is_valid()); EXPECT_EQ(value, s.value()); } TYPED_TEST(TypedScalarTestWithoutFixedPoint, SetNull) { TypeParam value = cudf::test::make_type_param_scalar<TypeParam>(6); cudf::scalar_type_t<TypeParam> s(value, true); s.set_valid_async(false); EXPECT_FALSE(s.is_valid()); } TYPED_TEST(TypedScalarTest, CopyConstructor) { using Type = cudf::device_storage_type_t<TypeParam>; Type value = static_cast<Type>(cudf::test::make_type_param_scalar<TypeParam>(8)); cudf::scalar_type_t<TypeParam> s(value); auto s2 = s; EXPECT_TRUE(s2.is_valid()); EXPECT_EQ(value, s2.value()); } TYPED_TEST(TypedScalarTest, MoveConstructor) { TypeParam value = cudf::test::make_type_param_scalar<TypeParam>(8); cudf::scalar_type_t<TypeParam> s(value); auto data_ptr = s.data(); auto mask_ptr = s.validity_data(); decltype(s) s2(std::move(s)); EXPECT_EQ(mask_ptr, s2.validity_data()); EXPECT_EQ(data_ptr, s2.data()); } struct StringScalarTest : public cudf::test::BaseFixture {}; TEST_F(StringScalarTest, DefaultValidity) { std::string value = "test string"; auto s = cudf::string_scalar(value); EXPECT_TRUE(s.is_valid()); EXPECT_EQ(value, s.to_string()); } TEST_F(StringScalarTest, CopyConstructor) { std::string value = "test_string"; auto s = cudf::string_scalar(value); auto s2 = s; EXPECT_TRUE(s2.is_valid()); EXPECT_EQ(value, s2.to_string()); } TEST_F(StringScalarTest, MoveConstructor) { std::string value = "another test string"; auto s = cudf::string_scalar(value); auto data_ptr = s.data(); auto mask_ptr = s.validity_data(); decltype(s) s2(std::move(s)); EXPECT_EQ(mask_ptr, s2.validity_data()); EXPECT_EQ(data_ptr, s2.data()); } struct ListScalarTest : public cudf::test::BaseFixture {}; TEST_F(ListScalarTest, DefaultValidityNonNested) { auto data = cudf::test::fixed_width_column_wrapper<int32_t>{1, 2, 3}; auto s = cudf::list_scalar(data); EXPECT_TRUE(s.is_valid()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(data, s.view()); } TEST_F(ListScalarTest, DefaultValidityNested) { auto data = cudf::test::lists_column_wrapper<int32_t>{{1, 2}, {2}, {}, {4, 5}}; auto s = cudf::list_scalar(data); EXPECT_TRUE(s.is_valid()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(data, s.view()); } TEST_F(ListScalarTest, MoveColumnConstructor) { auto data = cudf::test::fixed_width_column_wrapper<int32_t>{1, 2, 3}; auto col = cudf::column(data); auto ptr = col.view().data<int32_t>(); auto s = cudf::list_scalar(std::move(col)); EXPECT_TRUE(s.is_valid()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(data, s.view()); EXPECT_EQ(ptr, s.view().data<int32_t>()); } TEST_F(ListScalarTest, CopyConstructorNonNested) { auto data = cudf::test::fixed_width_column_wrapper<int32_t>{1, 2, 3}; auto s = cudf::list_scalar(data); auto s2 = s; EXPECT_TRUE(s2.is_valid()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(data, s2.view()); EXPECT_NE(s.view().data<int32_t>(), s2.view().data<int32_t>()); } TEST_F(ListScalarTest, CopyConstructorNested) { auto data = cudf::test::lists_column_wrapper<int32_t>{{1, 2}, {2}, {}, {4, 5}}; auto s = cudf::list_scalar(data); auto s2 = s; EXPECT_TRUE(s2.is_valid()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(data, s2.view()); EXPECT_NE(s.view().child(0).data<int32_t>(), s2.view().child(0).data<int32_t>()); EXPECT_NE(s.view().child(1).data<int32_t>(), s2.view().child(1).data<int32_t>()); } TEST_F(ListScalarTest, MoveConstructorNonNested) { auto data = cudf::test::fixed_width_column_wrapper<int32_t>{1, 2, 3}; auto s = cudf::list_scalar(data); auto data_ptr = s.view().data<int32_t>(); auto mask_ptr = s.validity_data(); decltype(s) s2(std::move(s)); EXPECT_EQ(mask_ptr, s2.validity_data()); EXPECT_EQ(data_ptr, s2.view().data<int32_t>()); EXPECT_EQ(s.view().data<int32_t>(), nullptr); } TEST_F(ListScalarTest, MoveConstructorNested) { auto data = cudf::test::lists_column_wrapper<int32_t>{{1, 2}, {2}, {}, {4, 5}}; auto s = cudf::list_scalar(data); auto offset_ptr = s.view().child(0).data<cudf::size_type>(); auto data_ptr = s.view().child(1).data<int32_t>(); auto mask_ptr = s.validity_data(); decltype(s) s2(std::move(s)); EXPECT_EQ(mask_ptr, s2.validity_data()); EXPECT_EQ(offset_ptr, s2.view().child(0).data<cudf::size_type>()); EXPECT_EQ(data_ptr, s2.view().child(1).data<int32_t>()); EXPECT_EQ(s.view().data<int32_t>(), nullptr); EXPECT_EQ(s.view().num_children(), 0); } struct StructScalarTest : public cudf::test::BaseFixture {}; TEST_F(StructScalarTest, Basic) { cudf::test::fixed_width_column_wrapper<int> col0{1}; cudf::test::strings_column_wrapper col1{"abc"}; cudf::test::lists_column_wrapper<int> col2{{1, 2, 3}}; cudf::test::structs_column_wrapper struct_col({col0, col1, col2}); cudf::column_view cv = static_cast<cudf::column_view>(struct_col); std::vector<cudf::column_view> children(cv.child_begin(), cv.child_end()); // table_view constructor { auto s = cudf::struct_scalar(children, true); EXPECT_TRUE(s.is_valid()); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(cudf::table_view{children}, s.view()); } // host_span constructor { auto s = cudf::struct_scalar(cudf::host_span<cudf::column_view const>{children}, true); EXPECT_TRUE(s.is_valid()); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(cudf::table_view{children}, s.view()); } } TEST_F(StructScalarTest, BasicNulls) { cudf::test::fixed_width_column_wrapper<int> col0{1}; cudf::test::strings_column_wrapper col1{"abc"}; cudf::test::lists_column_wrapper<int> col2{{1, 2, 3}}; std::vector<cudf::column_view> src_children({col0, col1, col2}); std::vector<std::unique_ptr<cudf::column>> src_columns; // structs_column_wrapper takes ownership of the incoming columns, so make a copy src_columns.push_back(std::make_unique<cudf::column>(src_children[0])); src_columns.push_back(std::make_unique<cudf::column>(src_children[1])); src_columns.push_back(std::make_unique<cudf::column>(src_children[2])); cudf::test::structs_column_wrapper valid_struct_col(std::move(src_columns), {1}); cudf::column_view vcv = static_cast<cudf::column_view>(valid_struct_col); std::vector<cudf::column_view> valid_children(vcv.child_begin(), vcv.child_end()); // structs_column_wrapper takes ownership of the incoming columns, so make a copy src_columns.push_back(std::make_unique<cudf::column>(src_children[0])); src_columns.push_back(std::make_unique<cudf::column>(src_children[1])); src_columns.push_back(std::make_unique<cudf::column>(src_children[2])); cudf::test::structs_column_wrapper invalid_struct_col(std::move(src_columns), {0}); cudf::column_view icv = static_cast<cudf::column_view>(invalid_struct_col); std::vector<cudf::column_view> invalid_children(icv.child_begin(), icv.child_end()); // table_view constructor { auto s = cudf::struct_scalar(cudf::table_view{src_children}, true); EXPECT_TRUE(s.is_valid()); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(cudf::table_view{valid_children}, s.view()); } // host_span constructor { auto s = cudf::struct_scalar(cudf::host_span<cudf::column_view const>{src_children}, true); EXPECT_TRUE(s.is_valid()); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(cudf::table_view{valid_children}, s.view()); } // with nulls, we expect the incoming children to get nullified by passing false to // the scalar constructor itself. so we use the unmodified `children` as the input, but // we compare against the modified `invalid_children` produced by the source column as // proof that the scalar did the validity pushdown. // table_view constructor { auto s = cudf::struct_scalar(cudf::table_view{src_children}, false); EXPECT_TRUE(!s.is_valid()); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(cudf::table_view{invalid_children}, s.view()); } // host_span constructor { auto s = cudf::struct_scalar(cudf::host_span<cudf::column_view const>{src_children}, false); EXPECT_TRUE(!s.is_valid()); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(cudf::table_view{invalid_children}, s.view()); } } CUDF_TEST_PROGRAM_MAIN()
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/transpose/transpose_test.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/transpose.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/type_lists.hpp> #include <algorithm> #include <limits> #include <random> #include <string> namespace { template <typename T, typename F> auto generate_vectors(size_t ncols, size_t nrows, F generator) { std::vector<std::vector<T>> values(ncols); std::for_each(values.begin(), values.end(), [generator, nrows](std::vector<T>& col) { col.resize(nrows); std::generate(col.begin(), col.end(), generator); }); return values; } template <typename T> auto transpose_vectors(std::vector<std::vector<T>> const& input) { if (input.empty()) { return input; } size_t ncols = input.size(); size_t nrows = input.front().size(); std::vector<std::vector<T>> transposed(nrows); std::for_each( transposed.begin(), transposed.end(), [=](std::vector<T>& col) { col.resize(ncols); }); for (size_t col = 0; col < input.size(); ++col) { for (size_t row = 0; row < nrows; ++row) { transposed[row][col] = input[col][row]; } } return transposed; } template <typename T, typename ColumnWrapper> auto make_columns(std::vector<std::vector<T>> const& values) { std::vector<ColumnWrapper> columns; columns.reserve(values.size()); for (auto const& value_col : values) { columns.emplace_back(value_col.begin(), value_col.end()); } return columns; } template <typename T, typename ColumnWrapper> auto make_columns(std::vector<std::vector<T>> const& values, std::vector<std::vector<cudf::size_type>> const& valids) { std::vector<ColumnWrapper> columns; columns.reserve(values.size()); for (size_t col = 0; col < values.size(); ++col) { columns.emplace_back(values[col].begin(), values[col].end(), valids[col].begin()); } return columns; } template <typename ColumnWrapper> auto make_table_view(std::vector<ColumnWrapper> const& cols) { std::vector<cudf::column_view> views(cols.size()); std::transform(cols.begin(), cols.end(), views.begin(), [](auto const& col) { return static_cast<cudf::column_view>(col); }); return cudf::table_view(views); } template <typename T> void run_test(size_t ncols, size_t nrows, bool add_nulls) { using ColumnWrapper = std::conditional_t<std::is_same_v<T, std::string>, cudf::test::strings_column_wrapper, cudf::test::fixed_width_column_wrapper<T>>; std::mt19937 rng(1); // Generate values as vector of vectors auto const values = generate_vectors<T>( ncols, nrows, [&rng]() { return cudf::test::make_type_param_scalar<T>(rng()); }); auto const valuesT = transpose_vectors(values); std::vector<ColumnWrapper> input_cols; std::vector<ColumnWrapper> expected_cols; std::vector<cudf::size_type> expected_nulls(nrows); if (add_nulls) { // Generate null mask as vector of vectors auto const valids = generate_vectors<cudf::size_type>( ncols, nrows, [&rng]() { return static_cast<cudf::size_type>(rng() % 3 > 0 ? 1 : 0); }); auto const validsT = transpose_vectors(valids); // Compute the null counts over each transposed column std::transform(validsT.begin(), validsT.end(), expected_nulls.begin(), [ncols](std::vector<cudf::size_type> const& vec) { // num nulls = num elems - num valids return ncols - std::accumulate(vec.begin(), vec.end(), 0); }); // Create column wrappers from vector of vectors input_cols = make_columns<T, ColumnWrapper>(values, valids); expected_cols = make_columns<T, ColumnWrapper>(valuesT, validsT); } else { input_cols = make_columns<T, ColumnWrapper>(values); expected_cols = make_columns<T, ColumnWrapper>(valuesT); } // Create table views from column wrappers auto input_view = make_table_view(input_cols); auto expected_view = make_table_view(expected_cols); auto result = transpose(input_view); auto result_view = std::get<1>(result); ASSERT_EQ(result_view.num_columns(), expected_view.num_columns()); for (cudf::size_type i = 0; i < result_view.num_columns(); ++i) { CUDF_TEST_EXPECT_COLUMNS_EQUAL(result_view.column(i), expected_view.column(i)); EXPECT_EQ(result_view.column(i).null_count(), expected_nulls[i]); } } } // namespace template <typename T> class TransposeTest : public cudf::test::BaseFixture {}; // Using std::string here instead of cudf::test::StringTypes allows us to // use std::vector<T> utilities in this file just like the fixed-width types. // Should consider changing cudf::test::StringTypes to std::string instead of cudf::string_view. using StdStringType = cudf::test::Types<std::string>; using TransposeTypes = cudf::test::Concat<cudf::test::FixedWidthTypes, StdStringType>; TYPED_TEST_SUITE(TransposeTest, TransposeTypes); // cudf::test::FixedWidthTypes); TYPED_TEST(TransposeTest, SingleValue) { run_test<TypeParam>(1, 1, false); } TYPED_TEST(TransposeTest, SingleColumn) { run_test<TypeParam>(1, 1000, false); } TYPED_TEST(TransposeTest, SingleColumnNulls) { run_test<TypeParam>(1, 1000, true); } TYPED_TEST(TransposeTest, Square) { run_test<TypeParam>(100, 100, false); } TYPED_TEST(TransposeTest, SquareNulls) { run_test<TypeParam>(100, 100, true); } TYPED_TEST(TransposeTest, Slim) { run_test<TypeParam>(10, 1000, false); } TYPED_TEST(TransposeTest, SlimNulls) { run_test<TypeParam>(10, 1000, true); } TYPED_TEST(TransposeTest, Fat) { run_test<TypeParam>(1000, 10, false); } TYPED_TEST(TransposeTest, FatNulls) { run_test<TypeParam>(1000, 10, true); } TYPED_TEST(TransposeTest, EmptyTable) { run_test<TypeParam>(0, 0, false); } TYPED_TEST(TransposeTest, EmptyColumns) { run_test<TypeParam>(10, 0, false); } class TransposeTestError : public cudf::test::BaseFixture {}; TEST_F(TransposeTestError, MismatchedColumns) { cudf::test::fixed_width_column_wrapper<uint32_t, int32_t> col1({1, 2, 3}); cudf::test::fixed_width_column_wrapper<int8_t> col2{{4, 5, 6}}; cudf::test::fixed_width_column_wrapper<float> col3{{7, 8, 9}}; cudf::table_view input{{col1, col2, col3}}; EXPECT_THROW(cudf::transpose(input), cudf::logic_error); } CUDF_TEST_PROGRAM_MAIN()
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/stream_compaction/stable_distinct_tests.cpp
/* * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf/copying.hpp> #include <cudf/sorting.hpp> #include <cudf/stream_compaction.hpp> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> #include <cudf/types.hpp> #include <cmath> auto constexpr null{0}; // null at current level auto constexpr XXX{0}; // null pushed down from parent level auto constexpr NaN = std::numeric_limits<double>::quiet_NaN(); auto constexpr KEEP_ANY = cudf::duplicate_keep_option::KEEP_ANY; auto constexpr KEEP_FIRST = cudf::duplicate_keep_option::KEEP_FIRST; auto constexpr KEEP_LAST = cudf::duplicate_keep_option::KEEP_LAST; auto constexpr KEEP_NONE = cudf::duplicate_keep_option::KEEP_NONE; auto constexpr NULL_EQUAL = cudf::null_equality::EQUAL; auto constexpr NULL_UNEQUAL = cudf::null_equality::UNEQUAL; auto constexpr NAN_EQUAL = cudf::nan_equality::ALL_EQUAL; auto constexpr NAN_UNEQUAL = cudf::nan_equality::UNEQUAL; using int32s_col = cudf::test::fixed_width_column_wrapper<int32_t>; using floats_col = cudf::test::fixed_width_column_wrapper<float>; using lists_col = cudf::test::lists_column_wrapper<int32_t>; using strings_col = cudf::test::strings_column_wrapper; using structs_col = cudf::test::structs_column_wrapper; using cudf::nan_policy; using cudf::null_equality; using cudf::null_policy; using cudf::test::iterators::no_nulls; using cudf::test::iterators::null_at; using cudf::test::iterators::nulls_at; struct StableDistinctKeepAny : public cudf::test::BaseFixture {}; struct StableDistinctKeepFirstLastNone : public cudf::test::BaseFixture {}; TEST_F(StableDistinctKeepAny, StringKeyColumn) { // Column(s) used to test KEEP_ANY needs to have same rows in contiguous // groups for equivalent keys because KEEP_ANY is nondeterministic. auto const col = int32s_col{{5, 5, null, null, 5, 8, 1}, nulls_at({2, 3})}; auto const keys = strings_col{{"all", "all", "new", "new", "" /*NULL*/, "the", "strings"}, null_at(4)}; auto const input = cudf::table_view{{col, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; auto const exp_col = int32s_col{{5, null, 5, 8, 1}, null_at(1)}; auto const exp_keys = strings_col{{"all", "new", "" /*NULL*/, "the", "strings"}, null_at(2)}; auto const expected = cudf::table_view{{exp_col, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } TEST_F(StableDistinctKeepFirstLastNone, StringKeyColumn) { // Column(s) used to test needs to have different rows for the same keys. auto const col = int32s_col{{0, null, 2, 3, 4, 5, 6}, null_at(1)}; auto const keys = strings_col{{"all", "new", "new", "all", "" /*NULL*/, "the", "strings"}, null_at(4)}; auto const input = cudf::table_view{{col, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP_FIRST { auto const exp_col = int32s_col{{0, null, 4, 5, 6}, null_at(1)}; auto const exp_keys = strings_col{{"all", "new", "" /*NULL*/, "the", "strings"}, null_at(2)}; auto const expected = cudf::table_view{{exp_col, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_FIRST); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // KEEP_LAST { auto const exp_col = int32s_col{{2, 3, 4, 5, 6}, no_nulls()}; auto const exp_keys = strings_col{{"new", "all", "" /*NULL*/, "the", "strings"}, null_at(2)}; auto const expected = cudf::table_view{{exp_col, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_LAST); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // KEEP_NONE { auto const exp_col = int32s_col{{4, 5, 6}, no_nulls()}; auto const exp_keys = strings_col{{"" /*NULL*/, "the", "strings"}, null_at(0)}; auto const expected = cudf::table_view{{exp_col, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_NONE); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } } TEST_F(StableDistinctKeepAny, EmptyInputTable) { int32s_col col(std::initializer_list<int32_t>{}); cudf::table_view input{{col}}; std::vector<cudf::size_type> key_idx{0}; auto got = cudf::stable_distinct(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(input, got->view()); } TEST_F(StableDistinctKeepAny, NoColumnInputTable) { cudf::table_view input{std::vector<cudf::column_view>()}; std::vector<cudf::size_type> key_idx{1, 2}; auto got = cudf::stable_distinct(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(input, got->view()); } TEST_F(StableDistinctKeepAny, EmptyKeys) { int32s_col col{{5, 4, 3, 5, 8, 1}, {1, 0, 1, 1, 1, 1}}; int32s_col empty_col{}; cudf::table_view input{{col}}; std::vector<cudf::size_type> key_idx{}; auto got = cudf::stable_distinct(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(cudf::table_view{{empty_col}}, got->view()); } TEST_F(StableDistinctKeepAny, NoNullsTable) { // Column(s) used to test KEEP_ANY needs to have same rows in contiguous // groups for equivalent keys because KEEP_ANY is nondeterministic. auto const col1 = int32s_col{6, 6, 6, 3, 5, 8, 5}; auto const col2 = floats_col{6, 6, 6, 3, 4, 9, 4}; auto const keys1 = int32s_col{20, 20, 20, 20, 19, 21, 9}; auto const keys2 = int32s_col{19, 19, 19, 20, 20, 9, 21}; auto const input = cudf::table_view{{col1, col2, keys1, keys2}}; auto const key_idx = std::vector<cudf::size_type>{2, 3}; auto const exp_col1 = int32s_col{6, 3, 5, 8, 5}; auto const exp_col2 = floats_col{6, 3, 4, 9, 4}; auto const exp_keys1 = int32s_col{20, 20, 19, 21, 9}; auto const exp_keys2 = int32s_col{19, 20, 20, 9, 21}; auto const expected = cudf::table_view{{exp_col1, exp_col2, exp_keys1, exp_keys2}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } TEST_F(StableDistinctKeepAny, NoNullsTableWithNaNs) { // Column(s) used to test KEEP_ANY needs to have same rows in contiguous // groups for equivalent keys because KEEP_ANY is nondeterministic. auto const col1 = int32s_col{6, 6, 6, 1, 1, 1, 3, 5, 8, 5}; auto const col2 = floats_col{6, 6, 6, 1, 1, 1, 3, 4, 9, 4}; auto const keys1 = int32s_col{20, 20, 20, 15, 15, 15, 20, 19, 21, 9}; auto const keys2 = floats_col{19., 19., 19., NaN, NaN, NaN, 20., 20., 9., 21.}; auto const input = cudf::table_view{{col1, col2, keys1, keys2}}; auto const key_idx = std::vector<cudf::size_type>{2, 3}; // NaNs are unequal. { auto const exp_col1 = int32s_col{6, 1, 1, 1, 3, 5, 8, 5}; auto const exp_col2 = floats_col{6, 1, 1, 1, 3, 4, 9, 4}; auto const exp_keys1 = int32s_col{20, 15, 15, 15, 20, 19, 21, 9}; auto const exp_keys2 = floats_col{19., NaN, NaN, NaN, 20., 20., 9., 21.}; auto const expected = cudf::table_view{{exp_col1, exp_col2, exp_keys1, exp_keys2}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY, NULL_EQUAL, NAN_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // NaNs are equal. { auto const exp_col1 = int32s_col{6, 1, 3, 5, 8, 5}; auto const exp_col2 = floats_col{6, 1, 3, 4, 9, 4}; auto const exp_keys1 = int32s_col{20, 15, 20, 19, 21, 9}; auto const exp_keys2 = floats_col{19., NaN, 20., 20., 9., 21.}; auto const expected = cudf::table_view{{exp_col1, exp_col2, exp_keys1, exp_keys2}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY, NULL_EQUAL, NAN_EQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } } TEST_F(StableDistinctKeepFirstLastNone, NoNullsTable) { // Column(s) used to test needs to have different rows for the same keys. auto const col1 = int32s_col{0, 1, 2, 3, 4, 5, 6}; auto const col2 = floats_col{10, 11, 12, 13, 14, 15, 16}; auto const keys1 = int32s_col{20, 20, 20, 20, 19, 21, 9}; auto const keys2 = int32s_col{19, 19, 19, 20, 20, 9, 21}; auto const input = cudf::table_view{{col1, col2, keys1, keys2}}; auto const key_idx = std::vector<cudf::size_type>{2, 3}; // KEEP_FIRST { auto const exp_col1 = int32s_col{0, 3, 4, 5, 6}; auto const exp_col2 = floats_col{10, 13, 14, 15, 16}; auto const exp_keys1 = int32s_col{20, 20, 19, 21, 9}; auto const exp_keys2 = int32s_col{19, 20, 20, 9, 21}; auto const expected = cudf::table_view{{exp_col1, exp_col2, exp_keys1, exp_keys2}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_FIRST); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // KEEP_LAST { auto const exp_col1 = int32s_col{2, 3, 4, 5, 6}; auto const exp_col2 = floats_col{12, 13, 14, 15, 16}; auto const exp_keys1 = int32s_col{20, 20, 19, 21, 9}; auto const exp_keys2 = int32s_col{19, 20, 20, 9, 21}; auto const expected = cudf::table_view{{exp_col1, exp_col2, exp_keys1, exp_keys2}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_LAST); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // KEEP_NONE { auto const exp_col1 = int32s_col{3, 4, 5, 6}; auto const exp_col2 = floats_col{13, 14, 15, 16}; auto const exp_keys1 = int32s_col{20, 19, 21, 9}; auto const exp_keys2 = int32s_col{20, 20, 9, 21}; auto const expected = cudf::table_view{{exp_col1, exp_col2, exp_keys1, exp_keys2}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_NONE); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } } TEST_F(StableDistinctKeepAny, SlicedNoNullsTable) { auto constexpr dont_care = int32_t{0}; // Column(s) used to test KEEP_ANY needs to have same rows in contiguous // groups for equivalent keys because KEEP_ANY is nondeterministic. auto const col1 = int32s_col{dont_care, dont_care, 6, 6, 6, 3, 5, 8, 5, dont_care}; auto const col2 = floats_col{dont_care, dont_care, 6, 6, 6, 3, 4, 9, 4, dont_care}; auto const keys1 = int32s_col{dont_care, dont_care, 20, 20, 20, 20, 19, 21, 9, dont_care}; auto const keys2 = int32s_col{dont_care, dont_care, 19, 19, 19, 20, 20, 9, 21, dont_care}; auto const input_original = cudf::table_view{{col1, col2, keys1, keys2}}; auto const input = cudf::slice(input_original, {2, 9})[0]; auto const key_idx = std::vector<cudf::size_type>{2, 3}; auto const exp_col1 = int32s_col{6, 3, 5, 8, 5}; auto const exp_col2 = floats_col{6, 3, 4, 9, 4}; auto const exp_keys1 = int32s_col{20, 20, 19, 21, 9}; auto const exp_keys2 = int32s_col{19, 20, 20, 9, 21}; auto const expected = cudf::table_view{{exp_col1, exp_col2, exp_keys1, exp_keys2}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } TEST_F(StableDistinctKeepFirstLastNone, SlicedNoNullsTable) { auto constexpr dont_care = int32_t{0}; // Column(s) used to test needs to have different rows for the same keys. // clang-format off auto const col1 = int32s_col{0, 1, 2, // <- don't care 3, 4, 5, 6, 7, 8, 9, dont_care}; auto const col2 = floats_col{10, 11, 12, // <- don't care 13, 14, 15, 16, 17, 18, 19, dont_care}; auto const keys1 = int32s_col{20, 20, 20, // <- don't care 20, 20, 20, 20, 19, 21, 9, dont_care}; auto const keys2 = int32s_col{19, 19, 19, // <- don't care 19, 19, 19, 20, 20, 9, 21, dont_care}; // clang-format on auto const input_original = cudf::table_view{{col1, col2, keys1, keys2}}; auto const input = cudf::slice(input_original, {3, 10})[0]; auto const key_idx = std::vector<cudf::size_type>{2, 3}; // KEEP_FIRST { auto const exp_col1 = int32s_col{3, 6, 7, 8, 9}; auto const exp_col2 = floats_col{13, 16, 17, 18, 19}; auto const exp_keys1 = int32s_col{20, 20, 19, 21, 9}; auto const exp_keys2 = int32s_col{19, 20, 20, 9, 21}; auto const expected = cudf::table_view{{exp_col1, exp_col2, exp_keys1, exp_keys2}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_FIRST); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // KEEP_LAST { auto const exp_col1 = int32s_col{5, 6, 7, 8, 9}; auto const exp_col2 = floats_col{15, 16, 17, 18, 19}; auto const exp_keys1 = int32s_col{20, 20, 19, 21, 9}; auto const exp_keys2 = int32s_col{19, 20, 20, 9, 21}; auto const expected = cudf::table_view{{exp_col1, exp_col2, exp_keys1, exp_keys2}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_LAST); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // KEEP_NONE { auto const exp_col1 = int32s_col{6, 7, 8, 9}; auto const exp_col2 = floats_col{16, 17, 18, 19}; auto const exp_keys1 = int32s_col{20, 19, 21, 9}; auto const exp_keys2 = int32s_col{20, 20, 9, 21}; auto const expected = cudf::table_view{{exp_col1, exp_col2, exp_keys1, exp_keys2}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_NONE); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } } TEST_F(StableDistinctKeepAny, InputWithNulls) { // Column(s) used to test KEEP_ANY needs to have same rows in contiguous // groups for equivalent keys because KEEP_ANY is nondeterministic. auto const col = int32s_col{5, 4, 4, 1, 1, 8}; auto const keys = int32s_col{{20, null, null, 19, 19, 21}, nulls_at({1, 2})}; auto const input = cudf::table_view{{col, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal. { auto const exp_col = int32s_col{5, 4, 1, 8}; auto const exp_keys = int32s_col{{20, null, 19, 21}, null_at(1)}; auto const expected = cudf::table_view{{exp_col, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // Nulls are unequal. { auto const exp_col = int32s_col{5, 4, 4, 1, 8}; auto const exp_keys = int32s_col{{20, null, null, 19, 21}, nulls_at({1, 2})}; auto const expected = cudf::table_view{{exp_col, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY, NULL_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } } TEST_F(StableDistinctKeepAny, InputWithNullsAndNaNs) { auto constexpr null{0.0}; // shadow the global `null` variable of type int // Column(s) used to test KEEP_ANY needs to have same rows in contiguous // groups for equivalent keys because KEEP_ANY is nondeterministic. auto const col = int32s_col{5, 4, 4, 1, 1, 1, 8, 8, 1}; auto const keys = floats_col{{20., null, null, NaN, NaN, NaN, 19., 19., 21.}, nulls_at({1, 2})}; auto const input = cudf::table_view{{col, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal, NaNs are unequal. { auto const exp_col = int32s_col{5, 4, 1, 1, 1, 8, 1}; auto const exp_keys = floats_col{{20., null, NaN, NaN, NaN, 19., 21.}, null_at(1)}; auto const expected = cudf::table_view{{exp_col, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY, NULL_EQUAL, NAN_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // Nulls are equal, NaNs are equal. { auto const exp_col = int32s_col{5, 4, 1, 8, 1}; auto const exp_keys = floats_col{{20., null, NaN, 19., 21.}, null_at(1)}; auto const expected = cudf::table_view{{exp_col, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY, NULL_EQUAL, NAN_EQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // Nulls are unequal, NaNs are unequal. { auto const exp_col = int32s_col{5, 4, 4, 1, 1, 1, 8, 1}; auto const exp_keys = floats_col{{20., null, null, NaN, NaN, NaN, 19., 21.}, nulls_at({1, 2})}; auto const expected = cudf::table_view{{exp_col, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY, NULL_UNEQUAL, NAN_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // Nulls are unequal, NaNs are equal. { auto const exp_col = int32s_col{5, 4, 4, 1, 8, 1}; auto const exp_keys = floats_col{{20., null, null, NaN, 19., 21.}, nulls_at({1, 2})}; auto const expected = cudf::table_view{{exp_col, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY, NULL_UNEQUAL, NAN_EQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } } TEST_F(StableDistinctKeepFirstLastNone, InputWithNullsEqual) { // Column(s) used to test needs to have different rows for the same keys. auto const col = int32s_col{0, 1, 2, 3, 4, 5, 6}; auto const keys = int32s_col{{20, null, null, 19, 21, 19, 22}, nulls_at({1, 2})}; auto const input = cudf::table_view{{col, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP_FIRST { auto const exp_col = int32s_col{0, 1, 3, 4, 6}; auto const exp_keys = int32s_col{{20, null, 19, 21, 22}, null_at(1)}; auto const expected = cudf::table_view{{exp_col, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_FIRST, NULL_EQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // KEEP_LAST { auto const exp_col = int32s_col{0, 2, 4, 5, 6}; auto const exp_keys = int32s_col{{20, null, 21, 19, 22}, null_at(1)}; auto const expected = cudf::table_view{{exp_col, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_LAST, NULL_EQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // KEEP_NONE { auto const exp_col = int32s_col{0, 4, 6}; auto const exp_keys = int32s_col{{20, 21, 22}, no_nulls()}; auto const expected = cudf::table_view{{exp_col, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_NONE, NULL_EQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } } TEST_F(StableDistinctKeepFirstLastNone, InputWithNullsUnequal) { // Column(s) used to test needs to have different rows for the same keys. auto const col = int32s_col{0, 1, 2, 3, 4, 5, 6, 7}; auto const keys = int32s_col{{20, null, null, 19, 21, 19, 22, 20}, nulls_at({1, 2})}; auto const input = cudf::table_view{{col, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP_FIRST { auto const exp_col = int32s_col{0, 1, 2, 3, 4, 6}; auto const exp_keys = int32s_col{{20, null, null, 19, 21, 22}, nulls_at({1, 2})}; auto const expected = cudf::table_view{{exp_col, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_FIRST, NULL_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // KEEP_LAST { auto const exp_col = int32s_col{1, 2, 4, 5, 6, 7}; auto const exp_keys = int32s_col{{null, null, 21, 19, 22, 20}, nulls_at({0, 1})}; auto const expected = cudf::table_view{{exp_col, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_LAST, NULL_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // KEEP_NONE { auto const exp_col = int32s_col{1, 2, 4, 6}; auto const exp_keys = int32s_col{{null, null, 21, 22}, nulls_at({0, 1})}; auto const expected = cudf::table_view{{exp_col, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_NONE, NULL_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } } TEST_F(StableDistinctKeepFirstLastNone, InputWithNaNsEqual) { // Column(s) used to test needs to have different rows for the same keys. auto const col = int32s_col{0, 1, 2, 3, 4, 5, 6}; auto const keys = floats_col{20., NaN, NaN, 19., 21., 19., 22.}; auto const input = cudf::table_view{{col, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP_FIRST { auto const exp_col = int32s_col{0, 1, 3, 4, 6}; auto const exp_keys = floats_col{20., NaN, 19., 21., 22.}; auto const expected = cudf::table_view{{exp_col, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_FIRST, NULL_EQUAL, NAN_EQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // KEEP_LAST { auto const exp_col = int32s_col{0, 2, 4, 5, 6}; auto const exp_keys = floats_col{20., NaN, 21., 19., 22.}; auto const expected = cudf::table_view{{exp_col, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_LAST, NULL_EQUAL, NAN_EQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // KEEP_NONE { auto const exp_col = int32s_col{0, 4, 6}; auto const exp_keys = floats_col{20., 21., 22.}; auto const expected = cudf::table_view{{exp_col, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_NONE, NULL_EQUAL, NAN_EQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } } TEST_F(StableDistinctKeepFirstLastNone, InputWithNaNsUnequal) { // Column(s) used to test needs to have different rows for the same keys. auto const col = int32s_col{0, 1, 2, 3, 4, 5, 6, 7}; auto const keys = floats_col{20., NaN, NaN, 19., 21., 19., 22., 20.}; auto const input = cudf::table_view{{col, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP_FIRST { auto const exp_col = int32s_col{0, 1, 2, 3, 4, 6}; auto const exp_keys = floats_col{20., NaN, NaN, 19., 21., 22.}; auto const expected = cudf::table_view{{exp_col, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_FIRST, NULL_UNEQUAL, NAN_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // KEEP_LAST { auto const exp_col = int32s_col{1, 2, 4, 5, 6, 7}; auto const exp_keys = floats_col{NaN, NaN, 21., 19., 22., 20.}; auto const expected = cudf::table_view{{exp_col, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_LAST, NULL_UNEQUAL, NAN_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // KEEP_NONE { auto const exp_col = int32s_col{1, 2, 4, 6}; auto const exp_keys = floats_col{NaN, NaN, 21., 22.}; auto const expected = cudf::table_view{{exp_col, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_NONE, NULL_UNEQUAL, NAN_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } } TEST_F(StableDistinctKeepAny, BasicLists) { // Column(s) used to test KEEP_ANY needs to have same rows in contiguous // groups for equivalent keys because KEEP_ANY is nondeterministic. // clang-format off auto const idx = int32s_col{ 0, 0, 1, 1, 2, 3, 4, 4, 4, 5, 5, 6}; auto const keys = lists_col{{}, {}, {1}, {1}, {1, 1}, {1, 2}, {2, 2}, {2, 2}, {2, 2}, {2}, {2}, {2, 1}}; // clang-format on auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; auto const exp_idx = int32s_col{0, 1, 2, 3, 4, 5, 6}; auto const exp_keys = lists_col{{}, {1}, {1, 1}, {1, 2}, {2, 2}, {2}, {2, 1}}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } TEST_F(StableDistinctKeepFirstLastNone, BasicLists) { // Column(s) used to test needs to have different rows for the same keys. // clang-format off auto const idx = int32s_col{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; auto const keys = lists_col{{}, {}, {1}, {1, 1}, {1}, {1, 2}, {2, 2}, {2}, {2}, {2, 1}, {2, 2}, {2, 2}}; // clang-format on auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP_FIRST { auto const exp_idx = int32s_col{0, 2, 3, 5, 6, 7, 9}; auto const exp_keys = lists_col{{}, {1}, {1, 1}, {1, 2}, {2, 2}, {2}, {2, 1}}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_FIRST); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // KEEP_LAST { auto const exp_idx = int32s_col{1, 3, 4, 5, 8, 9, 11}; auto const exp_keys = lists_col{{}, {1, 1}, {1}, {1, 2}, {2}, {2, 1}, {2, 2}}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_LAST); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // KEEP_NONE { auto const exp_idx = int32s_col{3, 5, 9}; auto const exp_keys = lists_col{{1, 1}, {1, 2}, {2, 1}}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_NONE); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } } TEST_F(StableDistinctKeepAny, SlicedBasicLists) { auto constexpr dont_care = int32_t{0}; // Column(s) used to test KEEP_ANY needs to have same rows in contiguous // groups for equivalent keys because KEEP_ANY is nondeterministic. auto const idx = int32s_col{dont_care, dont_care, 1, 1, 2, 3, 4, 4, 4, 5, 5, 6, dont_care}; auto const keys = lists_col{ {0, 0}, {0, 0}, {1}, {1}, {1, 1}, {1, 2}, {2, 2}, {2, 2}, {2, 2}, {2}, {2}, {2, 1}, {5, 5}}; auto const input_original = cudf::table_view{{idx, keys}}; auto const input = cudf::slice(input_original, {2, 12})[0]; auto const key_idx = std::vector<cudf::size_type>{1}; auto const exp_idx = int32s_col{1, 2, 3, 4, 5, 6}; auto const exp_val = lists_col{{1}, {1, 1}, {1, 2}, {2, 2}, {2}, {2, 1}}; auto const expected = cudf::table_view{{exp_idx, exp_val}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } TEST_F(StableDistinctKeepAny, NullableLists) { // Column(s) used to test KEEP_ANY needs to have same rows in contiguous // groups for equivalent keys because KEEP_ANY is nondeterministic. auto const idx = int32s_col{0, 0, 1, 1, 2, 2, 2, 3, 3, 4, 4}; auto const keys = lists_col{{{}, {}, {1}, {1}, {2, 2}, {2, 2}, {2, 2}, {2}, {2}, {} /*NULL*/, {} /*NULL*/}, nulls_at({9, 10})}; auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal. { auto const exp_idx = int32s_col{0, 1, 2, 3, 4}; auto const exp_keys = lists_col{{{}, {1}, {2, 2}, {2}, {} /*NULL*/}, null_at(4)}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // Nulls are unequal. { auto const exp_idx = int32s_col{0, 1, 2, 3, 4, 4}; auto const exp_keys = lists_col{{{}, {1}, {2, 2}, {2}, {} /*NULL*/, {} /*NULL*/}, nulls_at({4, 5})}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY, NULL_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } } TEST_F(StableDistinctKeepFirstLastNone, ListsWithNullsEqual) { // Column(s) used to test needs to have different rows for the same keys. auto const idx = int32s_col{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; auto const keys = lists_col{{{}, {}, {1}, {1}, {2, 2}, {2}, {2}, {} /*NULL*/, {2, 2}, {2, 2}, {} /*NULL*/}, nulls_at({7, 10})}; auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP_FIRST { auto const exp_idx = int32s_col{0, 2, 4, 5, 7}; auto const exp_keys = lists_col{{{}, {1}, {2, 2}, {2}, {} /*NULL*/}, null_at(4)}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_FIRST, NULL_EQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // KEEP_LAST { auto const exp_idx = int32s_col{1, 3, 6, 9, 10}; auto const exp_keys = lists_col{{{}, {1}, {2}, {2, 2}, {} /*NULL*/}, null_at(4)}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_LAST, NULL_EQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // KEEP_NONE { auto const exp_idx = int32s_col{}; auto const exp_keys = lists_col{}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_NONE, NULL_EQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } } TEST_F(StableDistinctKeepFirstLastNone, ListsWithNullsUnequal) { // Column(s) used to test needs to have different rows for the same keys. auto const idx = int32s_col{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; auto const keys = lists_col{{{}, {}, {1}, {1}, {2, 2}, {2}, {2}, {} /*NULL*/, {2, 2}, {2, 2}, {} /*NULL*/}, nulls_at({7, 10})}; auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP_FIRST { auto const exp_idx = int32s_col{0, 2, 4, 5, 7, 10}; auto const exp_keys = lists_col{{{}, {1}, {2, 2}, {2}, {} /*NULL*/, {} /*NULL*/}, nulls_at({4, 5})}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_FIRST, NULL_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // KEEP_LAST { auto const exp_idx = int32s_col{1, 3, 6, 7, 9, 10}; auto const exp_keys = lists_col{{{}, {1}, {2}, {} /*NULL*/, {2, 2}, {} /*NULL*/}, nulls_at({3, 5})}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_LAST, NULL_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // KEEP_NONE { auto const exp_idx = int32s_col{7, 10}; auto const exp_keys = lists_col{{lists_col{} /*NULL*/, lists_col{} /*NULL*/}, nulls_at({0, 1})}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_NONE, NULL_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } } TEST_F(StableDistinctKeepAny, ListsOfStructs) { // Constructing a list of structs of two elements // 0. [] == // 1. [] != // 2. Null == // 3. Null != // 4. [Null, Null] != // 5. [Null] == // 6. [Null] == // 7. [Null] != // 8. [{Null, Null}] != // 9. [{1,'a'}, {2,'b'}] != // 10. [{0,'a'}, {2,'b'}] != // 11. [{0,'a'}, {2,'c'}] == // 12. [{0,'a'}, {2,'c'}] != // 13. [{0,Null}] == // 14. [{0,Null}] != // 15. [{Null, 'b'}] == // 16. [{Null, 'b'}] auto const structs = [] { auto child1 = int32s_col{{XXX, XXX, XXX, XXX, XXX, null, 1, 2, 0, 2, 0, 2, 0, 2, 0, 0, null, null}, nulls_at({5, 16, 17})}; auto child2 = strings_col{{"" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*null*/, "a", "b", "a", "b", "a", "c", "a", "c", "" /*null*/, "" /*null*/, "b", "b"}, nulls_at({5, 14, 15})}; return structs_col{{child1, child2}, nulls_at({0, 1, 2, 3, 4})}; }(); auto const offsets = int32s_col{0, 0, 0, 0, 0, 2, 3, 4, 5, 6, 8, 10, 12, 14, 15, 16, 17, 18}; auto const null_it = nulls_at({2, 3}); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(null_it, null_it + 17); auto const keys = cudf::column_view(cudf::data_type(cudf::type_id::LIST), 17, nullptr, static_cast<cudf::bitmask_type const*>(null_mask.data()), null_count, 0, {offsets, structs}); auto const idx = int32s_col{1, 1, 2, 2, 3, 4, 4, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10}; auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal. { auto const expect_map = int32s_col{0, 2, 4, 5, 8, 9, 10, 11, 13, 15}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } // Nulls are unequal. { auto const expect_map = int32s_col{0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY, NULL_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } } TEST_F(StableDistinctKeepFirstLastNone, ListsOfStructs) { // Constructing a list of structs of two elements // 0. [] == // 1. [] != // 2. Null == // 3. Null != // 4. [Null, Null] != // 5. [Null] == // 6. [Null] == // 7. [Null] != // 8. [{Null, Null}] != // 9. [{1,'a'}, {2,'b'}] != // 10. [{0,'a'}, {2,'b'}] != // 11. [{0,'a'}, {2,'c'}] == // 12. [{0,'a'}, {2,'c'}] != // 13. [{0,Null}] == // 14. [{0,Null}] != // 15. [{Null, 'b'}] == // 16. [{Null, 'b'}] auto const structs = [] { auto child1 = int32s_col{{XXX, XXX, XXX, XXX, XXX, null, 1, 2, 0, 2, 0, 2, 0, 2, 0, 0, null, null}, nulls_at({5, 16, 17})}; auto child2 = strings_col{{"" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*null*/, "a", "b", "a", "b", "a", "c", "a", "c", "" /*null*/, "" /*null*/, "b", "b"}, nulls_at({5, 14, 15})}; return structs_col{{child1, child2}, nulls_at({0, 1, 2, 3, 4})}; }(); auto const offsets = int32s_col{0, 0, 0, 0, 0, 2, 3, 4, 5, 6, 8, 10, 12, 14, 15, 16, 17, 18}; auto const null_it = nulls_at({2, 3}); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(null_it, null_it + 17); auto const keys = cudf::column_view(cudf::data_type(cudf::type_id::LIST), 17, nullptr, static_cast<cudf::bitmask_type const*>(null_mask.data()), null_count, 0, {offsets, structs}); auto const idx = int32s_col{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP_FIRST { auto const expect_map = int32s_col{0, 2, 4, 5, 8, 9, 10, 11, 13, 15}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::stable_distinct(input, key_idx, KEEP_FIRST); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } // KEEP_LAST { auto const expect_map = int32s_col{1, 3, 4, 7, 8, 9, 10, 12, 14, 16}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::stable_distinct(input, key_idx, KEEP_LAST); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } // KEEP_NONE { auto const expect_map = int32s_col{4, 8, 9, 10}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::stable_distinct(input, key_idx, KEEP_NONE); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } } TEST_F(StableDistinctKeepAny, SlicedListsOfStructs) { // Constructing a list of struct of two elements // 0. [] == <- Don't care // 1. [] != <- Don't care // 2. Null == <- Don't care // 3. Null != <- Don't care // 4. [Null, Null] != <- Don't care // 5. [Null] == <- Don't care // 6. [Null] == <- Don't care // 7. [Null] != <- Don't care // 8. [{Null, Null}] != // 9. [{1,'a'}, {2,'b'}] != // 10. [{0,'a'}, {2,'b'}] != // 11. [{0,'a'}, {2,'c'}] == // 12. [{0,'a'}, {2,'c'}] != // 13. [{0,Null}] == // 14. [{0,Null}] != // 15. [{Null, 'b'}] == <- Don't care // 16. [{Null, 'b'}] <- Don't care auto const structs = [] { auto child1 = int32s_col{{XXX, XXX, XXX, XXX, XXX, null, 1, 2, 0, 2, 0, 2, 0, 2, 0, 0, null, null}, nulls_at({5, 16, 17})}; auto child2 = strings_col{{"" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*null*/, "a", "b", "a", "b", "a", "c", "a", "c", "" /*null*/, "" /*null*/, "b", "b"}, nulls_at({5, 14, 15})}; return structs_col{{child1, child2}, nulls_at({0, 1, 2, 3, 4})}; }(); auto const offsets = int32s_col{0, 0, 0, 0, 0, 2, 3, 4, 5, 6, 8, 10, 12, 14, 15, 16, 17, 18}; auto const null_it = nulls_at({2, 3}); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(null_it, null_it + 17); auto const keys = cudf::column_view(cudf::data_type(cudf::type_id::LIST), 17, nullptr, static_cast<cudf::bitmask_type const*>(null_mask.data()), null_count, 0, {offsets, structs}); auto const idx = int32s_col{1, 1, 2, 2, 3, 4, 4, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10}; auto const input_original = cudf::table_view{{idx, keys}}; auto const input = cudf::slice(input_original, {8, 15})[0]; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal. { auto const expect_map = int32s_col{8, 9, 10, 11, 13}; auto const expect_table = cudf::gather(input_original, expect_map); auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(*expect_table, *result); } // Nulls are unequal. { auto const expect_map = int32s_col{8, 9, 10, 11, 13, 14}; auto const expect_table = cudf::gather(input_original, expect_map); auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY, NULL_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(*expect_table, *result); } } TEST_F(StableDistinctKeepAny, ListsOfEmptyStructs) { // Column(s) used to test KEEP_ANY needs to have same rows in contiguous // groups for equivalent keys because KEEP_ANY is nondeterministic. // 0. [] == // 1. [] != // 2. Null == // 3. Null != // 4. [Null, Null] == // 5. [Null, Null] == // 6. [Null, Null] != // 7. [Null] == // 8. [Null] != // 9. [{}] == // 10. [{}] != // 11. [{}, {}] == // 12. [{}, {}] auto const structs_null_it = nulls_at({0, 1, 2, 3, 4, 5, 6, 7}); auto [structs_null_mask, structs_null_count] = cudf::test::detail::make_null_mask(structs_null_it, structs_null_it + 14); auto const structs = cudf::column_view(cudf::data_type(cudf::type_id::STRUCT), 14, nullptr, static_cast<cudf::bitmask_type const*>(structs_null_mask.data()), structs_null_count); auto const offsets = int32s_col{0, 0, 0, 0, 0, 2, 4, 6, 7, 8, 9, 10, 12, 14}; auto const lists_null_it = nulls_at({2, 3}); auto [lists_null_mask, lists_null_count] = cudf::test::detail::make_null_mask(lists_null_it, lists_null_it + 13); auto const keys = cudf::column_view(cudf::data_type(cudf::type_id::LIST), 13, nullptr, static_cast<cudf::bitmask_type const*>(lists_null_mask.data()), lists_null_count, 0, {offsets, structs}); auto const idx = int32s_col{1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6}; auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal. { auto const expect_map = int32s_col{0, 2, 4, 7, 9, 11}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } // Nulls are unequal. { auto const expect_map = int32s_col{0, 2, 3, 4, 5, 6, 7, 8, 9, 11}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY, NULL_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } } TEST_F(StableDistinctKeepAny, EmptyDeepList) { // Column(s) used to test KEEP_ANY needs to have same rows in contiguous // groups for equivalent keys because KEEP_ANY is nondeterministic. // List<List<int>>, where all lists are empty: // // 0. [] // 1. [] // 2. Null // 3. Null auto const keys = lists_col{{lists_col{}, lists_col{}, lists_col{}, lists_col{}}, nulls_at({2, 3})}; auto const idx = int32s_col{1, 1, 2, 2}; auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal. { auto const expect_map = int32s_col{0, 2}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } // Nulls are unequal. { auto const expect_map = int32s_col{0, 2, 3}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY, NULL_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } } TEST_F(StableDistinctKeepAny, StructsOfStructs) { // Column(s) used to test KEEP_ANY needs to have same rows in contiguous // groups for equivalent keys because KEEP_ANY is nondeterministic. // +-----------------+ // | s1{s2{a,b}, c} | // +-----------------+ // 0 | { {1, 1}, 5} | // 1 | { {1, 1}, 5} | // Same as 0 // 2 | { {1, 2}, 4} | // 3 | { Null, 6} | // 4 | { Null, 4} | // 5 | { Null, 4} | // Same as 4 // 6 | Null | // 7 | Null | // Same as 6 // 8 | { {2, 1}, 5} | auto s1 = [&] { auto a = int32s_col{1, 1, 1, XXX, XXX, XXX, XXX, XXX, 2}; auto b = int32s_col{1, 1, 2, XXX, XXX, XXX, XXX, XXX, 1}; auto s2 = structs_col{{a, b}, nulls_at({3, 4, 5})}; auto c = int32s_col{5, 5, 4, 6, 4, 4, XXX, XXX, 5}; std::vector<std::unique_ptr<cudf::column>> s1_children; s1_children.emplace_back(s2.release()); s1_children.emplace_back(c.release()); auto const null_it = nulls_at({6, 7}); return structs_col(std::move(s1_children), std::vector<bool>{null_it, null_it + 9}); }(); auto const idx = int32s_col{0, 0, 2, 3, 4, 4, 6, 6, 8}; auto const input = cudf::table_view{{idx, s1}}; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal. { auto const expect_map = int32s_col{0, 2, 3, 4, 6, 8}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } // Nulls are unequal. { auto const expect_map = int32s_col{0, 2, 3, 4, 4, 6, 6, 8}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY, NULL_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } } TEST_F(StableDistinctKeepAny, SlicedStructsOfStructs) { // Column(s) used to test KEEP_ANY needs to have same rows in contiguous // groups for equivalent keys because KEEP_ANY is nondeterministic. // +-----------------+ // | s1{s2{a,b}, c} | // +-----------------+ // 0 | { {1, 1}, 5} | // 1 | { {1, 1}, 5} | // Same as 0 // 2 | { {1, 2}, 4} | // 3 | { Null, 6} | // 4 | { Null, 4} | // 5 | { Null, 4} | // Same as 4 // 6 | Null | // 7 | Null | // Same as 6 // 8 | { {2, 1}, 5} | auto s1 = [&] { auto a = int32s_col{1, 1, XXX, XXX, XXX, XXX, 1, XXX, 2}; auto b = int32s_col{1, 2, XXX, XXX, XXX, XXX, 1, XXX, 1}; auto s2 = structs_col{{a, b}, nulls_at({3, 4, 5})}; auto c = int32s_col{5, 4, 6, 4, XXX, XXX, 5, 4, 5}; std::vector<std::unique_ptr<cudf::column>> s1_children; s1_children.emplace_back(s2.release()); s1_children.emplace_back(c.release()); auto const null_it = nulls_at({6, 7}); return structs_col(std::move(s1_children), std::vector<bool>{null_it, null_it + 9}); }(); auto const idx = int32s_col{0, 0, 2, 3, 4, 4, 6, 6, 8}; auto const input_original = cudf::table_view{{idx, s1}}; auto const input = cudf::slice(input_original, {1, 7})[0]; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal. { auto const expect_map = int32s_col{1, 2, 3, 4, 6}; auto const expect_table = cudf::gather(input_original, expect_map); auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } // Nulls are unequal. { auto const expect_map = int32s_col{1, 2, 3, 4, 4, 6}; auto const expect_table = cudf::gather(input_original, expect_map); auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY, NULL_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } } TEST_F(StableDistinctKeepAny, StructsOfLists) { // Column(s) used to test KEEP_ANY needs to have same rows in contiguous // groups for equivalent keys because KEEP_ANY is nondeterministic. auto const idx = int32s_col{1, 1, 2, 3, 4, 4, 4, 5, 5, 6}; auto const keys = [] { // All child columns are identical. auto child1 = lists_col{{1}, {1}, {1, 1}, {1, 2}, {2, 2}, {2, 2}, {2, 2}, {2}, {2}, {2, 1}}; auto child2 = lists_col{{1}, {1}, {1, 1}, {1, 2}, {2, 2}, {2, 2}, {2, 2}, {2}, {2}, {2, 1}}; auto child3 = lists_col{{1}, {1}, {1, 1}, {1, 2}, {2, 2}, {2, 2}, {2, 2}, {2}, {2}, {2, 1}}; return structs_col{{child1, child2, child3}}; }(); auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; auto const exp_idx = int32s_col{1, 2, 3, 4, 5, 6}; auto const exp_keys = [] { auto child1 = lists_col{{1}, {1, 1}, {1, 2}, {2, 2}, {2}, {2, 1}}; auto child2 = lists_col{{1}, {1, 1}, {1, 2}, {2, 2}, {2}, {2, 1}}; auto child3 = lists_col{{1}, {1, 1}, {1, 2}, {2, 2}, {2}, {2, 1}}; return structs_col{{child1, child2, child3}}; }(); auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } TEST_F(StableDistinctKeepFirstLastNone, StructsOfLists) { auto const idx = int32s_col{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto const keys = [] { // All child columns are identical. auto child1 = lists_col{{1}, {1, 1}, {1}, {1, 2}, {2, 2}, {2}, {2}, {2, 1}, {2, 2}, {2, 2}}; auto child2 = lists_col{{1}, {1, 1}, {1}, {1, 2}, {2, 2}, {2}, {2}, {2, 1}, {2, 2}, {2, 2}}; auto child3 = lists_col{{1}, {1, 1}, {1}, {1, 2}, {2, 2}, {2}, {2}, {2, 1}, {2, 2}, {2, 2}}; return structs_col{{child1, child2, child3}}; }(); auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP_FIRST { auto const expect_map = int32s_col{0, 1, 3, 4, 5, 7}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::stable_distinct(input, key_idx, KEEP_FIRST); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } // KEEP_LAST { auto const expect_map = int32s_col{1, 2, 3, 6, 7, 9}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::stable_distinct(input, key_idx, KEEP_LAST); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } // KEEP_NONE { auto const expect_map = int32s_col{1, 3, 7}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::stable_distinct(input, key_idx, KEEP_NONE); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } } TEST_F(StableDistinctKeepAny, SlicedStructsOfLists) { // Column(s) used to test KEEP_ANY needs to have same rows in contiguous // groups for equivalent keys because KEEP_ANY is nondeterministic. auto constexpr dont_care = int32_t{0}; auto const idx = int32s_col{dont_care, dont_care, 1, 1, 2, 3, 4, 4, 4, 5, 5, 6, dont_care}; auto const keys = [] { // All child columns are identical. auto child1 = lists_col{ {0, 0}, {0, 0}, {1}, {1}, {1, 1}, {1, 2}, {2, 2}, {2, 2}, {2, 2}, {2}, {2}, {2, 1}, {5, 5}}; auto child2 = lists_col{ {0, 0}, {0, 0}, {1}, {1}, {1, 1}, {1, 2}, {2, 2}, {2, 2}, {2, 2}, {2}, {2}, {2, 1}, {5, 5}}; auto child3 = lists_col{ {0, 0}, {0, 0}, {1}, {1}, {1, 1}, {1, 2}, {2, 2}, {2, 2}, {2, 2}, {2}, {2}, {2, 1}, {5, 5}}; return structs_col{{child1, child2, child3}}; }(); auto const input_original = cudf::table_view{{idx, keys}}; auto const input = cudf::slice(input_original, {2, 12})[0]; auto const key_idx = std::vector<cudf::size_type>{1}; auto const exp_idx = int32s_col{1, 2, 3, 4, 5, 6}; auto const exp_keys = [] { auto child1 = lists_col{{1}, {1, 1}, {1, 2}, {2, 2}, {2}, {2, 1}}; auto child2 = lists_col{{1}, {1, 1}, {1, 2}, {2, 2}, {2}, {2, 1}}; auto child3 = lists_col{{1}, {1, 1}, {1, 2}, {2, 2}, {2}, {2, 1}}; return structs_col{{child1, child2, child3}}; }(); auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::stable_distinct(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/stream_compaction/distinct_tests.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf/copying.hpp> #include <cudf/sorting.hpp> #include <cudf/stream_compaction.hpp> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> #include <cudf/types.hpp> #include <cmath> auto constexpr null{0}; // null at current level auto constexpr XXX{0}; // null pushed down from parent level auto constexpr NaN = std::numeric_limits<double>::quiet_NaN(); auto constexpr KEEP_ANY = cudf::duplicate_keep_option::KEEP_ANY; auto constexpr KEEP_FIRST = cudf::duplicate_keep_option::KEEP_FIRST; auto constexpr KEEP_LAST = cudf::duplicate_keep_option::KEEP_LAST; auto constexpr KEEP_NONE = cudf::duplicate_keep_option::KEEP_NONE; auto constexpr NULL_EQUAL = cudf::null_equality::EQUAL; auto constexpr NULL_UNEQUAL = cudf::null_equality::UNEQUAL; auto constexpr NAN_EQUAL = cudf::nan_equality::ALL_EQUAL; auto constexpr NAN_UNEQUAL = cudf::nan_equality::UNEQUAL; using int32s_col = cudf::test::fixed_width_column_wrapper<int32_t>; using floats_col = cudf::test::fixed_width_column_wrapper<float>; using lists_col = cudf::test::lists_column_wrapper<int32_t>; using strings_col = cudf::test::strings_column_wrapper; using structs_col = cudf::test::structs_column_wrapper; using cudf::nan_policy; using cudf::null_equality; using cudf::null_policy; using cudf::test::iterators::no_nulls; using cudf::test::iterators::null_at; using cudf::test::iterators::nulls_at; struct DistinctKeepAny : public cudf::test::BaseFixture {}; struct DistinctKeepFirstLastNone : public cudf::test::BaseFixture {}; TEST_F(DistinctKeepAny, StringKeyColumn) { // Column(s) used to test KEEP_ANY needs to have same rows for same keys because KEEP_ANY is // nondeterministic. auto const col = int32s_col{{5, null, null, 5, 5, 8, 1}, nulls_at({1, 2})}; auto const keys = strings_col{{"all", "new", "new", "all", "" /*NULL*/, "the", "strings"}, null_at(4)}; auto const input = cudf::table_view{{col, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; auto const exp_col_sort = int32s_col{{5, 5, null, 1, 8}, null_at(2)}; auto const exp_keys_sort = strings_col{{"" /*NULL*/, "all", "new", "strings", "the"}, null_at(0)}; auto const expected_sort = cudf::table_view{{exp_col_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_ANY); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } TEST_F(DistinctKeepFirstLastNone, StringKeyColumn) { // Column(s) used to test needs to have different rows for the same keys. auto const col = int32s_col{{0, null, 2, 3, 4, 5, 6}, null_at(1)}; auto const keys = strings_col{{"all", "new", "new", "all", "" /*NULL*/, "the", "strings"}, null_at(4)}; auto const input = cudf::table_view{{col, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP_FIRST { auto const exp_col_sort = int32s_col{{4, 0, null, 6, 5}, null_at(2)}; auto const exp_keys_sort = strings_col{{"" /*NULL*/, "all", "new", "strings", "the"}, null_at(0)}; auto const expected_sort = cudf::table_view{{exp_col_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_FIRST); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // KEEP_LAST { auto const exp_col_sort = int32s_col{{4, 3, 2, 6, 5}, no_nulls()}; auto const exp_keys_sort = strings_col{{"" /*NULL*/, "all", "new", "strings", "the"}, null_at(0)}; auto const expected_sort = cudf::table_view{{exp_col_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_LAST); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // KEEP_NONE { auto const exp_col_sort = int32s_col{{4, 6, 5}, no_nulls()}; auto const exp_keys_sort = strings_col{{"" /*NULL*/, "strings", "the"}, null_at(0)}; auto const expected_sort = cudf::table_view{{exp_col_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_NONE); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } } TEST_F(DistinctKeepAny, EmptyInputTable) { int32s_col col(std::initializer_list<int32_t>{}); cudf::table_view input{{col}}; std::vector<cudf::size_type> key_idx{0}; auto got = cudf::distinct(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(input, got->view()); } TEST_F(DistinctKeepAny, NoColumnInputTable) { cudf::table_view input{std::vector<cudf::column_view>()}; std::vector<cudf::size_type> key_idx{1, 2}; auto got = cudf::distinct(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(input, got->view()); } TEST_F(DistinctKeepAny, EmptyKeys) { int32s_col col{{5, 4, 3, 5, 8, 1}, {1, 0, 1, 1, 1, 1}}; int32s_col empty_col{}; cudf::table_view input{{col}}; std::vector<cudf::size_type> key_idx{}; auto got = cudf::distinct(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(cudf::table_view{{empty_col}}, got->view()); } TEST_F(DistinctKeepAny, NoNullsTable) { // Column(s) used to test KEEP_ANY needs to have same rows for same keys because KEEP_ANY is // nondeterministic. auto const col1 = int32s_col{6, 6, 6, 3, 5, 8, 5}; auto const col2 = floats_col{6, 6, 6, 3, 4, 9, 4}; auto const keys1 = int32s_col{20, 20, 20, 20, 19, 21, 9}; auto const keys2 = int32s_col{19, 19, 19, 20, 20, 9, 21}; auto const input = cudf::table_view{{col1, col2, keys1, keys2}}; auto const key_idx = std::vector<cudf::size_type>{2, 3}; auto const exp_col1_sort = int32s_col{5, 5, 6, 3, 8}; auto const exp_col2_sort = floats_col{4, 4, 6, 3, 9}; auto const exp_keys1_sort = int32s_col{9, 19, 20, 20, 21}; auto const exp_keys2_sort = int32s_col{21, 20, 19, 20, 9}; auto const expected_sort = cudf::table_view{{exp_col1_sort, exp_col2_sort, exp_keys1_sort, exp_keys2_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_ANY); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } TEST_F(DistinctKeepAny, NoNullsTableWithNaNs) { // Column(s) used to test KEEP_ANY needs to have same rows for same keys. auto const col1 = int32s_col{6, 6, 6, 1, 1, 1, 3, 5, 8, 5}; auto const col2 = floats_col{6, 6, 6, 1, 1, 1, 3, 4, 9, 4}; auto const keys1 = int32s_col{20, 20, 20, 15, 15, 15, 20, 19, 21, 9}; auto const keys2 = floats_col{19., 19., 19., NaN, NaN, NaN, 20., 20., 9., 21.}; auto const input = cudf::table_view{{col1, col2, keys1, keys2}}; auto const key_idx = std::vector<cudf::size_type>{2, 3}; // NaNs are unequal. { auto const exp_col1_sort = int32s_col{5, 1, 1, 1, 5, 6, 3, 8}; auto const exp_col2_sort = floats_col{4, 1, 1, 1, 4, 6, 3, 9}; auto const exp_keys1_sort = int32s_col{9, 15, 15, 15, 19, 20, 20, 21}; auto const exp_keys2_sort = floats_col{21., NaN, NaN, NaN, 20., 19., 20., 9.}; auto const expected_sort = cudf::table_view{{exp_col1_sort, exp_col2_sort, exp_keys1_sort, exp_keys2_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_ANY, NULL_EQUAL, NAN_UNEQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // NaNs are equal. { auto const exp_col1_sort = int32s_col{5, 1, 5, 6, 3, 8}; auto const exp_col2_sort = floats_col{4, 1, 4, 6, 3, 9}; auto const exp_keys1_sort = int32s_col{9, 15, 19, 20, 20, 21}; auto const exp_keys2_sort = floats_col{21., NaN, 20., 19., 20., 9.}; auto const expected_sort = cudf::table_view{{exp_col1_sort, exp_col2_sort, exp_keys1_sort, exp_keys2_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_ANY, NULL_EQUAL, NAN_EQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } } TEST_F(DistinctKeepFirstLastNone, NoNullsTable) { // Column(s) used to test needs to have different rows for the same keys. auto const col1 = int32s_col{0, 1, 2, 3, 4, 5, 6}; auto const col2 = floats_col{10, 11, 12, 13, 14, 15, 16}; auto const keys1 = int32s_col{20, 20, 20, 20, 19, 21, 9}; auto const keys2 = int32s_col{19, 19, 19, 20, 20, 9, 21}; auto const input = cudf::table_view{{col1, col2, keys1, keys2}}; auto const key_idx = std::vector<cudf::size_type>{2, 3}; // KEEP_FIRST { auto const exp_col1_sort = int32s_col{6, 4, 0, 3, 5}; auto const exp_col2_sort = floats_col{16, 14, 10, 13, 15}; auto const exp_keys1_sort = int32s_col{9, 19, 20, 20, 21}; auto const exp_keys2_sort = int32s_col{21, 20, 19, 20, 9}; auto const expected_sort = cudf::table_view{{exp_col1_sort, exp_col2_sort, exp_keys1_sort, exp_keys2_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_FIRST); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // KEEP_LAST { auto const exp_col1_sort = int32s_col{6, 4, 2, 3, 5}; auto const exp_col2_sort = floats_col{16, 14, 12, 13, 15}; auto const exp_keys1_sort = int32s_col{9, 19, 20, 20, 21}; auto const exp_keys2_sort = int32s_col{21, 20, 19, 20, 9}; auto const expected_sort = cudf::table_view{{exp_col1_sort, exp_col2_sort, exp_keys1_sort, exp_keys2_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_LAST); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // KEEP_NONE { auto const exp_col1_sort = int32s_col{6, 4, 3, 5}; auto const exp_col2_sort = floats_col{16, 14, 13, 15}; auto const exp_keys1_sort = int32s_col{9, 19, 20, 21}; auto const exp_keys2_sort = int32s_col{21, 20, 20, 9}; auto const expected_sort = cudf::table_view{{exp_col1_sort, exp_col2_sort, exp_keys1_sort, exp_keys2_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_NONE); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } } TEST_F(DistinctKeepAny, SlicedNoNullsTable) { auto constexpr dont_care = int32_t{0}; // Column(s) used to test KEEP_ANY needs to have same rows for same keys because KEEP_ANY is // nondeterministic. auto const col1 = int32s_col{dont_care, dont_care, 6, 6, 6, 3, 5, 8, 5, dont_care}; auto const col2 = floats_col{dont_care, dont_care, 6, 6, 6, 3, 4, 9, 4, dont_care}; auto const keys1 = int32s_col{dont_care, dont_care, 20, 20, 20, 20, 19, 21, 9, dont_care}; auto const keys2 = int32s_col{dont_care, dont_care, 19, 19, 19, 20, 20, 9, 21, dont_care}; auto const input_original = cudf::table_view{{col1, col2, keys1, keys2}}; auto const input = cudf::slice(input_original, {2, 9})[0]; auto const key_idx = std::vector<cudf::size_type>{2, 3}; auto const exp_col1_sort = int32s_col{5, 5, 6, 3, 8}; auto const exp_col2_sort = floats_col{4, 4, 6, 3, 9}; auto const exp_keys1_sort = int32s_col{9, 19, 20, 20, 21}; auto const exp_keys2_sort = int32s_col{21, 20, 19, 20, 9}; auto const expected_sort = cudf::table_view{{exp_col1_sort, exp_col2_sort, exp_keys1_sort, exp_keys2_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_ANY); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } TEST_F(DistinctKeepFirstLastNone, SlicedNoNullsTable) { auto constexpr dont_care = int32_t{0}; // Column(s) used to test needs to have different rows for the same keys. // clang-format off auto const col1 = int32s_col{0, 1, 2, // <- don't care 3, 4, 5, 6, 7, 8, 9, dont_care}; auto const col2 = floats_col{10, 11, 12, // <- don't care 13, 14, 15, 16, 17, 18, 19, dont_care}; auto const keys1 = int32s_col{20, 20, 20, // <- don't care 20, 20, 20, 20, 19, 21, 9, dont_care}; auto const keys2 = int32s_col{19, 19, 19, // <- don't care 19, 19, 19, 20, 20, 9, 21, dont_care}; // clang-format on auto const input_original = cudf::table_view{{col1, col2, keys1, keys2}}; auto const input = cudf::slice(input_original, {3, 10})[0]; auto const key_idx = std::vector<cudf::size_type>{2, 3}; // KEEP_FIRST { auto const exp_col1_sort = int32s_col{9, 7, 3, 6, 8}; auto const exp_col2_sort = floats_col{19, 17, 13, 16, 18}; auto const exp_keys1_sort = int32s_col{9, 19, 20, 20, 21}; auto const exp_keys2_sort = int32s_col{21, 20, 19, 20, 9}; auto const expected_sort = cudf::table_view{{exp_col1_sort, exp_col2_sort, exp_keys1_sort, exp_keys2_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_FIRST); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // KEEP_LAST { auto const exp_col1_sort = int32s_col{9, 7, 5, 6, 8}; auto const exp_col2_sort = floats_col{19, 17, 15, 16, 18}; auto const exp_keys1_sort = int32s_col{9, 19, 20, 20, 21}; auto const exp_keys2_sort = int32s_col{21, 20, 19, 20, 9}; auto const expected_sort = cudf::table_view{{exp_col1_sort, exp_col2_sort, exp_keys1_sort, exp_keys2_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_LAST); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // KEEP_NONE { auto const exp_col1_sort = int32s_col{9, 7, 6, 8}; auto const exp_col2_sort = floats_col{19, 17, 16, 18}; auto const exp_keys1_sort = int32s_col{9, 19, 20, 21}; auto const exp_keys2_sort = int32s_col{21, 20, 20, 9}; auto const expected_sort = cudf::table_view{{exp_col1_sort, exp_col2_sort, exp_keys1_sort, exp_keys2_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_NONE); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } } TEST_F(DistinctKeepAny, InputWithNulls) { // Column(s) used to test KEEP_ANY needs to have same rows for same keys because KEEP_ANY is // nondeterministic. auto const col = int32s_col{5, 4, 4, 1, 8, 1}; auto const keys = int32s_col{{20, null, null, 19, 21, 19}, nulls_at({1, 2})}; auto const input = cudf::table_view{{col, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal. { auto const exp_col_sort = int32s_col{4, 1, 5, 8}; auto const exp_keys_sort = int32s_col{{null, 19, 20, 21}, null_at(0)}; auto const expected_sort = cudf::table_view{{exp_col_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_ANY); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // Nulls are unequal. { auto const exp_col_sort = int32s_col{4, 4, 1, 5, 8}; auto const exp_keys_sort = int32s_col{{null, null, 19, 20, 21}, nulls_at({0, 1})}; auto const expected_sort = cudf::table_view{{exp_col_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_ANY, NULL_UNEQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } } TEST_F(DistinctKeepAny, InputWithNullsAndNaNs) { auto constexpr null{0.0}; // shadow the global `null` variable of type int // Column(s) used to test KEEP_ANY needs to have same rows for same keys because KEEP_ANY is // nondeterministic. auto const col = int32s_col{5, 4, 1, 1, 1, 4, 1, 8, 1}; auto const keys = floats_col{{20., null, NaN, NaN, NaN, null, 19., 21., 19.}, nulls_at({1, 5})}; auto const input = cudf::table_view{{col, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal, NaNs are unequal. { auto const exp_col_sort = int32s_col{4, 1, 5, 8, 1, 1, 1}; auto const exp_keys_sort = floats_col{{null, 19., 20., 21., NaN, NaN, NaN}, null_at(0)}; auto const expected_sort = cudf::table_view{{exp_col_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_ANY, NULL_EQUAL, NAN_UNEQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // Nulls are equal, NaNs are equal. { auto const exp_col_sort = int32s_col{4, 1, 5, 8, 1}; auto const exp_keys_sort = floats_col{{null, 19., 20., 21., NaN}, null_at(0)}; auto const expected_sort = cudf::table_view{{exp_col_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_ANY, NULL_EQUAL, NAN_EQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // Nulls are unequal, NaNs are unequal. { auto const exp_col_sort = int32s_col{4, 4, 1, 5, 8, 1, 1, 1}; auto const exp_keys_sort = floats_col{{null, null, 19., 20., 21., NaN, NaN, NaN}, nulls_at({0, 1})}; auto const expected_sort = cudf::table_view{{exp_col_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_ANY, NULL_UNEQUAL, NAN_UNEQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // Nulls are unequal, NaNs are equal. { auto const exp_col_sort = int32s_col{4, 4, 1, 5, 8, 1}; auto const exp_keys_sort = floats_col{{null, null, 19., 20., 21., NaN}, nulls_at({0, 1})}; auto const expected_sort = cudf::table_view{{exp_col_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_ANY, NULL_UNEQUAL, NAN_EQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } } TEST_F(DistinctKeepFirstLastNone, InputWithNullsEqual) { // Column(s) used to test needs to have different rows for the same keys. auto const col = int32s_col{0, 1, 2, 3, 4, 5, 6}; auto const keys = int32s_col{{20, null, null, 19, 21, 19, 22}, nulls_at({1, 2})}; auto const input = cudf::table_view{{col, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP_FIRST { auto const exp_col_sort = int32s_col{1, 3, 0, 4, 6}; auto const exp_keys_sort = int32s_col{{null, 19, 20, 21, 22}, null_at(0)}; auto const expected_sort = cudf::table_view{{exp_col_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_FIRST, NULL_EQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // KEEP_LAST { auto const exp_col_sort = int32s_col{2, 5, 0, 4, 6}; auto const exp_keys_sort = int32s_col{{null, 19, 20, 21, 22}, null_at(0)}; auto const expected_sort = cudf::table_view{{exp_col_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_LAST, NULL_EQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // KEEP_NONE { auto const exp_col_sort = int32s_col{0, 4, 6}; auto const exp_keys_sort = int32s_col{{20, 21, 22}, no_nulls()}; auto const expected_sort = cudf::table_view{{exp_col_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_NONE, NULL_EQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select(key_idx)); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } } TEST_F(DistinctKeepFirstLastNone, InputWithNullsUnequal) { // Column(s) used to test needs to have different rows for the same keys. auto const col = int32s_col{0, 1, 2, 3, 4, 5, 6, 7}; auto const keys = int32s_col{{20, null, null, 19, 21, 19, 22, 20}, nulls_at({1, 2})}; auto const input = cudf::table_view{{col, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP_FIRST { auto const exp_col_sort = int32s_col{0, 1, 2, 3, 4, 6}; auto const exp_keys_sort = int32s_col{{20, null, null, 19, 21, 22}, nulls_at({1, 2})}; auto const expected_sort = cudf::table_view{{exp_col_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_FIRST, NULL_UNEQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // KEEP_LAST { auto const exp_col_sort = int32s_col{1, 2, 4, 5, 6, 7}; auto const exp_keys_sort = int32s_col{{null, null, 21, 19, 22, 20}, nulls_at({0, 1})}; auto const expected_sort = cudf::table_view{{exp_col_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_LAST, NULL_UNEQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // KEEP_NONE { auto const exp_col_sort = int32s_col{1, 2, 4, 6}; auto const exp_keys_sort = int32s_col{{null, null, 21, 22}, nulls_at({0, 1})}; auto const expected_sort = cudf::table_view{{exp_col_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_NONE, NULL_UNEQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } } TEST_F(DistinctKeepFirstLastNone, InputWithNaNsEqual) { // Column(s) used to test needs to have different rows for the same keys. auto const col = int32s_col{0, 1, 2, 3, 4, 5, 6}; auto const keys = floats_col{20., NaN, NaN, 19., 21., 19., 22.}; auto const input = cudf::table_view{{col, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP_FIRST { auto const exp_col_sort = int32s_col{0, 1, 3, 4, 6}; auto const exp_keys_sort = floats_col{20., NaN, 19., 21., 22.}; auto const expected_sort = cudf::table_view{{exp_col_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_FIRST, NULL_EQUAL, NAN_EQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // KEEP_LAST { auto const exp_col_sort = int32s_col{0, 2, 4, 5, 6}; auto const exp_keys_sort = floats_col{20., NaN, 21., 19., 22.}; auto const expected_sort = cudf::table_view{{exp_col_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_LAST, NULL_EQUAL, NAN_EQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // KEEP_NONE { auto const exp_col_sort = int32s_col{0, 4, 6}; auto const exp_keys_sort = floats_col{20., 21., 22.}; auto const expected_sort = cudf::table_view{{exp_col_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_NONE, NULL_EQUAL, NAN_EQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } } TEST_F(DistinctKeepFirstLastNone, InputWithNaNsUnequal) { // Column(s) used to test needs to have different rows for the same keys. auto const col = int32s_col{0, 1, 2, 3, 4, 5, 6, 7}; auto const keys = floats_col{20., NaN, NaN, 19., 21., 19., 22., 20.}; auto const input = cudf::table_view{{col, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP_FIRST { auto const exp_col_sort = int32s_col{0, 1, 2, 3, 4, 6}; auto const exp_keys_sort = floats_col{20., NaN, NaN, 19., 21., 22.}; auto const expected_sort = cudf::table_view{{exp_col_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_FIRST, NULL_UNEQUAL, NAN_UNEQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // KEEP_LAST { auto const exp_col_sort = int32s_col{1, 2, 4, 5, 6, 7}; auto const exp_keys_sort = floats_col{NaN, NaN, 21., 19., 22., 20.}; auto const expected_sort = cudf::table_view{{exp_col_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_LAST, NULL_UNEQUAL, NAN_UNEQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // KEEP_NONE { auto const exp_col_sort = int32s_col{1, 2, 4, 6}; auto const exp_keys_sort = floats_col{NaN, NaN, 21., 22.}; auto const expected_sort = cudf::table_view{{exp_col_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_NONE, NULL_UNEQUAL, NAN_UNEQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } } TEST_F(DistinctKeepAny, BasicLists) { // Column(s) used to test KEEP_ANY needs to have same rows for same keys because KEEP_ANY is // nondeterministic. // clang-format off auto const idx = int32s_col{ 0, 0, 1, 2, 1, 3, 4, 5, 5, 6, 4, 4}; auto const keys = lists_col{{}, {}, {1}, {1, 1}, {1}, {1, 2}, {2, 2}, {2}, {2}, {2, 1}, {2, 2}, {2, 2}}; // clang-format on auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; auto const exp_idx_sort = int32s_col{0, 1, 2, 3, 4, 5, 6}; auto const exp_keys_sort = lists_col{{}, {1}, {1, 1}, {1, 2}, {2, 2}, {2}, {2, 1}}; auto const expected_sort = cudf::table_view{{exp_idx_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_ANY); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } TEST_F(DistinctKeepFirstLastNone, BasicLists) { // Column(s) used to test needs to have different rows for the same keys. // clang-format off auto const idx = int32s_col{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; auto const keys = lists_col{{}, {}, {1}, {1, 1}, {1}, {1, 2}, {2, 2}, {2}, {2}, {2, 1}, {2, 2}, {2, 2}}; // clang-format on auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP_FIRST { auto const exp_idx_sort = int32s_col{0, 2, 3, 5, 6, 7, 9}; auto const exp_keys_sort = lists_col{{}, {1}, {1, 1}, {1, 2}, {2, 2}, {2}, {2, 1}}; auto const expected_sort = cudf::table_view{{exp_idx_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_FIRST); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // KEEP_LAST { auto const exp_idx_sort = int32s_col{1, 3, 4, 5, 8, 9, 11}; auto const exp_keys_sort = lists_col{{}, {1, 1}, {1}, {1, 2}, {2}, {2, 1}, {2, 2}}; auto const expected_sort = cudf::table_view{{exp_idx_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_LAST); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // KEEP_NONE { auto const exp_idx_sort = int32s_col{3, 5, 9}; auto const exp_keys_sort = lists_col{{1, 1}, {1, 2}, {2, 1}}; auto const expected_sort = cudf::table_view{{exp_idx_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_NONE); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } } TEST_F(DistinctKeepAny, SlicedBasicLists) { auto constexpr dont_care = int32_t{0}; // Column(s) used to test KEEP_ANY needs to have same rows for same keys because KEEP_ANY is // nondeterministic. auto const idx = int32s_col{dont_care, dont_care, 1, 2, 1, 3, 4, 5, 5, 6, 4, 4, dont_care}; auto const keys = lists_col{ {0, 0}, {0, 0}, {1}, {1, 1}, {1}, {1, 2}, {2, 2}, {2}, {2}, {2, 1}, {2, 2}, {2, 2}, {5, 5}}; auto const input_original = cudf::table_view{{idx, keys}}; auto const input = cudf::slice(input_original, {2, 12})[0]; auto const key_idx = std::vector<cudf::size_type>{1}; auto const exp_idx_sort = int32s_col{1, 2, 3, 4, 5, 6}; auto const exp_val_sort = lists_col{{1}, {1, 1}, {1, 2}, {2, 2}, {2}, {2, 1}}; auto const expected_sort = cudf::table_view{{exp_idx_sort, exp_val_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_ANY); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } TEST_F(DistinctKeepAny, NullableLists) { // Column(s) used to test KEEP_ANY needs to have same rows for same keys because KEEP_ANY is // nondeterministic. auto const idx = int32s_col{0, 0, 1, 1, 4, 5, 5, 6, 4, 4, 6}; auto const keys = lists_col{{{}, {}, {1}, {1}, {2, 2}, {2}, {2}, {} /*NULL*/, {2, 2}, {2, 2}, {} /*NULL*/}, nulls_at({7, 10})}; auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal. { auto const exp_idx_sort = int32s_col{0, 1, 4, 5, 6}; auto const exp_keys_sort = lists_col{{{}, {1}, {2, 2}, {2}, {} /*NULL*/}, null_at(4)}; auto const expected_sort = cudf::table_view{{exp_idx_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_ANY); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // Nulls are unequal. { auto const exp_idx_sort = int32s_col{0, 1, 4, 5, 6, 6}; auto const exp_keys_sort = lists_col{{{}, {1}, {2, 2}, {2}, {} /*NULL*/, {} /*NULL*/}, nulls_at({4, 5})}; auto const expected_sort = cudf::table_view{{exp_idx_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_ANY, NULL_UNEQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } } TEST_F(DistinctKeepFirstLastNone, ListsWithNullsEqual) { // Column(s) used to test needs to have different rows for the same keys. // clang-format off auto const idx = int32s_col{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; auto const keys = lists_col{{{}, {}, {1}, {1}, {2, 2}, {2}, {2}, {} /*NULL*/, {2, 2}, {2, 2}, {} /*NULL*/}, nulls_at({7, 10})}; // clang-format on auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP_FIRST { auto const exp_idx_sort = int32s_col{0, 2, 4, 5, 7}; auto const exp_keys_sort = lists_col{{{}, {1}, {2, 2}, {2}, {} /*NULL*/}, null_at(4)}; auto const expected_sort = cudf::table_view{{exp_idx_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_FIRST, NULL_EQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // KEEP_LAST { auto const exp_idx_sort = int32s_col{1, 3, 6, 9, 10}; auto const exp_keys_sort = lists_col{{{}, {1}, {2}, {2, 2}, {} /*NULL*/}, null_at(4)}; auto const expected_sort = cudf::table_view{{exp_idx_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_LAST, NULL_EQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // KEEP_NONE { auto const exp_idx = int32s_col{}; auto const exp_keys = lists_col{}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::distinct(input, key_idx, KEEP_NONE, NULL_EQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } } TEST_F(DistinctKeepFirstLastNone, ListsWithNullsUnequal) { // Column(s) used to test needs to have different rows for the same keys. // clang-format off auto const idx = int32s_col{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; auto const keys = lists_col{{{}, {}, {1}, {1}, {2, 2}, {2}, {2}, {} /*NULL*/, {2, 2}, {2, 2}, {} /*NULL*/}, nulls_at({7, 10})}; // clang-format on auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP_FIRST { auto const exp_idx_sort = int32s_col{0, 2, 4, 5, 7, 10}; auto const exp_keys_sort = lists_col{{{}, {1}, {2, 2}, {2}, {} /*NULL*/, {} /*NULL*/}, nulls_at({4, 5})}; auto const expected_sort = cudf::table_view{{exp_idx_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_FIRST, NULL_UNEQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // KEEP_LAST { auto const exp_idx_sort = int32s_col{1, 3, 6, 7, 9, 10}; auto const exp_keys_sort = lists_col{{{}, {1}, {2}, {} /*NULL*/, {2, 2}, {} /*NULL*/}, nulls_at({3, 5})}; auto const expected_sort = cudf::table_view{{exp_idx_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_LAST, NULL_UNEQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } // KEEP_NONE { auto const exp_idx_sort = int32s_col{7, 10}; auto const exp_keys_sort = lists_col{{lists_col{} /*NULL*/, lists_col{} /*NULL*/}, nulls_at({0, 1})}; auto const expected_sort = cudf::table_view{{exp_idx_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_NONE, NULL_UNEQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } } TEST_F(DistinctKeepAny, ListsOfStructs) { // Constructing a list of structs of two elements // 0. [] == // 1. [] != // 2. Null == // 3. Null != // 4. [Null, Null] != // 5. [Null] == // 6. [Null] == // 7. [Null] != // 8. [{Null, Null}] != // 9. [{1,'a'}, {2,'b'}] != // 10. [{0,'a'}, {2,'b'}] != // 11. [{0,'a'}, {2,'c'}] == // 12. [{0,'a'}, {2,'c'}] != // 13. [{0,Null}] == // 14. [{0,Null}] != // 15. [{Null, 'b'}] == // 16. [{Null, 'b'}] auto const structs = [] { auto child1 = int32s_col{{XXX, XXX, XXX, XXX, XXX, null, 1, 2, 0, 2, 0, 2, 0, 2, 0, 0, null, null}, nulls_at({5, 16, 17})}; auto child2 = strings_col{{"" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*null*/, "a", "b", "a", "b", "a", "c", "a", "c", "" /*null*/, "" /*null*/, "b", "b"}, nulls_at({5, 14, 15})}; return structs_col{{child1, child2}, nulls_at({0, 1, 2, 3, 4})}; }(); auto const offsets = int32s_col{0, 0, 0, 0, 0, 2, 3, 4, 5, 6, 8, 10, 12, 14, 15, 16, 17, 18}; auto const null_it = nulls_at({2, 3}); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(null_it, null_it + 17); auto const keys = cudf::column_view(cudf::data_type(cudf::type_id::LIST), 17, nullptr, static_cast<cudf::bitmask_type const*>(null_mask.data()), null_count, 0, {offsets, structs}); auto const idx = int32s_col{1, 1, 2, 2, 3, 4, 4, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10}; auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal. { auto const expect_map = int32s_col{0, 2, 4, 5, 8, 9, 10, 11, 13, 15}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::distinct(input, key_idx, KEEP_ANY); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result_sort); } // Nulls are unequal. { auto const expect_map = int32s_col{0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::distinct(input, key_idx, KEEP_ANY, NULL_UNEQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result_sort); } } TEST_F(DistinctKeepFirstLastNone, ListsOfStructs) { // Constructing a list of structs of two elements // 0. [] == // 1. [] != // 2. Null == // 3. Null != // 4. [Null, Null] != // 5. [Null] == // 6. [Null] == // 7. [Null] != // 8. [{Null, Null}] != // 9. [{1,'a'}, {2,'b'}] != // 10. [{0,'a'}, {2,'b'}] != // 11. [{0,'a'}, {2,'c'}] == // 12. [{0,'a'}, {2,'c'}] != // 13. [{0,Null}] == // 14. [{0,Null}] != // 15. [{Null, 'b'}] == // 16. [{Null, 'b'}] auto const structs = [] { auto child1 = int32s_col{{XXX, XXX, XXX, XXX, XXX, null, 1, 2, 0, 2, 0, 2, 0, 2, 0, 0, null, null}, nulls_at({5, 16, 17})}; auto child2 = strings_col{{"" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*null*/, "a", "b", "a", "b", "a", "c", "a", "c", "" /*null*/, "" /*null*/, "b", "b"}, nulls_at({5, 14, 15})}; return structs_col{{child1, child2}, nulls_at({0, 1, 2, 3, 4})}; }(); auto const offsets = int32s_col{0, 0, 0, 0, 0, 2, 3, 4, 5, 6, 8, 10, 12, 14, 15, 16, 17, 18}; auto const null_it = nulls_at({2, 3}); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(null_it, null_it + 17); auto const keys = cudf::column_view(cudf::data_type(cudf::type_id::LIST), 17, nullptr, static_cast<cudf::bitmask_type const*>(null_mask.data()), null_count, 0, {offsets, structs}); auto const idx = int32s_col{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP_FIRST { auto const expect_map = int32s_col{0, 2, 4, 5, 8, 9, 10, 11, 13, 15}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::distinct(input, key_idx, KEEP_FIRST); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result_sort); } // KEEP_LAST { auto const expect_map = int32s_col{1, 3, 4, 7, 8, 9, 10, 12, 14, 16}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::distinct(input, key_idx, KEEP_LAST); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result_sort); } // KEEP_NONE { auto const expect_map = int32s_col{4, 8, 9, 10}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::distinct(input, key_idx, KEEP_NONE); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result_sort); } } TEST_F(DistinctKeepAny, SlicedListsOfStructs) { // Constructing a list of struct of two elements // 0. [] == <- Don't care // 1. [] != <- Don't care // 2. Null == <- Don't care // 3. Null != <- Don't care // 4. [Null, Null] != <- Don't care // 5. [Null] == <- Don't care // 6. [Null] == <- Don't care // 7. [Null] != <- Don't care // 8. [{Null, Null}] != // 9. [{1,'a'}, {2,'b'}] != // 10. [{0,'a'}, {2,'b'}] != // 11. [{0,'a'}, {2,'c'}] == // 12. [{0,'a'}, {2,'c'}] != // 13. [{0,Null}] == // 14. [{0,Null}] != // 15. [{Null, 'b'}] == <- Don't care // 16. [{Null, 'b'}] <- Don't care auto const structs = [] { auto child1 = int32s_col{{XXX, XXX, XXX, XXX, XXX, null, 1, 2, 0, 2, 0, 2, 0, 2, 0, 0, null, null}, nulls_at({5, 16, 17})}; auto child2 = strings_col{{"" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*null*/, "a", "b", "a", "b", "a", "c", "a", "c", "" /*null*/, "" /*null*/, "b", "b"}, nulls_at({5, 14, 15})}; return structs_col{{child1, child2}, nulls_at({0, 1, 2, 3, 4})}; }(); auto const offsets = int32s_col{0, 0, 0, 0, 0, 2, 3, 4, 5, 6, 8, 10, 12, 14, 15, 16, 17, 18}; auto const null_it = nulls_at({2, 3}); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(null_it, null_it + 17); auto const keys = cudf::column_view(cudf::data_type(cudf::type_id::LIST), 17, nullptr, static_cast<cudf::bitmask_type const*>(null_mask.data()), null_count, 0, {offsets, structs}); auto const idx = int32s_col{1, 1, 2, 2, 3, 4, 4, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10}; auto const input_original = cudf::table_view{{idx, keys}}; auto const input = cudf::slice(input_original, {8, 15})[0]; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal. { auto const expect_map = int32s_col{8, 9, 10, 11, 13}; auto const expect_table = cudf::gather(input_original, expect_map); auto const result = cudf::distinct(input, key_idx, KEEP_ANY); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(*expect_table, *result_sort); } // Nulls are unequal. { auto const expect_map = int32s_col{8, 9, 10, 11, 13, 14}; auto const expect_table = cudf::gather(input_original, expect_map); auto const result = cudf::distinct(input, key_idx, KEEP_ANY, NULL_UNEQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(*expect_table, *result_sort); } } TEST_F(DistinctKeepAny, ListsOfEmptyStructs) { // 0. [] == // 1. [] != // 2. Null == // 3. Null != // 4. [Null, Null] == // 5. [Null, Null] == // 6. [Null, Null] != // 7. [Null] == // 8. [Null] != // 9. [{}] == // 10. [{}] != // 11. [{}, {}] == // 12. [{}, {}] auto const structs_null_it = nulls_at({0, 1, 2, 3, 4, 5, 6, 7}); auto [structs_null_mask, structs_null_count] = cudf::test::detail::make_null_mask(structs_null_it, structs_null_it + 14); auto const structs = cudf::column_view(cudf::data_type(cudf::type_id::STRUCT), 14, nullptr, static_cast<cudf::bitmask_type const*>(structs_null_mask.data()), structs_null_count); auto const offsets = int32s_col{0, 0, 0, 0, 0, 2, 4, 6, 7, 8, 9, 10, 12, 14}; auto const lists_null_it = nulls_at({2, 3}); auto [lists_null_mask, lists_null_count] = cudf::test::detail::make_null_mask(lists_null_it, lists_null_it + 13); auto const keys = cudf::column_view(cudf::data_type(cudf::type_id::LIST), 13, nullptr, static_cast<cudf::bitmask_type const*>(lists_null_mask.data()), lists_null_count, 0, {offsets, structs}); auto const idx = int32s_col{1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6}; auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal. { auto const expect_map = int32s_col{0, 2, 4, 7, 9, 11}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::distinct(input, key_idx, KEEP_ANY); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result_sort); } // Nulls are unequal. { auto const expect_map = int32s_col{0, 2, 3, 4, 5, 6, 7, 8, 9, 11}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::distinct(input, key_idx, KEEP_ANY, NULL_UNEQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result_sort); } } TEST_F(DistinctKeepAny, EmptyDeepList) { // List<List<int>>, where all lists are empty: // // 0. [] // 1. [] // 2. Null // 3. Null auto const keys = lists_col{{lists_col{}, lists_col{}, lists_col{}, lists_col{}}, nulls_at({2, 3})}; auto const idx = int32s_col{1, 1, 2, 2}; auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal. { auto const expect_map = int32s_col{0, 2}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::distinct(input, key_idx, KEEP_ANY); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result_sort); } // Nulls are unequal. { auto const expect_map = int32s_col{0, 2, 3}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::distinct(input, key_idx, KEEP_ANY, NULL_UNEQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result_sort); } } TEST_F(DistinctKeepAny, StructsOfStructs) { // +-----------------+ // | s1{s2{a,b}, c} | // +-----------------+ // 0 | { {1, 1}, 5} | // 1 | { {1, 2}, 4} | // 2 | { Null, 6} | // 3 | { Null, 4} | // 4 | Null | // 5 | Null | // Same as 4 // 6 | { {1, 1}, 5} | // Same as 0 // 7 | { Null, 4} | // Same as 3 // 8 | { {2, 1}, 5} | auto s1 = [&] { auto a = int32s_col{1, 1, XXX, XXX, XXX, XXX, 1, XXX, 2}; auto b = int32s_col{1, 2, XXX, XXX, XXX, XXX, 1, XXX, 1}; auto s2 = structs_col{{a, b}, nulls_at({2, 3, 7})}; auto c = int32s_col{5, 4, 6, 4, XXX, XXX, 5, 4, 5}; std::vector<std::unique_ptr<cudf::column>> s1_children; s1_children.emplace_back(s2.release()); s1_children.emplace_back(c.release()); auto const null_it = nulls_at({4, 5}); return structs_col(std::move(s1_children), std::vector<bool>{null_it, null_it + 9}); }(); auto const idx = int32s_col{0, 1, 2, 3, 4, 4, 0, 3, 8}; auto const input = cudf::table_view{{idx, s1}}; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal. { auto const expect_map = int32s_col{0, 1, 2, 3, 4, 8}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::distinct(input, key_idx, KEEP_ANY); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result_sort); } // Nulls are unequal. { auto const expect_map = int32s_col{0, 1, 2, 3, 7, 4, 5, 8}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::distinct(input, key_idx, KEEP_ANY, NULL_UNEQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result_sort); } } TEST_F(DistinctKeepAny, SlicedStructsOfStructs) { // +-----------------+ // | s1{s2{a,b}, c} | // +-----------------+ // 0 | { {1, 1}, 5} | // 1 | { {1, 2}, 4} | // 2 | { Null, 6} | // 3 | { Null, 4} | // 4 | Null | // 5 | Null | // Same as 4 // 6 | { {1, 1}, 5} | // Same as 0 // 7 | { Null, 4} | // Same as 3 // 8 | { {2, 1}, 5} | auto s1 = [&] { auto a = int32s_col{1, 1, XXX, XXX, XXX, XXX, 1, XXX, 2}; auto b = int32s_col{1, 2, XXX, XXX, XXX, XXX, 1, XXX, 1}; auto s2 = structs_col{{a, b}, nulls_at({2, 3, 7})}; auto c = int32s_col{5, 4, 6, 4, XXX, XXX, 5, 4, 5}; std::vector<std::unique_ptr<cudf::column>> s1_children; s1_children.emplace_back(s2.release()); s1_children.emplace_back(c.release()); auto const null_it = nulls_at({4, 5}); return structs_col(std::move(s1_children), std::vector<bool>{null_it, null_it + 9}); }(); auto const idx = int32s_col{0, 1, 2, 3, 4, 4, 0, 3, 8}; auto const input_original = cudf::table_view{{idx, s1}}; auto const input = cudf::slice(input_original, {1, 7})[0]; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal. { auto const expect_map = int32s_col{6, 1, 2, 3, 4}; auto const expect_table = cudf::gather(input_original, expect_map); auto const result = cudf::distinct(input, key_idx, KEEP_ANY); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result_sort); } // Nulls are unequal. { auto const expect_map = int32s_col{6, 1, 2, 3, 4, 5}; auto const expect_table = cudf::gather(input_original, expect_map); auto const result = cudf::distinct(input, key_idx, KEEP_ANY, NULL_UNEQUAL); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result_sort); } } TEST_F(DistinctKeepAny, StructsOfLists) { auto const idx = int32s_col{1, 2, 1, 3, 4, 5, 5, 6, 4, 4}; auto const keys = [] { // All child columns are identical. auto child1 = lists_col{{1}, {1, 1}, {1}, {1, 2}, {2, 2}, {2}, {2}, {2, 1}, {2, 2}, {2, 2}}; auto child2 = lists_col{{1}, {1, 1}, {1}, {1, 2}, {2, 2}, {2}, {2}, {2, 1}, {2, 2}, {2, 2}}; auto child3 = lists_col{{1}, {1, 1}, {1}, {1, 2}, {2, 2}, {2}, {2}, {2, 1}, {2, 2}, {2, 2}}; return structs_col{{child1, child2, child3}}; }(); auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; auto const exp_idx_sort = int32s_col{1, 2, 3, 4, 5, 6}; auto const exp_keys_sort = [] { auto child1 = lists_col{{1}, {1, 1}, {1, 2}, {2, 2}, {2}, {2, 1}}; auto child2 = lists_col{{1}, {1, 1}, {1, 2}, {2, 2}, {2}, {2, 1}}; auto child3 = lists_col{{1}, {1, 1}, {1, 2}, {2, 2}, {2}, {2, 1}}; return structs_col{{child1, child2, child3}}; }(); auto const expected_sort = cudf::table_view{{exp_idx_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_ANY); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); } TEST_F(DistinctKeepFirstLastNone, StructsOfLists) { auto const idx = int32s_col{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto const keys = [] { // All child columns are identical. auto child1 = lists_col{{1}, {1, 1}, {1}, {1, 2}, {2, 2}, {2}, {2}, {2, 1}, {2, 2}, {2, 2}}; auto child2 = lists_col{{1}, {1, 1}, {1}, {1, 2}, {2, 2}, {2}, {2}, {2, 1}, {2, 2}, {2, 2}}; auto child3 = lists_col{{1}, {1, 1}, {1}, {1, 2}, {2, 2}, {2}, {2}, {2, 1}, {2, 2}, {2, 2}}; return structs_col{{child1, child2, child3}}; }(); auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP_FIRST { auto const expect_map = int32s_col{0, 1, 3, 4, 5, 7}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::distinct(input, key_idx, KEEP_FIRST); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result_sort); } // KEEP_LAST { auto const expect_map = int32s_col{1, 2, 3, 6, 7, 9}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::distinct(input, key_idx, KEEP_LAST); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result_sort); } // KEEP_NONE { auto const expect_map = int32s_col{1, 3, 7}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::distinct(input, key_idx, KEEP_NONE); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result_sort); } } TEST_F(DistinctKeepAny, SlicedStructsOfLists) { auto const idx = int32s_col{0, 0, 1, 2, 1, 3, 4, 5, 5, 6, 4, 4, 70}; auto const keys = [] { // All child columns are identical. auto child1 = lists_col{ {0, 0}, {0, 0}, {1}, {1, 1}, {1}, {1, 2}, {2, 2}, {2}, {2}, {2, 1}, {2, 2}, {2, 2}, {5, 5}}; auto child2 = lists_col{ {0, 0}, {0, 0}, {1}, {1, 1}, {1}, {1, 2}, {2, 2}, {2}, {2}, {2, 1}, {2, 2}, {2, 2}, {5, 5}}; auto child3 = lists_col{ {0, 0}, {0, 0}, {1}, {1, 1}, {1}, {1, 2}, {2, 2}, {2}, {2}, {2, 1}, {2, 2}, {2, 2}, {5, 5}}; return structs_col{{child1, child2, child3}}; }(); auto const input_original = cudf::table_view{{idx, keys}}; auto const input = cudf::slice(input_original, {2, 12})[0]; auto const key_idx = std::vector<cudf::size_type>{1}; auto const exp_idx_sort = int32s_col{1, 2, 3, 4, 5, 6}; auto const exp_keys_sort = [] { auto child1 = lists_col{{1}, {1, 1}, {1, 2}, {2, 2}, {2}, {2, 1}}; auto child2 = lists_col{{1}, {1, 1}, {1, 2}, {2, 2}, {2}, {2, 1}}; auto child3 = lists_col{{1}, {1, 1}, {1, 2}, {2, 2}, {2}, {2, 1}}; return structs_col{{child1, child2, child3}}; }(); auto const expected_sort = cudf::table_view{{exp_idx_sort, exp_keys_sort}}; auto const result = cudf::distinct(input, key_idx, KEEP_ANY); auto const result_sort = cudf::sort_by_key(*result, result->select({0})); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_sort, *result_sort); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/stream_compaction/unique_count_tests.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/copying.hpp> #include <cudf/sorting.hpp> #include <cudf/stream_compaction.hpp> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> #include <cudf/types.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <algorithm> #include <cmath> using lists_col = cudf::test::lists_column_wrapper<int32_t>; using structs_col = cudf::test::structs_column_wrapper; using cudf::test::iterators::nulls_at; using cudf::nan_policy; using cudf::null_equality; using cudf::null_policy; constexpr int32_t XXX{70}; // Mark for null elements constexpr int32_t YYY{3}; // Mark for null elements template <typename T> struct TypedUniqueCount : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(TypedUniqueCount, cudf::test::NumericTypes); TYPED_TEST(TypedUniqueCount, NoNull) { using T = TypeParam; auto const input = cudf::test::make_type_param_vector<T>( {1, 3, 3, 4, 31, 1, 8, 2, 0, 4, 1, 4, 10, 40, 31, 42, 0, 42, 8, 5, 4}); cudf::test::fixed_width_column_wrapper<T> input_col(input.begin(), input.end()); // explicit instantiation to one particular type (`double`) to reduce build time std::vector<double> input_data(input.begin(), input.end()); auto const new_end = std::unique(input_data.begin(), input_data.end()); auto const gold = std::distance(input_data.begin(), new_end); EXPECT_EQ(gold, cudf::unique_count(input_col, null_policy::INCLUDE, nan_policy::NAN_IS_VALID)); } TYPED_TEST(TypedUniqueCount, TableNoNull) { using T = TypeParam; auto const input1 = cudf::test::make_type_param_vector<T>( {1, 3, 3, 3, 4, 31, 1, 8, 2, 0, 4, 1, 4, 10, 40, 31, 42, 0, 42, 8, 5, 4}); auto const input2 = cudf::test::make_type_param_vector<T>( {3, 3, 3, 4, 31, 1, 8, 5, 0, 4, 1, 4, 10, 40, 31, 42, 0, 42, 8, 5, 4, 1}); std::vector<std::pair<T, T>> pair_input; std::transform( input1.begin(), input1.end(), input2.begin(), std::back_inserter(pair_input), [](T a, T b) { return std::pair(a, b); }); cudf::test::fixed_width_column_wrapper<T> input_col1(input1.begin(), input1.end()); cudf::test::fixed_width_column_wrapper<T> input_col2(input2.begin(), input2.end()); cudf::table_view input_table({input_col1, input_col2}); auto const new_end = std::unique(pair_input.begin(), pair_input.end()); auto const gold = std::distance(pair_input.begin(), new_end); EXPECT_EQ(gold, cudf::unique_count(input_table, null_equality::EQUAL)); } struct UniqueCount : public cudf::test::BaseFixture {}; TEST_F(UniqueCount, WithNull) { using T = int32_t; std::vector<T> input = {1, 3, 3, XXX, 31, 1, 8, 2, 0, XXX, XXX, XXX, 10, 40, 31, 42, 0, 42, 8, 5, XXX}; std::vector<cudf::size_type> valid = {1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0}; cudf::test::fixed_width_column_wrapper<T> input_col(input.begin(), input.end(), valid.begin()); auto const new_end = std::unique(input.begin(), input.end()); auto const gold = std::distance(input.begin(), new_end) - 3; EXPECT_EQ(gold, cudf::unique_count(input_col, null_policy::EXCLUDE, nan_policy::NAN_IS_VALID)); } TEST_F(UniqueCount, IgnoringNull) { using T = int32_t; std::vector<T> input = {1, YYY, YYY, XXX, 31, 1, 8, 2, 0, XXX, 1, XXX, 10, 40, 31, 42, 0, 42, 8, 5, XXX}; std::vector<cudf::size_type> valid = {1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0}; cudf::test::fixed_width_column_wrapper<T> input_col(input.begin(), input.end(), valid.begin()); auto const new_end = std::unique(input.begin(), input.end()); // -1 since `YYY, YYY, XXX` is in the same group of equivalent rows auto const gold = std::distance(input.begin(), new_end) - 1; EXPECT_EQ(gold, cudf::unique_count(input_col, null_policy::INCLUDE, nan_policy::NAN_IS_VALID)); } TEST_F(UniqueCount, WithNansAndNull) { using T = float; std::vector<T> input = {1, 3, NAN, XXX, 31, 1, 8, 2, 0, XXX, 1, XXX, 10, 40, 31, NAN, 0, NAN, 8, 5, XXX}; std::vector<cudf::size_type> valid = {1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0}; cudf::test::fixed_width_column_wrapper<T> input_col{input.begin(), input.end(), valid.begin()}; auto const new_end = std::unique(input.begin(), input.end()); auto const gold = std::distance(input.begin(), new_end); EXPECT_EQ(gold, cudf::unique_count(input_col, null_policy::INCLUDE, nan_policy::NAN_IS_VALID)); input = {NAN, NAN, XXX}; valid = {1, 1, 0}; input_col = cudf::test::fixed_width_column_wrapper<T>{input.begin(), input.end(), valid.begin()}; constexpr auto expected_all_nan = 2; EXPECT_EQ(expected_all_nan, cudf::unique_count(input_col, null_policy::INCLUDE, nan_policy::NAN_IS_VALID)); } TEST_F(UniqueCount, WithNansOnly) { using T = float; std::vector<T> input = {1, 3, NAN, 70, 31}; std::vector<cudf::size_type> valid = {1, 1, 1, 1, 1}; cudf::test::fixed_width_column_wrapper<T> input_col{input.begin(), input.end(), valid.begin()}; constexpr auto expected = 5; EXPECT_EQ(expected, cudf::unique_count(input_col, null_policy::INCLUDE, nan_policy::NAN_IS_VALID)); input = {NAN, NAN, NAN}; valid = {1, 1, 1}; input_col = cudf::test::fixed_width_column_wrapper<T>{input.begin(), input.end(), valid.begin()}; constexpr auto expected_all_nan = 1; EXPECT_EQ(expected_all_nan, cudf::unique_count(input_col, null_policy::INCLUDE, nan_policy::NAN_IS_VALID)); } TEST_F(UniqueCount, NansAsNullWithNoNull) { using T = float; std::vector<T> input = {1, 3, NAN, 70, 31}; std::vector<cudf::size_type> valid = {1, 1, 1, 1, 1}; cudf::test::fixed_width_column_wrapper<T> input_col{input.begin(), input.end(), valid.begin()}; constexpr auto expected = 5; EXPECT_EQ(expected, cudf::unique_count(input_col, null_policy::INCLUDE, nan_policy::NAN_IS_NULL)); input = {NAN, NAN, NAN}; valid = {1, 1, 1}; input_col = cudf::test::fixed_width_column_wrapper<T>{input.begin(), input.end(), valid.begin()}; constexpr auto expected_all_nan = 1; EXPECT_EQ(expected_all_nan, cudf::unique_count(input_col, null_policy::INCLUDE, nan_policy::NAN_IS_NULL)); } TEST_F(UniqueCount, NansAsNullWithNull) { using T = float; std::vector<T> input = {1, 3, NAN, XXX, 31}; std::vector<cudf::size_type> valid = {1, 1, 1, 0, 1}; cudf::test::fixed_width_column_wrapper<T> input_col{input.begin(), input.end(), valid.begin()}; constexpr auto expected = 4; EXPECT_EQ(expected, cudf::unique_count(input_col, null_policy::INCLUDE, nan_policy::NAN_IS_NULL)); input = {NAN, NAN, XXX}; valid = {1, 1, 0}; input_col = cudf::test::fixed_width_column_wrapper<T>{input.begin(), input.end(), valid.begin()}; constexpr auto expected_all_null = 1; EXPECT_EQ(expected_all_null, cudf::unique_count(input_col, null_policy::INCLUDE, nan_policy::NAN_IS_NULL)); } TEST_F(UniqueCount, NansAsNullWithIgnoreNull) { using T = float; std::vector<T> input = {1, 3, NAN, XXX, 31}; std::vector<cudf::size_type> valid = {1, 1, 1, 0, 1}; cudf::test::fixed_width_column_wrapper<T> input_col{input.begin(), input.end(), valid.begin()}; constexpr auto expected = 3; EXPECT_EQ(expected, cudf::unique_count(input_col, null_policy::EXCLUDE, nan_policy::NAN_IS_NULL)); input = {NAN, NAN, NAN}; valid = {1, 1, 1}; input_col = cudf::test::fixed_width_column_wrapper<T>{input.begin(), input.end(), valid.begin()}; constexpr auto expected_all_nan = 0; EXPECT_EQ(expected_all_nan, cudf::unique_count(input_col, null_policy::EXCLUDE, nan_policy::NAN_IS_NULL)); } TEST_F(UniqueCount, EmptyColumn) { using T = float; cudf::test::fixed_width_column_wrapper<T> input_col{}; constexpr auto expected = 0; EXPECT_EQ(expected, cudf::unique_count(input_col, null_policy::EXCLUDE, nan_policy::NAN_IS_NULL)); } TEST_F(UniqueCount, NullableLists) { auto const keys = lists_col{ {{}, {}, {1, 1}, {1}, {1}, {} /*NULL*/, {} /*NULL*/, {2}, {2}, {2, 1}, {2, 2}, {2, 2}}, nulls_at({5, 6})}; auto const input = cudf::table_view{{keys}}; EXPECT_EQ(7, cudf::unique_count(input, null_equality::EQUAL)); EXPECT_EQ(8, cudf::unique_count(input, null_equality::UNEQUAL)); } TEST_F(UniqueCount, NullableStructOfStructs) { // +-----------------+ // | s1{s2{a,b}, c} | // +-----------------+ // 0 | { {1, 1}, 5} | // 1 | { {1, 1}, 5} | // Same as 0 // 2 | { {1, 2}, 4} | // 3 | { Null, 6} | // 4 | { Null, 4} | // 5 | { Null, 4} | // Same as 4 // 6 | Null | // 7 | Null | // Same as 6 // 8 | { {2, 1}, 5} | auto const keys = [&] { auto a = cudf::test::fixed_width_column_wrapper<int32_t>{1, 1, 1, XXX, XXX, XXX, 2, 1, 2}; auto b = cudf::test::fixed_width_column_wrapper<int32_t>{1, 1, 2, XXX, XXX, XXX, 2, 1, 1}; auto s2 = structs_col{{a, b}, nulls_at({3, 4, 5})}; auto c = cudf::test::fixed_width_column_wrapper<int32_t>{5, 5, 4, 6, 4, 4, 3, 3, 5}; std::vector<std::unique_ptr<cudf::column>> s1_children; s1_children.emplace_back(s2.release()); s1_children.emplace_back(c.release()); auto const null_it = nulls_at({6, 7}); return structs_col(std::move(s1_children), std::vector<bool>{null_it, null_it + 9}); }(); auto const input = cudf::table_view{{keys}}; EXPECT_EQ(6, cudf::unique_count(input, null_equality::EQUAL)); EXPECT_EQ(8, cudf::unique_count(input, null_equality::UNEQUAL)); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/stream_compaction/drop_nans_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cmath> #include <cudf/copying.hpp> #include <cudf/stream_compaction.hpp> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> #include <cudf/types.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_lists.hpp> struct DropNANsTest : public cudf::test::BaseFixture {}; TEST_F(DropNANsTest, MixedNANsAndNull) { using F = float; using D = double; cudf::test::fixed_width_column_wrapper<float> col1{ {F(1.0), F(2.0), F(NAN), F(NAN), F(5.0), F(6.0)}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<int32_t> col2{{10, 40, 70, 5, 2, 10}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<double> col3{{D(NAN), 40.0, 70.0, 5.0, 2.0, 10.0}, {1, 1, 0, 1, 1, 0}}; cudf::table_view input{{col1, col2, col3}}; std::vector<cudf::size_type> keys{0, 2}; cudf::test::fixed_width_column_wrapper<float> col1_expected{{2.0, 3.0, 5.0, 6.0}, {1, 0, 1, 0}}; cudf::test::fixed_width_column_wrapper<int32_t> col2_expected{{40, 70, 2, 10}, {1, 0, 1, 0}}; cudf::test::fixed_width_column_wrapper<double> col3_expected{{40.0, 70.0, 2.0, 10.0}, {1, 0, 1, 0}}; cudf::table_view expected{{col1_expected, col2_expected, col3_expected}}; auto got = cudf::drop_nans(input, keys); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); } TEST_F(DropNANsTest, NoNANs) { cudf::test::fixed_width_column_wrapper<float> col1{{1.0, 2.0, 3.0, 4.0, 5.0, 6.0}, {1, 1, 0, 1, 1, 1}}; cudf::test::fixed_width_column_wrapper<int32_t> col2{{10, 40, 70, 5, 2, 10}, {1, 1, 1, 1, 0, 1}}; cudf::test::fixed_width_column_wrapper<double> col3{{10, 40, 70, 5, 2, 10}, {1, 1, 0, 1, 1, 1}}; cudf::table_view input{{col1, col2, col3}}; std::vector<cudf::size_type> keys{0, 2}; auto got = cudf::drop_nans(input, keys); CUDF_TEST_EXPECT_TABLES_EQUAL(input, got->view()); } TEST_F(DropNANsTest, MixedWithThreshold) { using F = float; using D = double; cudf::test::fixed_width_column_wrapper<float> col1{ {F(1.0), F(2.0), F(NAN), F(NAN), F(5.0), F(6.0)}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<int32_t> col2{{10, 40, 70, 5, 2, 10}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<double> col3{{D(NAN), 40.0, 70.0, D(NAN), 2.0, 10.0}, {1, 1, 0, 1, 1, 0}}; cudf::table_view input{{col1, col2, col3}}; std::vector<cudf::size_type> keys{0, 2}; cudf::test::fixed_width_column_wrapper<float> col1_expected{{1.0, 2.0, 3.0, 5.0, 6.0}, {1, 1, 0, 1, 0}}; cudf::test::fixed_width_column_wrapper<int32_t> col2_expected{{10, 40, 70, 2, 10}, {1, 1, 0, 1, 0}}; cudf::test::fixed_width_column_wrapper<double> col3_expected{{D(NAN), 40.0, 70.0, 2.0, 10.0}, {1, 1, 0, 1, 0}}; cudf::table_view expected{{col1_expected, col2_expected, col3_expected}}; auto got = cudf::drop_nans(input, keys, 1); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); } TEST_F(DropNANsTest, EmptyTable) { cudf::table_view input{std::vector<cudf::column_view>()}; cudf::table_view expected{std::vector<cudf::column_view>()}; std::vector<cudf::size_type> keys{}; auto got = cudf::drop_nans(input, keys); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); } TEST_F(DropNANsTest, EmptyColumns) { cudf::test::fixed_width_column_wrapper<float> col1{}; cudf::test::fixed_width_column_wrapper<int32_t> col2{}; cudf::test::fixed_width_column_wrapper<double> col3{}; cudf::table_view input{{col1, col2, col3}}; std::vector<cudf::size_type> keys{0, 2}; cudf::test::fixed_width_column_wrapper<float> col1_expected{}; cudf::test::fixed_width_column_wrapper<int32_t> col2_expected{}; cudf::test::fixed_width_column_wrapper<double> col3_expected{}; cudf::table_view expected{{col1_expected, col2_expected, col3_expected}}; auto got = cudf::drop_nans(input, keys); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); } TEST_F(DropNANsTest, EmptyKeys) { using F = float; cudf::test::fixed_width_column_wrapper<float> col1{ {F(1.0), F(2.0), F(NAN), F(NAN), F(5.0), F(6.0)}, {1, 1, 0, 1, 1, 0}}; cudf::table_view input{{col1}}; std::vector<cudf::size_type> keys{}; auto got = cudf::drop_nans(input, keys); CUDF_TEST_EXPECT_TABLES_EQUAL(input, got->view()); } TEST_F(DropNANsTest, NonFloatingKey) { cudf::test::fixed_width_column_wrapper<float> col1{{1.0}}; cudf::test::fixed_width_column_wrapper<int32_t> col2{2}; cudf::test::fixed_width_column_wrapper<double> col3{{3.0}}; cudf::table_view input{{col1, col2, col3}}; std::vector<cudf::size_type> keys{0, 1}; EXPECT_THROW(cudf::drop_nans(input, keys), cudf::logic_error); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/stream_compaction/distinct_count_tests.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/copying.hpp> #include <cudf/sorting.hpp> #include <cudf/stream_compaction.hpp> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> #include <cudf/types.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <algorithm> #include <cmath> using lists_col = cudf::test::lists_column_wrapper<int32_t>; using structs_col = cudf::test::structs_column_wrapper; using cudf::test::iterators::nulls_at; using cudf::nan_policy; using cudf::null_equality; using cudf::null_policy; constexpr int32_t XXX{70}; // Mark for null elements constexpr int32_t YYY{3}; // Mark for null elements template <typename T> struct TypedDistinctCount : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(TypedDistinctCount, cudf::test::NumericTypes); TYPED_TEST(TypedDistinctCount, NoNull) { using T = TypeParam; auto const input = cudf::test::make_type_param_vector<T>( {1, 3, 3, 4, 31, 1, 8, 2, 0, 4, 1, 4, 10, 40, 31, 42, 0, 42, 8, 5, 4}); cudf::test::fixed_width_column_wrapper<T> input_col(input.begin(), input.end()); // explicit instantiation to one particular type (`double`) to reduce build time auto const expected = static_cast<cudf::size_type>(std::set<double>(input.begin(), input.end()).size()); EXPECT_EQ(expected, cudf::distinct_count(input_col, null_policy::INCLUDE, nan_policy::NAN_IS_VALID)); } TYPED_TEST(TypedDistinctCount, TableNoNull) { using T = TypeParam; auto const input1 = cudf::test::make_type_param_vector<T>( {1, 3, 3, 3, 4, 31, 1, 8, 2, 0, 4, 1, 4, 10, 40, 31, 42, 0, 42, 8, 5, 4}); auto const input2 = cudf::test::make_type_param_vector<T>( {3, 3, 3, 4, 31, 1, 8, 5, 0, 4, 1, 4, 10, 40, 31, 42, 0, 42, 8, 5, 4, 1}); std::vector<std::pair<T, T>> pair_input; std::transform( input1.begin(), input1.end(), input2.begin(), std::back_inserter(pair_input), [](T a, T b) { return std::pair(a, b); }); cudf::test::fixed_width_column_wrapper<T> input_col1(input1.begin(), input1.end()); cudf::test::fixed_width_column_wrapper<T> input_col2(input2.begin(), input2.end()); cudf::table_view input_table({input_col1, input_col2}); auto const expected = static_cast<cudf::size_type>( std::set<std::pair<T, T>>(pair_input.begin(), pair_input.end()).size()); EXPECT_EQ(expected, cudf::distinct_count(input_table, null_equality::EQUAL)); } struct DistinctCount : public cudf::test::BaseFixture {}; TEST_F(DistinctCount, WithNull) { using T = int32_t; std::vector<T> input = {1, 3, 3, XXX, 31, 1, 8, 2, 0, XXX, XXX, XXX, 10, 40, 31, 42, 0, 42, 8, 5, XXX}; std::vector<cudf::size_type> valid = {1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0}; cudf::test::fixed_width_column_wrapper<T> input_col(input.begin(), input.end(), valid.begin()); // explicit instantiation to one particular type (`double`) to reduce build time auto const expected = static_cast<cudf::size_type>(std::set<double>(input.begin(), input.end()).size()); EXPECT_EQ(expected, cudf::distinct_count(input_col, null_policy::INCLUDE, nan_policy::NAN_IS_VALID)); } TEST_F(DistinctCount, IgnoringNull) { using T = int32_t; std::vector<T> input = {1, YYY, YYY, XXX, 31, 1, 8, 2, 0, XXX, 1, XXX, 10, 40, 31, 42, 0, 42, 8, 5, XXX}; std::vector<cudf::size_type> valid = {1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0}; cudf::test::fixed_width_column_wrapper<T> input_col(input.begin(), input.end(), valid.begin()); auto const expected = static_cast<cudf::size_type>(std::set<T>(input.begin(), input.end()).size()); // Removing 2 from expected to remove count for `XXX` and `YYY` EXPECT_EQ(expected - 2, cudf::distinct_count(input_col, null_policy::EXCLUDE, nan_policy::NAN_IS_VALID)); } TEST_F(DistinctCount, WithNansAndNull) { using T = float; std::vector<T> input = {1, 3, NAN, XXX, 31, 1, 8, 2, 0, XXX, 1, XXX, 10, 40, 31, NAN, 0, NAN, 8, 5, XXX}; std::vector<cudf::size_type> valid = {1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0}; cudf::test::fixed_width_column_wrapper<T> input_col{input.begin(), input.end(), valid.begin()}; auto const expected = static_cast<cudf::size_type>(std::set<T>(input.begin(), input.end()).size()); EXPECT_EQ(expected + 1, // +1 since `NAN` is not in std::set cudf::distinct_count(input_col, null_policy::INCLUDE, nan_policy::NAN_IS_VALID)); input = {NAN, NAN, XXX}; valid = {1, 1, 0}; input_col = cudf::test::fixed_width_column_wrapper<T>{input.begin(), input.end(), valid.begin()}; constexpr auto expected_all_nan = 2; EXPECT_EQ(expected_all_nan, cudf::distinct_count(input_col, null_policy::INCLUDE, nan_policy::NAN_IS_VALID)); } TEST_F(DistinctCount, WithNansOnly) { using T = float; std::vector<T> input = {1, 3, NAN, 70, 31}; std::vector<cudf::size_type> valid = {1, 1, 1, 1, 1}; cudf::test::fixed_width_column_wrapper<T> input_col{input.begin(), input.end(), valid.begin()}; constexpr auto expected = 5; EXPECT_EQ(expected, cudf::distinct_count(input_col, null_policy::INCLUDE, nan_policy::NAN_IS_VALID)); input = {NAN, NAN, NAN}; valid = {1, 1, 1}; input_col = cudf::test::fixed_width_column_wrapper<T>{input.begin(), input.end(), valid.begin()}; constexpr auto expected_all_nan = 1; EXPECT_EQ(expected_all_nan, cudf::distinct_count(input_col, null_policy::INCLUDE, nan_policy::NAN_IS_VALID)); } TEST_F(DistinctCount, NansAsNullWithNoNull) { using T = float; std::vector<T> input = {1, 3, NAN, 70, 31}; std::vector<cudf::size_type> valid = {1, 1, 1, 1, 1}; cudf::test::fixed_width_column_wrapper<T> input_col{input.begin(), input.end(), valid.begin()}; constexpr auto expected = 5; EXPECT_EQ(expected, cudf::distinct_count(input_col, null_policy::INCLUDE, nan_policy::NAN_IS_NULL)); input = {NAN, NAN, NAN}; valid = {1, 1, 1}; input_col = cudf::test::fixed_width_column_wrapper<T>{input.begin(), input.end(), valid.begin()}; constexpr auto expected_all_nan = 1; EXPECT_EQ(expected_all_nan, cudf::distinct_count(input_col, null_policy::INCLUDE, nan_policy::NAN_IS_NULL)); } TEST_F(DistinctCount, NansAsNullWithNull) { using T = float; std::vector<T> input = {1, 3, NAN, XXX, 31}; std::vector<cudf::size_type> valid = {1, 1, 1, 0, 1}; cudf::test::fixed_width_column_wrapper<T> input_col{input.begin(), input.end(), valid.begin()}; constexpr auto expected = 4; EXPECT_EQ(expected, cudf::distinct_count(input_col, null_policy::INCLUDE, nan_policy::NAN_IS_NULL)); input = {NAN, NAN, XXX}; valid = {1, 1, 0}; input_col = cudf::test::fixed_width_column_wrapper<T>{input.begin(), input.end(), valid.begin()}; constexpr auto expected_all_null = 1; EXPECT_EQ(expected_all_null, cudf::distinct_count(input_col, null_policy::INCLUDE, nan_policy::NAN_IS_NULL)); } TEST_F(DistinctCount, NansAsNullWithIgnoreNull) { using T = float; std::vector<T> input = {1, 3, NAN, XXX, 31}; std::vector<cudf::size_type> valid = {1, 1, 1, 0, 1}; cudf::test::fixed_width_column_wrapper<T> input_col{input.begin(), input.end(), valid.begin()}; constexpr auto expected = 3; EXPECT_EQ(expected, cudf::distinct_count(input_col, null_policy::EXCLUDE, nan_policy::NAN_IS_NULL)); input = {NAN, NAN, NAN}; valid = {1, 1, 1}; input_col = cudf::test::fixed_width_column_wrapper<T>{input.begin(), input.end(), valid.begin()}; constexpr auto expected_all_nan = 0; EXPECT_EQ(expected_all_nan, cudf::distinct_count(input_col, null_policy::EXCLUDE, nan_policy::NAN_IS_NULL)); } TEST_F(DistinctCount, EmptyColumn) { using T = float; cudf::test::fixed_width_column_wrapper<T> input_col{}; constexpr auto expected = 0; EXPECT_EQ(expected, cudf::distinct_count(input_col, null_policy::EXCLUDE, nan_policy::NAN_IS_NULL)); } TEST_F(DistinctCount, StringColumnWithNull) { cudf::test::strings_column_wrapper input_col{ {"", "this", "is", "this", "This", "a", "column", "of", "the", "strings"}, {1, 1, 1, 1, 1, 1, 1, 1, 0, 1}}; cudf::size_type const expected = (std::vector<std::string>{"", "this", "is", "This", "a", "column", "of", "strings"}).size(); EXPECT_EQ(expected, cudf::distinct_count(input_col, null_policy::EXCLUDE, nan_policy::NAN_IS_VALID)); } TEST_F(DistinctCount, TableWithNull) { cudf::test::fixed_width_column_wrapper<int32_t> col1{{5, 4, 3, 5, 8, 1, 4, 5, 0, 9, -1}, {1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0}}; cudf::test::fixed_width_column_wrapper<int32_t> col2{{2, 2, 2, -1, 2, 1, 2, 0, 0, 9, -1}, {1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0}}; cudf::table_view input{{col1, col2}}; EXPECT_EQ(8, cudf::distinct_count(input, null_equality::EQUAL)); EXPECT_EQ(10, cudf::distinct_count(input, null_equality::UNEQUAL)); } TEST_F(DistinctCount, TableWithSomeNull) { cudf::test::fixed_width_column_wrapper<int32_t> col1{{1, 2, 3, 4, 5, 6}, {1, 0, 1, 0, 1, 0}}; cudf::test::fixed_width_column_wrapper<int32_t> col2{{1, 1, 1, 1, 1, 1}}; cudf::table_view input{{col1, col2}}; EXPECT_EQ(4, cudf::distinct_count(input, null_equality::EQUAL)); EXPECT_EQ(6, cudf::distinct_count(input, null_equality::UNEQUAL)); } TEST_F(DistinctCount, EmptyColumnedTable) { std::vector<cudf::column_view> cols{}; cudf::table_view input(cols); EXPECT_EQ(0, cudf::distinct_count(input, null_equality::EQUAL)); EXPECT_EQ(0, cudf::distinct_count(input, null_equality::UNEQUAL)); } TEST_F(DistinctCount, TableMixedTypes) { cudf::test::fixed_width_column_wrapper<int32_t> col1{{5, 4, 3, 5, 8, 1, 4, 5, 0, 9, -1}, {1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0}}; cudf::test::fixed_width_column_wrapper<double> col2{{2, 2, 2, -1, 2, 1, 2, 0, 0, 9, -1}, {1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0}}; cudf::test::fixed_width_column_wrapper<uint32_t> col3{{2, 2, 2, -1, 2, 1, 2, 0, 0, 9, -1}, {1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0}}; cudf::table_view input{{col1, col2, col3}}; EXPECT_EQ(9, cudf::distinct_count(input, null_equality::EQUAL)); EXPECT_EQ(10, cudf::distinct_count(input, null_equality::UNEQUAL)); } TEST_F(DistinctCount, TableWithStringColumnWithNull) { cudf::test::fixed_width_column_wrapper<int32_t> col1{{0, 9, 8, 9, 6, 5, 4, 3, 2, 1, 0}, {1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0}}; cudf::test::strings_column_wrapper col2{ {"", "this", "is", "this", "this", "a", "column", "of", "the", "strings", ""}, {1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0}}; cudf::table_view input{{col1, col2}}; EXPECT_EQ(9, cudf::distinct_count(input, null_equality::EQUAL)); EXPECT_EQ(10, cudf::distinct_count(input, null_equality::UNEQUAL)); } TEST_F(DistinctCount, NullableLists) { auto const keys = lists_col{ {{}, {1, 1}, {1}, {} /*NULL*/, {1}, {} /*NULL*/, {2}, {2, 1}, {2}, {2, 2}, {}, {2, 2}}, nulls_at({3, 5})}; auto const input = cudf::table_view{{keys}}; EXPECT_EQ(7, cudf::distinct_count(input, null_equality::EQUAL)); EXPECT_EQ(8, cudf::distinct_count(input, null_equality::UNEQUAL)); } TEST_F(DistinctCount, NullableStructOfStructs) { // +-----------------+ // | s1{s2{a,b}, c} | // +-----------------+ // 0 | { {1, 1}, 5} | // 1 | { Null, 4} | // 2 | { {1, 1}, 5} | // Same as 0 // 3 | { {1, 2}, 4} | // 4 | { Null, 6} | // 5 | { Null, 4} | // Same as 4 // 6 | Null | // Same as 6 // 7 | { {2, 1}, 5} | // 8 | Null | auto const keys = [&] { auto a = cudf::test::fixed_width_column_wrapper<int32_t>{1, XXX, 1, 1, XXX, XXX, 0, 2, 0}; auto b = cudf::test::fixed_width_column_wrapper<int32_t>{1, XXX, 1, 2, XXX, XXX, 0, 1, 0}; auto s2 = structs_col{{a, b}, nulls_at({1, 4, 5})}; auto c = cudf::test::fixed_width_column_wrapper<int32_t>{5, 4, 5, 4, 6, 4, 0, 5, 0}; std::vector<std::unique_ptr<cudf::column>> s1_children; s1_children.emplace_back(s2.release()); s1_children.emplace_back(c.release()); auto const null_it = nulls_at({6, 8}); return structs_col(std::move(s1_children), std::vector<bool>{null_it, null_it + 9}); }(); auto const input = cudf::table_view{{keys}}; EXPECT_EQ(6, cudf::distinct_count(input, null_equality::EQUAL)); EXPECT_EQ(8, cudf::distinct_count(input, null_equality::UNEQUAL)); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/stream_compaction/drop_nulls_tests.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/copying.hpp> #include <cudf/stream_compaction.hpp> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> #include <cudf/types.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <algorithm> #include <numeric> struct DropNullsTest : public cudf::test::BaseFixture {}; TEST_F(DropNullsTest, WholeRowIsNull) { cudf::test::fixed_width_column_wrapper<int16_t> col1{{true, false, true, false, true, false}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<int32_t> col2{{10, 40, 70, 5, 2, 10}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<double> col3{{10, 40, 70, 5, 2, 10}, {1, 1, 0, 1, 1, 0}}; cudf::table_view input{{col1, col2, col3}}; std::vector<cudf::size_type> keys{0, 1, 2}; cudf::test::fixed_width_column_wrapper<int16_t> col1_expected{{true, false, false, true}, {1, 1, 1, 1}}; cudf::test::fixed_width_column_wrapper<int32_t> col2_expected{{10, 40, 5, 2}, {1, 1, 1, 1}}; cudf::test::fixed_width_column_wrapper<double> col3_expected{{10, 40, 5, 2}, {1, 1, 1, 1}}; cudf::table_view expected{{col1_expected, col2_expected, col3_expected}}; auto got = cudf::drop_nulls(input, keys); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); } TEST_F(DropNullsTest, NoNull) { cudf::test::fixed_width_column_wrapper<int16_t> col1{{true, false, true, false, true, false}, {1, 1, 1, 1, 1, 1}}; cudf::test::fixed_width_column_wrapper<int32_t> col2{{10, 40, 70, 5, 2, 10}, {1, 1, 1, 1, 1, 1}}; cudf::test::fixed_width_column_wrapper<double> col3{{10, 40, 70, 5, 2, 10}, {1, 1, 1, 1, 1, 1}}; cudf::table_view input{{col1, col2, col3}}; std::vector<cudf::size_type> keys{0, 1, 2}; auto got = cudf::drop_nulls(input, keys); CUDF_TEST_EXPECT_TABLES_EQUAL(input, got->view()); } TEST_F(DropNullsTest, MixedSetOfRows) { cudf::test::fixed_width_column_wrapper<int16_t> col1{{true, false, true, false, true, false}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<int32_t> col2{{10, 40, 70, 5, 2, 10}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<double> col3{{10, 40, 70, 5, 2, 10}, {1, 1, 0, 1, 1, 1}}; cudf::table_view input{{col1, col2, col3}}; std::vector<cudf::size_type> keys{0, 1, 2}; cudf::test::fixed_width_column_wrapper<int16_t> col1_expected{{true, false, false, true}, {1, 1, 1, 1}}; cudf::test::fixed_width_column_wrapper<int32_t> col2_expected{{10, 40, 5, 2}, {1, 1, 1, 1}}; cudf::test::fixed_width_column_wrapper<double> col3_expected{{10, 40, 5, 2}, {1, 1, 1, 1}}; cudf::table_view expected{{col1_expected, col2_expected, col3_expected}}; auto got = cudf::drop_nulls(input, keys); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); } TEST_F(DropNullsTest, LargeColumn) { // This test is a C++ repro of the failing Python in this issue: // https://github.com/rapidsai/cudf/issues/5456 // Specifically, there are two large columns, one nullable, one non-nullable using T = int32_t; using index_T = int64_t; constexpr cudf::size_type column_size{270000}; std::vector<index_T> index(column_size); std::vector<T> data(column_size); std::vector<bool> mask_data(column_size); std::iota(index.begin(), index.end(), 0); std::generate_n(data.begin(), column_size, [x = 1]() mutable { return x++ % 3; }); std::transform(data.begin(), data.end(), mask_data.begin(), [](auto const& x) { return x != 0; }); std::vector<T> expected_data(column_size); // zeros are the null elements, remove them auto end = std::remove_copy(data.begin(), data.end(), expected_data.begin(), 0); auto expected_size = std::distance(expected_data.begin(), end); expected_data.resize(expected_size); std::vector<index_T> expected_index(expected_size); std::copy_if(index.begin(), index.end(), expected_index.begin(), [](auto const& x) { return (x - 2) % 3 != 0; }); // output null mask is all true std::vector<bool> expected_mask(expected_size, true); cudf::test::fixed_width_column_wrapper<T> col1(data.begin(), data.end(), mask_data.begin()); cudf::test::fixed_width_column_wrapper<index_T> index1(index.begin(), index.end()); cudf::table_view input{{index1, col1}}; std::vector<cudf::size_type> keys{1}; cudf::test::fixed_width_column_wrapper<T> exp1( expected_data.begin(), expected_data.end(), expected_mask.begin()); cudf::test::fixed_width_column_wrapper<index_T> exp_index1(expected_index.begin(), expected_index.end()); cudf::table_view expected{{exp_index1, exp1}}; auto got = cudf::drop_nulls(input, keys); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); } TEST_F(DropNullsTest, MixedSetOfRowsWithThreshold) { cudf::test::fixed_width_column_wrapper<int16_t> col1{{true, false, true, false, true, false}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<int32_t> col2{{10, 40, 70, 5, 2, 10}, {1, 1, 0, 1, 1, 1}}; cudf::test::fixed_width_column_wrapper<double> col3{{10, 40, 70, 5, 2, 10}, {1, 1, 1, 1, 1, 1}}; cudf::table_view input{{col1, col2, col3}}; std::vector<cudf::size_type> keys{0, 1, 2}; cudf::test::fixed_width_column_wrapper<int16_t> col1_expected{{true, false, false, true, false}, {1, 1, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<int32_t> col2_expected{{10, 40, 5, 2, 10}, {1, 1, 1, 1, 1}}; cudf::test::fixed_width_column_wrapper<double> col3_expected{{10, 40, 5, 2, 10}, {1, 1, 1, 1, 1}}; cudf::table_view expected{{col1_expected, col2_expected, col3_expected}}; auto got = cudf::drop_nulls(input, keys, keys.size() - 1); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); } TEST_F(DropNullsTest, EmptyTable) { cudf::table_view input{std::vector<cudf::column_view>()}; cudf::table_view expected{std::vector<cudf::column_view>()}; std::vector<cudf::size_type> keys{}; auto got = cudf::drop_nulls(input, keys); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); } TEST_F(DropNullsTest, EmptyColumns) { cudf::test::fixed_width_column_wrapper<int16_t> col1{}; cudf::test::fixed_width_column_wrapper<int32_t> col2{}; cudf::test::fixed_width_column_wrapper<double> col3{}; cudf::table_view input{{col1, col2, col3}}; std::vector<cudf::size_type> keys{0, 1, 2}; cudf::test::fixed_width_column_wrapper<int16_t> col1_expected{}; cudf::test::fixed_width_column_wrapper<int32_t> col2_expected{}; cudf::test::fixed_width_column_wrapper<double> col3_expected{}; cudf::table_view expected{{col1_expected, col2_expected, col3_expected}}; auto got = cudf::drop_nulls(input, keys); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); } TEST_F(DropNullsTest, EmptyKeys) { cudf::test::fixed_width_column_wrapper<int16_t> col1{{true, false, true, false, true, false}, {1, 1, 0, 1, 1, 0}}; cudf::table_view input{{col1}}; std::vector<cudf::size_type> keys{}; auto got = cudf::drop_nulls(input, keys); CUDF_TEST_EXPECT_TABLES_EQUAL(input, got->view()); } TEST_F(DropNullsTest, StringColWithNull) { cudf::test::fixed_width_column_wrapper<int16_t> col1{{11, 12, 11, 13, 12, 15}, {1, 1, 0, 1, 0, 1}}; cudf::test::strings_column_wrapper col2{{"Hi", "Hello", "Hi", "No", "Hello", "Naive"}, {1, 1, 0, 1, 0, 1}}; cudf::table_view input{{col1, col2}}; std::vector<cudf::size_type> keys{0, 1}; cudf::test::fixed_width_column_wrapper<int16_t> col1_expected{{11, 12, 13, 15}, {1, 1, 1, 1}}; cudf::test::strings_column_wrapper col2_expected{{"Hi", "Hello", "No", "Naive"}, {1, 1, 1, 1}}; cudf::table_view expected{{col1_expected, col2_expected}}; auto got = cudf::drop_nulls(input, keys); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); } template <typename T> struct DropNullsTestAll : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(DropNullsTestAll, cudf::test::NumericTypes); TYPED_TEST(DropNullsTestAll, AllNull) { using T = TypeParam; cudf::test::fixed_width_column_wrapper<T> key_col{{true, false, true, false, true, false}, {0, 0, 0, 0, 0, 0}}; cudf::test::fixed_width_column_wrapper<T> col{{true, false, true, false, true, false}, {1, 1, 1, 1, 1, 1}}; cudf::table_view input{{key_col, col}}; std::vector<cudf::size_type> keys{0}; cudf::test::fixed_width_column_wrapper<T> expected_col{}; cudf::column_view view = expected_col; cudf::table_view expected{{expected_col, expected_col}}; auto got = cudf::drop_nulls(input, keys); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/stream_compaction/apply_boolean_mask_tests.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/copying.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/detail/null_mask.hpp> #include <cudf/stream_compaction.hpp> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> #include <cudf/types.hpp> #include <cudf/utilities/default_stream.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <thrust/copy.h> #include <thrust/execution_policy.h> #include <thrust/functional.h> struct ApplyBooleanMask : public cudf::test::BaseFixture {}; TEST_F(ApplyBooleanMask, NonNullBooleanMask) { cudf::test::fixed_width_column_wrapper<int16_t> col1{{true, false, true, false, true, false}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<int32_t> col2{{10, 40, 70, 5, 2, 10}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<double> col3{{10, 40, 70, 5, 2, 10}, {1, 1, 0, 1, 1, 0}}; cudf::table_view input{{col1, col2, col3}}; cudf::test::fixed_width_column_wrapper<bool> boolean_mask{ {true, false, true, false, true, false}}; cudf::test::fixed_width_column_wrapper<int16_t> col1_expected{{true, true, true}, {1, 0, 1}}; cudf::test::fixed_width_column_wrapper<int32_t> col2_expected{{10, 70, 2}, {1, 0, 1}}; cudf::test::fixed_width_column_wrapper<double> col3_expected{{10, 70, 2}, {1, 0, 1}}; cudf::table_view expected{{col1_expected, col2_expected, col3_expected}}; auto got = cudf::apply_boolean_mask(input, boolean_mask); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); } TEST_F(ApplyBooleanMask, NullBooleanMask) { cudf::test::fixed_width_column_wrapper<int16_t> col1{{true, false, true, false, true, false}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<int32_t> col2{{10, 40, 70, 5, 2, 10}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<double> col3{{10, 40, 70, 5, 2, 10}, {1, 1, 0, 1, 1, 0}}; cudf::table_view input{{col1, col2, col3}}; cudf::test::fixed_width_column_wrapper<bool> boolean_mask{{true, false, true, false, true, false}, {0, 1, 1, 1, 1, 1}}; cudf::test::fixed_width_column_wrapper<int16_t> col1_expected{{true, true}, {0, 1}}; cudf::test::fixed_width_column_wrapper<int32_t> col2_expected{{70, 2}, {0, 1}}; cudf::test::fixed_width_column_wrapper<double> col3_expected{{70, 2}, {0, 1}}; cudf::table_view expected{{col1_expected, col2_expected, col3_expected}}; auto got = cudf::apply_boolean_mask(input, boolean_mask); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); } TEST_F(ApplyBooleanMask, EmptyMask) { cudf::test::fixed_width_column_wrapper<int16_t> col1{{true, false, true, false, true, false}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<int32_t> col2{{10, 40, 70, 5, 2, 10}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<double> col3{{10, 40, 70, 5, 2, 10}, {1, 1, 0, 1, 1, 0}}; cudf::table_view input{{col1, col2, col3}}; cudf::test::fixed_width_column_wrapper<bool> boolean_mask{}; cudf::test::fixed_width_column_wrapper<int16_t> col1_expected{}; cudf::test::fixed_width_column_wrapper<int32_t> col2_expected{}; cudf::test::fixed_width_column_wrapper<double> col3_expected{}; cudf::table_view expected{{col1_expected, col2_expected, col3_expected}}; auto got = cudf::apply_boolean_mask(input, boolean_mask); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); } TEST_F(ApplyBooleanMask, WrongMaskType) { cudf::test::fixed_width_column_wrapper<int16_t> col1{{true, false, true, false, true, false}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<int32_t> col2{{10, 40, 70, 5, 2, 10}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<double> col3{{10, 40, 70, 5, 2, 10}, {1, 1, 0, 1, 1, 0}}; cudf::table_view input{{col1, col2, col3}}; cudf::test::fixed_width_column_wrapper<int16_t> boolean_mask{ {true, false, true, false, true, false}}; EXPECT_THROW(cudf::apply_boolean_mask(input, boolean_mask), cudf::logic_error); } TEST_F(ApplyBooleanMask, MaskAndInputSizeMismatch) { cudf::test::fixed_width_column_wrapper<int16_t> col1{{true, false, true, false, true, false}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<int32_t> col2{{10, 40, 70, 5, 2, 10}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<double> col3{{10, 40, 70, 5, 2, 10}, {1, 1, 0, 1, 1, 0}}; cudf::table_view input{{col1, col2, col3}}; cudf::test::fixed_width_column_wrapper<bool> boolean_mask{{true, false, true, false, true}}; EXPECT_THROW(cudf::apply_boolean_mask(input, boolean_mask), cudf::logic_error); } TEST_F(ApplyBooleanMask, StringColumnTest) { cudf::test::strings_column_wrapper col1{ {"This", "is", "the", "a", "k12", "string", "table", "column"}, {1, 1, 1, 1, 1, 0, 1, 1}}; cudf::table_view input{{col1}}; cudf::test::fixed_width_column_wrapper<bool> boolean_mask{ {true, true, true, true, false, true, false, true}, {1, 1, 0, 1, 1, 1, 1, 1}}; cudf::test::strings_column_wrapper col1_expected{{"This", "is", "a", "string", "column"}, {1, 1, 1, 0, 1}}; cudf::table_view expected{{col1_expected}}; auto got = cudf::apply_boolean_mask(input, boolean_mask); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); } TEST_F(ApplyBooleanMask, withoutNullString) { cudf::test::strings_column_wrapper col1({"d", "e", "a", "d", "k", "d", "l"}); cudf::table_view cudf_table_in_view{{col1}}; cudf::test::fixed_width_column_wrapper<bool> bool_filter{{1, 1, 0, 0, 1, 0, 0}}; cudf::column_view bool_filter_col(bool_filter); std::unique_ptr<cudf::table> filteredTable = cudf::apply_boolean_mask(cudf_table_in_view, bool_filter_col); cudf::table_view tableView = filteredTable->view(); cudf::test::strings_column_wrapper expect_col1({"d", "e", "k"}); cudf::table_view expect_cudf_table_view{{expect_col1}}; CUDF_TEST_EXPECT_TABLES_EQUAL(expect_cudf_table_view, tableView); } TEST_F(ApplyBooleanMask, FixedPointColumnTest) { using namespace numeric; using decimal32_wrapper = cudf::test::fixed_point_column_wrapper<int32_t>; using decimal64_wrapper = cudf::test::fixed_point_column_wrapper<int64_t>; auto const col1 = decimal32_wrapper{{10, 40, 70, 5, 2, 10, -123}, scale_type{-1}}; auto const col2 = decimal64_wrapper{{10, 40, 70, 5, 2, 10, -123}, scale_type{-10}}; cudf::table_view cudf_table_in_view{{col1, col2}}; cudf::test::fixed_width_column_wrapper<bool> bool_filter{{1, 1, 0, 0, 1, 0, 0}}; cudf::column_view bool_filter_col(bool_filter); std::unique_ptr<cudf::table> filteredTable = cudf::apply_boolean_mask(cudf_table_in_view, bool_filter_col); cudf::table_view tableView = filteredTable->view(); auto const expect_col1 = decimal32_wrapper{{10, 40, 2}, scale_type{-1}}; auto const expect_col2 = decimal64_wrapper{{10, 40, 2}, scale_type{-10}}; cudf::table_view expect_cudf_table_view{{expect_col1, expect_col2}}; CUDF_TEST_EXPECT_TABLES_EQUAL(expect_cudf_table_view, tableView); } TEST_F(ApplyBooleanMask, FixedPointLargeColumnTest) { cudf::size_type const num_rows = 10000; using decimal32_wrapper = cudf::test::fixed_point_column_wrapper<int32_t>; using decimal64_wrapper = cudf::test::fixed_point_column_wrapper<int64_t>; std::vector<int32_t> dec32_data(num_rows); std::vector<int64_t> dec64_data(num_rows); std::vector<bool> mask_data(num_rows); cudf::test::UniformRandomGenerator<int32_t> rng32(-10000000, 10000000); cudf::test::UniformRandomGenerator<int64_t> rng64(-1000000000000, 1000000000000); cudf::test::UniformRandomGenerator<bool> rbg; std::generate(dec32_data.begin(), dec32_data.end(), [&rng32]() { return rng32.generate(); }); std::generate(dec64_data.begin(), dec64_data.end(), [&rng64]() { return rng64.generate(); }); std::generate(mask_data.begin(), mask_data.end(), [&rbg]() { return rbg.generate(); }); decimal32_wrapper col32(dec32_data.begin(), dec32_data.end(), numeric::scale_type{-3}); decimal64_wrapper col64(dec64_data.begin(), dec64_data.end(), numeric::scale_type{-10}); cudf::table_view cudf_table_in_view{{col32, col64}}; cudf::test::fixed_width_column_wrapper<bool> bool_filter(mask_data.begin(), mask_data.end()); cudf::column_view bool_filter_col(bool_filter); std::unique_ptr<cudf::table> filteredTable = cudf::apply_boolean_mask(cudf_table_in_view, bool_filter_col); cudf::table_view tableView = filteredTable->view(); std::vector<int32_t> expect_dec32_data; std::vector<int64_t> expect_dec64_data; thrust::copy_if(thrust::seq, dec32_data.cbegin(), dec32_data.cend(), mask_data.cbegin(), std::back_inserter(expect_dec32_data), thrust::identity{}); thrust::copy_if(thrust::seq, dec64_data.cbegin(), dec64_data.cend(), mask_data.cbegin(), std::back_inserter(expect_dec64_data), thrust::identity{}); decimal32_wrapper expect_col32( expect_dec32_data.begin(), expect_dec32_data.end(), numeric::scale_type{-3}); decimal64_wrapper expect_col64( expect_dec64_data.begin(), expect_dec64_data.end(), numeric::scale_type{-10}); cudf::table_view expect_cudf_table_view{{expect_col32, expect_col64}}; CUDF_TEST_EXPECT_TABLES_EQUAL(expect_cudf_table_view, tableView); } TEST_F(ApplyBooleanMask, NoNullInput) { cudf::test::fixed_width_column_wrapper<int32_t> col( {9668, 9590, 9526, 9205, 9434, 9347, 9160, 9569, 9143, 9807, 9606, 9446, 9279, 9822, 9691}); cudf::test::fixed_width_column_wrapper<bool> mask({false, false, true, false, false, true, false, true, false, true, false, false, true, false, true}); cudf::table_view input({col}); cudf::test::fixed_width_column_wrapper<int32_t> col_expected( {9526, 9347, 9569, 9807, 9279, 9691}); cudf::table_view expected({col_expected}); auto got = cudf::apply_boolean_mask(input, mask); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); } TEST_F(ApplyBooleanMask, CorrectNullCount) { cudf::size_type inputRows = 471234; auto seq1 = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i; }); auto valid_seq1 = cudf::detail::make_counting_transform_iterator(0, [](auto row) { return true; }); cudf::test::fixed_width_column_wrapper<int64_t, typename decltype(seq1)::value_type> col1( seq1, seq1 + inputRows, valid_seq1); cudf::table_view input{{col1}}; auto seq3 = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return (i % 277) == 0; }); cudf::test::fixed_width_column_wrapper<bool> boolean_mask(seq3, seq3 + inputRows); auto got = cudf::apply_boolean_mask(input, boolean_mask); auto out_col = got->get_column(0).view(); auto expected_null_count = cudf::detail::null_count(out_col.null_mask(), 0, out_col.size(), cudf::get_default_stream()); ASSERT_EQ(out_col.null_count(), expected_null_count); } TEST_F(ApplyBooleanMask, StructFiltering) { using namespace cudf::test; auto int_member = fixed_width_column_wrapper<int32_t>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 0, 1, 1, 1, 1, 0}}; auto struct_column = structs_column_wrapper{{int_member}, {0, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto filter_mask = fixed_width_column_wrapper<bool>{{1, 1, 1, 1, 1, 0, 0, 0, 0, 0}}; auto filtered_table = cudf::apply_boolean_mask(cudf::table_view({struct_column}), filter_mask); auto filtered_struct_column = filtered_table->get_column(0); // Compare against expected results. auto expected_int_member = fixed_width_column_wrapper<int32_t>{{-1, 1, 2, 3, -1}, {0, 1, 1, 1, 0}}; auto expected_struct_column = structs_column_wrapper{{expected_int_member}, {1, 1, 1, 1, 0}}; CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(filtered_struct_column, expected_struct_column); } TEST_F(ApplyBooleanMask, ListOfStructsFiltering) { using namespace cudf::test; auto key_member = fixed_width_column_wrapper<int32_t>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 0, 1, 1, 1, 1, 0}}; auto value_member = fixed_width_column_wrapper<int32_t>{{0, 10, 20, 30, 40, 50, 60, 70, 80, 90}, {1, 1, 1, 1, 0, 1, 1, 1, 1, 0}}; auto struct_column = structs_column_wrapper{{key_member, value_member}, {0, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto list_of_structs_column = cudf::make_lists_column(5, fixed_width_column_wrapper<int32_t>{0, 2, 4, 6, 8, 10}.release(), struct_column.release(), 0, {}); auto filter_mask = fixed_width_column_wrapper<bool>{{1, 0, 1, 0, 1}}; auto filtered_table = cudf::apply_boolean_mask(cudf::table_view({list_of_structs_column->view()}), filter_mask); auto filtered_list_column = filtered_table->get_column(0); // Compare against expected values. auto expected_key_column = fixed_width_column_wrapper<int32_t>{{0, 1, 4, 5, 8, 9}, {0, 1, 0, 0, 1, 0}}; auto expected_value_column = fixed_width_column_wrapper<int32_t>{{0, 10, 40, 50, 80, 90}, {0, 1, 0, 0, 1, 0}}; auto expected_struct_column = structs_column_wrapper{{expected_key_column, expected_value_column}, {0, 1, 1, 0, 1, 1}}; auto expected_list_of_structs_column = cudf::make_lists_column(3, fixed_width_column_wrapper<int32_t>{0, 2, 4, 6}.release(), expected_struct_column.release(), 0, {}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(filtered_list_column, expected_list_of_structs_column->view()); } TEST_F(ApplyBooleanMask, StructOfListsFiltering) { using namespace cudf::test; auto lists_column = lists_column_wrapper<int32_t>{ {{0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 2; })}; auto structs_column = structs_column_wrapper{{lists_column}}; auto filter_mask = fixed_width_column_wrapper<bool>{{1, 0, 1, 0, 1}}; auto filtered_table = cudf::apply_boolean_mask(cudf::table_view({structs_column}), filter_mask); auto filtered_lists_column = filtered_table->get_column(0); // Compare against expected values; auto expected_lists_column = lists_column_wrapper<int32_t>{ {{0, 0}, {2, 2}, {4, 4}}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 1; })}; auto expected_structs_column = structs_column_wrapper{{expected_lists_column}}; CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(filtered_lists_column, expected_structs_column); } CUDF_TEST_PROGRAM_MAIN()
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/stream_compaction/unique_tests.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/copying.hpp> #include <cudf/sorting.hpp> #include <cudf/stream_compaction.hpp> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> #include <cudf/types.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <algorithm> #include <cmath> using cudf::nan_policy; using cudf::null_equality; using cudf::null_policy; using cudf::test::iterators::null_at; using cudf::test::iterators::nulls_at; auto constexpr null{0}; // null at current level auto constexpr XXX{0}; // null pushed down from parent level auto constexpr KEEP_ANY = cudf::duplicate_keep_option::KEEP_ANY; auto constexpr KEEP_FIRST = cudf::duplicate_keep_option::KEEP_FIRST; auto constexpr KEEP_LAST = cudf::duplicate_keep_option::KEEP_LAST; auto constexpr KEEP_NONE = cudf::duplicate_keep_option::KEEP_NONE; auto constexpr NULL_EQUAL = cudf::null_equality::EQUAL; auto constexpr NULL_UNEQUAL = cudf::null_equality::UNEQUAL; using int32s_col = cudf::test::fixed_width_column_wrapper<int32_t>; using floats_col = cudf::test::fixed_width_column_wrapper<float>; using lists_col = cudf::test::lists_column_wrapper<int32_t>; using strings_col = cudf::test::strings_column_wrapper; using structs_col = cudf::test::structs_column_wrapper; struct Unique : public cudf::test::BaseFixture {}; TEST_F(Unique, StringKeyColumn) { cudf::test::fixed_width_column_wrapper<int32_t> col{{5, 4, 4, 5, 5, 8, 1}, {1, 0, 0, 1, 1, 1, 1}}; cudf::test::strings_column_wrapper key_col{{"all", "new", "new", "all", "new", "the", "strings"}, {1, 1, 1, 1, 0, 1, 1}}; cudf::table_view input{{col, key_col}}; std::vector<cudf::size_type> keys{1}; cudf::test::fixed_width_column_wrapper<int32_t> exp_col{{5, 4, 5, 5, 8, 1}, {1, 0, 1, 1, 1, 1}}; cudf::test::strings_column_wrapper exp_key_col{{"all", "new", "all", "new", "the", "strings"}, {1, 1, 1, 0, 1, 1}}; cudf::table_view expected{{exp_col, exp_key_col}}; auto got = unique(input, keys, cudf::duplicate_keep_option::KEEP_LAST); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); } TEST_F(Unique, EmptyInputTable) { cudf::test::fixed_width_column_wrapper<int32_t> col(std::initializer_list<int32_t>{}); cudf::table_view input{{col}}; std::vector<cudf::size_type> keys{1, 2}; auto got = unique(input, keys, cudf::duplicate_keep_option::KEEP_FIRST, null_equality::EQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(input, got->view()); } TEST_F(Unique, NoColumnInputTable) { cudf::table_view input{std::vector<cudf::column_view>()}; std::vector<cudf::size_type> keys{1, 2}; auto got = unique(input, keys, cudf::duplicate_keep_option::KEEP_FIRST, null_equality::EQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(input, got->view()); } TEST_F(Unique, EmptyKeys) { cudf::test::fixed_width_column_wrapper<int32_t> col{{5, 4, 3, 5, 8, 1}, {1, 0, 1, 1, 1, 1}}; cudf::test::fixed_width_column_wrapper<int32_t> empty_col{}; cudf::table_view input{{col}}; std::vector<cudf::size_type> keys{}; auto got = unique(input, keys, cudf::duplicate_keep_option::KEEP_FIRST, null_equality::EQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(cudf::table_view{{empty_col}}, got->view()); } TEST_F(Unique, NonNullTable) { cudf::test::fixed_width_column_wrapper<int32_t> col1{{5, 4, 3, 5, 8, 5}}; cudf::test::fixed_width_column_wrapper<float> col2{{4, 5, 3, 4, 9, 4}}; cudf::test::fixed_width_column_wrapper<int32_t> col1_key{{20, 20, 20, 19, 21, 9}}; cudf::test::fixed_width_column_wrapper<int32_t> col2_key{{19, 19, 20, 20, 9, 21}}; cudf::table_view input{{col1, col2, col1_key, col2_key}}; std::vector<cudf::size_type> keys{2, 3}; // Keep the first duplicate row // The expected table would be sorted in ascending order with respect to keys cudf::test::fixed_width_column_wrapper<int32_t> exp_col1_first{{5, 3, 5, 8, 5}}; cudf::test::fixed_width_column_wrapper<float> exp_col2_first{{4, 3, 4, 9, 4}}; cudf::test::fixed_width_column_wrapper<int32_t> exp_col1_key_first{{20, 20, 19, 21, 9}}; cudf::test::fixed_width_column_wrapper<int32_t> exp_col2_key_first{{19, 20, 20, 9, 21}}; cudf::table_view expected_first{ {exp_col1_first, exp_col2_first, exp_col1_key_first, exp_col2_key_first}}; auto got_first = unique(input, keys, cudf::duplicate_keep_option::KEEP_FIRST); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_first, got_first->view()); // Keep the last duplicate row cudf::test::fixed_width_column_wrapper<int32_t> exp_col1_last{{4, 3, 5, 8, 5}}; cudf::test::fixed_width_column_wrapper<float> exp_col2_last{{5, 3, 4, 9, 4}}; cudf::test::fixed_width_column_wrapper<int32_t> exp_col1_key_last{{20, 20, 19, 21, 9}}; cudf::test::fixed_width_column_wrapper<int32_t> exp_col2_key_last{{19, 20, 20, 9, 21}}; cudf::table_view expected_last{ {exp_col1_last, exp_col2_last, exp_col1_key_last, exp_col2_key_last}}; auto got_last = unique(input, keys, cudf::duplicate_keep_option::KEEP_LAST); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_last, got_last->view()); // Keep no duplicate rows cudf::test::fixed_width_column_wrapper<int32_t> exp_col1_unique{{3, 5, 8, 5}}; cudf::test::fixed_width_column_wrapper<float> exp_col2_unique{{3, 4, 9, 4}}; cudf::test::fixed_width_column_wrapper<int32_t> exp_col1_key_unique{{20, 19, 21, 9}}; cudf::test::fixed_width_column_wrapper<int32_t> exp_col2_key_unique{{20, 20, 9, 21}}; cudf::table_view expected_unique{ {exp_col1_unique, exp_col2_unique, exp_col1_key_unique, exp_col2_key_unique}}; auto got_unique = unique(input, keys, cudf::duplicate_keep_option::KEEP_NONE); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_unique, got_unique->view()); } TEST_F(Unique, KeepFirstWithNull) { cudf::test::fixed_width_column_wrapper<int32_t> col{{5, 4, 3, 2, 5, 8, 1}, {1, 0, 1, 1, 1, 1, 1}}; cudf::test::fixed_width_column_wrapper<int32_t> key{{20, 20, 20, 20, 19, 21, 19}, {1, 1, 0, 0, 1, 1, 1}}; cudf::table_view input{{col, key}}; std::vector<cudf::size_type> keys{1}; // nulls are equal cudf::test::fixed_width_column_wrapper<int32_t> exp_col_first_equal{{5, 3, 5, 8, 1}, {1, 1, 1, 1, 1}}; cudf::test::fixed_width_column_wrapper<int32_t> exp_key_col_first_equal{{20, 20, 19, 21, 19}, {1, 0, 1, 1, 1}}; cudf::table_view expected_first_equal{{exp_col_first_equal, exp_key_col_first_equal}}; auto got_first_equal = unique(input, keys, cudf::duplicate_keep_option::KEEP_FIRST, null_equality::EQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_first_equal, got_first_equal->view()); // nulls are unequal cudf::test::fixed_width_column_wrapper<int32_t> exp_col_first_unequal{{5, 3, 2, 5, 8, 1}, {1, 1, 1, 1, 1, 1}}; cudf::test::fixed_width_column_wrapper<int32_t> exp_key_col_first_unequal{ {20, 20, 20, 19, 21, 19}, {1, 0, 0, 1, 1, 1}}; cudf::table_view expected_first_unequal{{exp_col_first_unequal, exp_key_col_first_unequal}}; auto got_first_unequal = unique(input, keys, cudf::duplicate_keep_option::KEEP_FIRST, null_equality::UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_first_unequal, got_first_unequal->view()); } TEST_F(Unique, KeepLastWithNull) { cudf::test::fixed_width_column_wrapper<int32_t> col{{5, 4, 3, 2, 5, 8, 1}, {1, 0, 1, 1, 1, 1, 1}}; cudf::test::fixed_width_column_wrapper<int32_t> key{{20, 20, 20, 20, 19, 21, 19}, {1, 1, 0, 0, 1, 1, 1}}; cudf::table_view input{{col, key}}; std::vector<cudf::size_type> keys{1}; // nulls are equal cudf::test::fixed_width_column_wrapper<int32_t> exp_col_last_equal{{4, 2, 5, 8, 1}, {0, 1, 1, 1, 1}}; cudf::test::fixed_width_column_wrapper<int32_t> exp_key_col_last_equal{{20, 20, 19, 21, 19}, {1, 0, 1, 1, 1}}; cudf::table_view expected_last_equal{{exp_col_last_equal, exp_key_col_last_equal}}; auto got_last_equal = unique(input, keys, cudf::duplicate_keep_option::KEEP_LAST, null_equality::EQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_last_equal, got_last_equal->view()); // nulls are unequal cudf::test::fixed_width_column_wrapper<int32_t> exp_col_last_unequal{{4, 3, 2, 5, 8, 1}, {0, 1, 1, 1, 1, 1}}; cudf::test::fixed_width_column_wrapper<int32_t> exp_key_col_last_unequal{{20, 20, 20, 19, 21, 19}, {1, 0, 0, 1, 1, 1}}; cudf::table_view expected_last_unequal{{exp_col_last_unequal, exp_key_col_last_unequal}}; auto got_last_unequal = unique(input, keys, cudf::duplicate_keep_option::KEEP_LAST, null_equality::UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_last_unequal, got_last_unequal->view()); } TEST_F(Unique, KeepNoneWithNull) { cudf::test::fixed_width_column_wrapper<int32_t> col{{5, 4, 3, 2, 5, 8, 1}, {1, 0, 1, 1, 1, 1, 1}}; cudf::test::fixed_width_column_wrapper<int32_t> key{{20, 20, 20, 20, 19, 21, 19}, {1, 1, 0, 0, 1, 1, 1}}; cudf::table_view input{{col, key}}; std::vector<cudf::size_type> keys{1}; // nulls are equal cudf::test::fixed_width_column_wrapper<int32_t> exp_col_unique_equal{{5, 8, 1}, {1, 1, 1}}; cudf::test::fixed_width_column_wrapper<int32_t> exp_key_col_unique_equal{{19, 21, 19}, {1, 1, 1}}; cudf::table_view expected_unique_equal{{exp_col_unique_equal, exp_key_col_unique_equal}}; auto got_unique_equal = unique(input, keys, cudf::duplicate_keep_option::KEEP_NONE, null_equality::EQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_unique_equal, got_unique_equal->view()); // nulls are unequal cudf::test::fixed_width_column_wrapper<int32_t> exp_col_unique_unequal{{3, 2, 5, 8, 1}, {1, 1, 1, 1, 1}}; cudf::test::fixed_width_column_wrapper<int32_t> exp_key_col_unique_unequal{{20, 20, 19, 21, 19}, {0, 0, 1, 1, 1}}; cudf::table_view expected_unique_unequal{{exp_col_unique_unequal, exp_key_col_unique_unequal}}; auto got_unique_unequal = unique(input, keys, cudf::duplicate_keep_option::KEEP_NONE, null_equality::UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_unique_unequal, got_unique_unequal->view()); } TEST_F(Unique, ListsKeepAny) { // Column(s) used to test KEEP_ANY needs to have same rows for same keys because KEEP_ANY is // nondeterministic. // clang-format off auto const idx = int32s_col{0, 0, 2, 1, 1, 3, 5, 5, 6, 4, 4, 4}; auto const keys = lists_col{{}, {}, {1, 1}, {1}, {1}, {1, 2}, {2}, {2}, {2, 1}, {2, 2}, {2, 2}, {2, 2}}; // clang-format on auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; auto const exp_idx = int32s_col{0, 2, 1, 3, 5, 6, 4}; auto const exp_keys = lists_col{{}, {1, 1}, {1}, {1, 2}, {2}, {2, 1}, {2, 2}}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::unique(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } TEST_F(Unique, ListsKeepFirstLastNone) { // clang-format off auto const idx = int32s_col{0, 1, 2, 1, 2, 3, 5, 6, 6, 4, 5, 6}; auto const keys = lists_col{{}, {}, {1, 1}, {1}, {1}, {1, 2}, {2}, {2}, {2, 1}, {2, 2}, {2, 2}, {2, 2}}; // clang-format on auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP FIRST { auto const exp_idx = int32s_col{0, 2, 1, 3, 5, 6, 4}; auto const exp_keys = lists_col{{}, {1, 1}, {1}, {1, 2}, {2}, {2, 1}, {2, 2}}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::unique(input, key_idx, KEEP_FIRST); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // KEEP LAST { auto const exp_idx = int32s_col{1, 2, 2, 3, 6, 6, 6}; auto const exp_keys = lists_col{{}, {1, 1}, {1}, {1, 2}, {2}, {2, 1}, {2, 2}}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::unique(input, key_idx, KEEP_LAST); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // KEEP NONE { auto const exp_idx = int32s_col{2, 3, 6}; auto const exp_keys = lists_col{{1, 1}, {1, 2}, {2, 1}}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::unique(input, key_idx, KEEP_NONE); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } } TEST_F(Unique, NullableListsKeepAny) { // Column(s) used to test KEEP_ANY needs to have same rows for same keys because KEEP_ANY is // nondeterministic. // clang-format off auto const idx = int32s_col{0, 0, 2, 1, 1, 3, 3, 5, 5, 6, 4, 4}; auto const keys = lists_col{{{}, {}, {1, 1}, {1}, {1}, {} /*NULL*/, {} /*NULL*/, {2}, {2}, {2, 1}, {2, 2}, {2, 2}}, nulls_at({5, 6})}; // clang-format on auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal. { auto const exp_idx = int32s_col{0, 2, 1, 3, 5, 6, 4}; auto const exp_keys = lists_col{{{}, {1, 1}, {1}, {} /*NULL*/, {2}, {2, 1}, {2, 2}}, null_at(3)}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::unique(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // Nulls are unequal. { auto const exp_idx = int32s_col{0, 2, 1, 3, 3, 5, 6, 4}; auto const exp_keys = lists_col{{{}, {1, 1}, {1}, {} /*NULL*/, {} /*NULL*/, {2}, {2, 1}, {2, 2}}, nulls_at({3, 4})}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::unique(input, key_idx, KEEP_ANY, NULL_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } } TEST_F(Unique, NullableListsKeepFirstLastNone) { // clang-format off auto const idx = int32s_col{0, 1, 2, 1, 2, 3, 4, 5, 6, 6, 4, 5}; auto const keys = lists_col{{{}, {}, {1, 1}, {1}, {1}, {} /*NULL*/, {} /*NULL*/, {2}, {2}, {2, 1}, {2, 2}, {2, 2}}, nulls_at({5, 6})}; // clang-format on auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP FIRST {// Nulls are equal. {auto const exp_idx = int32s_col{0, 2, 1, 3, 5, 6, 4}; auto const exp_keys = lists_col{{{}, {1, 1}, {1}, {} /*NULL*/, {2}, {2, 1}, {2, 2}}, null_at(3)}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::unique(input, key_idx, KEEP_FIRST); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // Nulls are unequal. { auto const exp_idx = int32s_col{0, 2, 1, 3, 4, 5, 6, 4}; auto const exp_keys = lists_col{{{}, {1, 1}, {1}, {} /*NULL*/, {} /*NULL*/, {2}, {2, 1}, {2, 2}}, nulls_at({3, 4})}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::unique(input, key_idx, KEEP_FIRST, NULL_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } } // KEEP LAST {// Nulls are equal. {auto const exp_idx = int32s_col{1, 2, 2, 4, 6, 6, 5}; auto const exp_keys = lists_col{{{}, {1, 1}, {1}, {} /*NULL*/, {2}, {2, 1}, {2, 2}}, null_at(3)}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::unique(input, key_idx, KEEP_LAST); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // Nulls are unequal. { auto const exp_idx = int32s_col{1, 2, 2, 3, 4, 6, 6, 5}; auto const exp_keys = lists_col{{{}, {1, 1}, {1}, {} /*NULL*/, {} /*NULL*/, {2}, {2, 1}, {2, 2}}, nulls_at({3, 4})}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::unique(input, key_idx, KEEP_LAST, NULL_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } } // KEEP NONE { // Nulls are equal. { auto const exp_idx = int32s_col{2, 6}; auto const exp_keys = lists_col{{{1, 1}, {2, 1}}, nulls_at({})}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::unique(input, key_idx, KEEP_NONE); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } // Nulls are unequal. { auto const exp_idx = int32s_col{2, 3, 4, 6}; auto const exp_keys = lists_col{{{1, 1}, {} /*NULL*/, {} /*NULL*/, {2, 1}}, nulls_at({1, 2})}; auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::unique(input, key_idx, KEEP_NONE, NULL_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } } } TEST_F(Unique, ListsOfStructsKeepAny) { // Constructing a list of structs of two elements // 0. [] == // 1. [] != // 2. Null == // 3. Null != // 4. [Null, Null] != // 5. [Null] == // 6. [Null] == // 7. [Null] != // 8. [{Null, Null}] != // 9. [{1,'a'}, {2,'b'}] != // 10. [{0,'a'}, {2,'b'}] != // 11. [{0,'a'}, {2,'c'}] == // 12. [{0,'a'}, {2,'c'}] != // 13. [{0,Null}] == // 14. [{0,Null}] != // 15. [{Null, 'b'}] == // 16. [{Null, 'b'}] auto const structs = [] { auto child1 = int32s_col{{XXX, XXX, XXX, XXX, XXX, null, 1, 2, 0, 2, 0, 2, 0, 2, 0, 0, null, null}, nulls_at({5, 16, 17})}; auto child2 = strings_col{{"" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*null*/, "a", "b", "a", "b", "a", "c", "a", "c", "" /*null*/, "" /*null*/, "b", "b"}, nulls_at({5, 14, 15})}; return structs_col{{child1, child2}, nulls_at({0, 1, 2, 3, 4})}; }(); auto const offsets = int32s_col{0, 0, 0, 0, 0, 2, 3, 4, 5, 6, 8, 10, 12, 14, 15, 16, 17, 18}; auto const null_it = nulls_at({2, 3}); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(null_it, null_it + 17); auto const keys = cudf::column_view(cudf::data_type(cudf::type_id::LIST), 17, nullptr, static_cast<cudf::bitmask_type const*>(null_mask.data()), null_count, 0, {offsets, structs}); auto const idx = int32s_col{1, 1, 2, 2, 3, 4, 4, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10}; auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal. { auto const expect_map = int32s_col{0, 2, 4, 5, 8, 9, 10, 11, 13, 15}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::unique(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } // Nulls are unequal. { auto const expect_map = int32s_col{0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::unique(input, key_idx, KEEP_ANY, NULL_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } } TEST_F(Unique, ListsOfStructsKeepFirstLastNone) { // Constructing a list of structs of two elements // 0. [] == // 1. [] != // 2. Null == // 3. Null != // 4. [Null, Null] != // 5. [Null] == // 6. [Null] == // 7. [Null] != // 8. [{Null, Null}] != // 9. [{1,'a'}, {2,'b'}] != // 10. [{0,'a'}, {2,'b'}] != // 11. [{0,'a'}, {2,'c'}] == // 12. [{0,'a'}, {2,'c'}] != // 13. [{0,Null}] == // 14. [{0,Null}] != // 15. [{Null, 'b'}] == // 16. [{Null, 'b'}] auto const structs = [] { auto child1 = int32s_col{{XXX, XXX, XXX, XXX, XXX, null, 1, 2, 0, 2, 0, 2, 0, 2, 0, 0, null, null}, nulls_at({5, 16, 17})}; auto child2 = strings_col{{"" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*XXX*/, "" /*null*/, "a", "b", "a", "b", "a", "c", "a", "c", "" /*null*/, "" /*null*/, "b", "b"}, nulls_at({5, 14, 15})}; return structs_col{{child1, child2}, nulls_at({0, 1, 2, 3, 4})}; }(); auto const offsets = int32s_col{0, 0, 0, 0, 0, 2, 3, 4, 5, 6, 8, 10, 12, 14, 15, 16, 17, 18}; auto const null_it = nulls_at({2, 3}); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(null_it, null_it + 17); auto const keys = cudf::column_view(cudf::data_type(cudf::type_id::LIST), 17, nullptr, static_cast<cudf::bitmask_type const*>(null_mask.data()), null_count, 0, {offsets, structs}); auto const idx = int32s_col{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP_FIRST { auto const expect_map = int32s_col{0, 2, 4, 5, 8, 9, 10, 11, 13, 15}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::unique(input, key_idx, KEEP_FIRST); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } // KEEP_LAST { auto const expect_map = int32s_col{1, 3, 4, 7, 8, 9, 10, 12, 14, 16}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::unique(input, key_idx, KEEP_LAST); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } // KEEP_NONE { auto const expect_map = int32s_col{4, 8, 9, 10}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::unique(input, key_idx, KEEP_NONE); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } } TEST_F(Unique, ListsOfEmptyStructsKeepAny) { // 0. [] == // 1. [] != // 2. Null == // 3. Null != // 4. [Null, Null] == // 5. [Null, Null] == // 6. [Null, Null] != // 7. [Null] == // 8. [Null] != // 9. [{}] == // 10. [{}] != // 11. [{}, {}] == // 12. [{}, {}] auto const structs_null_it = nulls_at({0, 1, 2, 3, 4, 5, 6, 7}); auto [structs_null_mask, structs_null_count] = cudf::test::detail::make_null_mask(structs_null_it, structs_null_it + 14); auto const structs = cudf::column_view(cudf::data_type(cudf::type_id::STRUCT), 14, nullptr, static_cast<cudf::bitmask_type const*>(structs_null_mask.data()), structs_null_count); auto const offsets = int32s_col{0, 0, 0, 0, 0, 2, 4, 6, 7, 8, 9, 10, 12, 14}; auto const lists_null_it = nulls_at({2, 3}); auto [lists_null_mask, lists_null_count] = cudf::test::detail::make_null_mask(lists_null_it, lists_null_it + 13); auto const keys = cudf::column_view(cudf::data_type(cudf::type_id::LIST), 13, nullptr, static_cast<cudf::bitmask_type const*>(lists_null_mask.data()), lists_null_count, 0, {offsets, structs}); auto const idx = int32s_col{1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6}; auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal. { auto const expect_map = int32s_col{0, 2, 4, 7, 9, 11}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::unique(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } // Nulls are unequal. { auto const expect_map = int32s_col{0, 2, 3, 4, 5, 6, 7, 8, 9, 11}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::unique(input, key_idx, KEEP_ANY, NULL_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } } TEST_F(Unique, EmptyDeepListKeepAny) { // List<List<int>>, where all lists are empty: // // 0. [] // 1. [] // 2. Null // 3. Null auto const keys = lists_col{{lists_col{}, lists_col{}, lists_col{}, lists_col{}}, nulls_at({2, 3})}; auto const idx = int32s_col{1, 1, 2, 2}; auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal. { auto const expect_map = int32s_col{0, 2}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::unique(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } // Nulls are unequal. { auto const expect_map = int32s_col{0, 2, 3}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::unique(input, key_idx, KEEP_ANY, NULL_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } } TEST_F(Unique, StructsOfStructsKeepAny) { // +-----------------+ // | s1{s2{a,b}, c} | // +-----------------+ // 0 | { {1, 1}, 5} | // 1 | { {1, 1}, 5} | // Same as 0 // 2 | { {1, 2}, 4} | // 3 | { Null, 6} | // 4 | { Null, 4} | // 5 | { Null, 4} | // Same as 4 // 6 | Null | // 7 | Null | // Same as 6 // 8 | { {2, 1}, 5} | auto s1 = [&] { auto a = int32s_col{1, 1, 1, XXX, XXX, XXX, 2, 1, 2}; auto b = int32s_col{1, 1, 2, XXX, XXX, XXX, 2, 1, 1}; auto s2 = structs_col{{a, b}, nulls_at({3, 4, 5})}; auto c = int32s_col{5, 5, 4, 6, 4, 4, 3, 3, 5}; std::vector<std::unique_ptr<cudf::column>> s1_children; s1_children.emplace_back(s2.release()); s1_children.emplace_back(c.release()); auto const null_it = nulls_at({6, 7}); return structs_col(std::move(s1_children), std::vector<bool>{null_it, null_it + 9}); }(); auto const idx = int32s_col{0, 0, 1, 2, 3, 3, 4, 4, 5}; auto const input = cudf::table_view{{idx, s1}}; auto const key_idx = std::vector<cudf::size_type>{1}; // Nulls are equal. { auto const expect_map = int32s_col{0, 2, 3, 4, 6, 8}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::unique(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } // Nulls are unequal. { auto const expect_map = int32s_col{0, 2, 3, 4, 5, 6, 7, 8}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::unique(input, key_idx, KEEP_ANY, NULL_UNEQUAL); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } } TEST_F(Unique, StructsOfListsKeepAny) { auto const idx = int32s_col{1, 1, 2, 3, 4, 4, 4, 5, 5, 6}; auto const keys = [] { // All child columns are identical. auto child1 = lists_col{{1}, {1}, {1, 1}, {1, 2}, {2, 2}, {2, 2}, {2, 2}, {2}, {2}, {2, 1}}; auto child2 = lists_col{{1}, {1}, {1, 1}, {1, 2}, {2, 2}, {2, 2}, {2, 2}, {2}, {2}, {2, 1}}; auto child3 = lists_col{{1}, {1}, {1, 1}, {1, 2}, {2, 2}, {2, 2}, {2, 2}, {2}, {2}, {2, 1}}; return structs_col{{child1, child2, child3}}; }(); auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; auto const exp_idx = int32s_col{1, 2, 3, 4, 5, 6}; auto const exp_keys = [] { auto child1 = lists_col{{1}, {1, 1}, {1, 2}, {2, 2}, {2}, {2, 1}}; auto child2 = lists_col{{1}, {1, 1}, {1, 2}, {2, 2}, {2}, {2, 1}}; auto child3 = lists_col{{1}, {1, 1}, {1, 2}, {2, 2}, {2}, {2, 1}}; return structs_col{{child1, child2, child3}}; }(); auto const expected = cudf::table_view{{exp_idx, exp_keys}}; auto const result = cudf::unique(input, key_idx, KEEP_ANY); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *result); } TEST_F(Unique, StructsOfListsKeepFirstLastNone) { auto const idx = int32s_col{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto const keys = [] { // All child columns are identical. auto child1 = lists_col{{1}, {1}, {1, 1}, {1, 2}, {2, 2}, {2, 2}, {2, 2}, {2}, {2}, {2, 1}}; auto child2 = lists_col{{1}, {1}, {1, 1}, {1, 2}, {2, 2}, {2, 2}, {2, 2}, {2}, {2}, {2, 1}}; auto child3 = lists_col{{1}, {1}, {1, 1}, {1, 2}, {2, 2}, {2, 2}, {2, 2}, {2}, {2}, {2, 1}}; return structs_col{{child1, child2, child3}}; }(); auto const input = cudf::table_view{{idx, keys}}; auto const key_idx = std::vector<cudf::size_type>{1}; // KEEP_FIRST { auto const expect_map = int32s_col{0, 2, 3, 4, 7, 9}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::unique(input, key_idx, KEEP_FIRST); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } // KEEP_LAST { auto const expect_map = int32s_col{1, 2, 3, 6, 8, 9}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::unique(input, key_idx, KEEP_LAST); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } // KEEP_NONE { auto const expect_map = int32s_col{2, 3, 9}; auto const expect_table = cudf::gather(input, expect_map); auto const result = cudf::unique(input, key_idx, KEEP_NONE); CUDF_TEST_EXPECT_TABLES_EQUAL(*expect_table, *result); } }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/fixed_point/fixed_point_tests.cu
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/detail/utilities/vector_factories.hpp> #include <cudf/fixed_point/fixed_point.hpp> #include <cudf/utilities/default_stream.hpp> #include <cudf/utilities/type_dispatcher.hpp> #include <rmm/exec_policy.hpp> #include <thrust/reduce.h> #include <thrust/scan.h> #include <thrust/transform.h> #include <algorithm> #include <limits> #include <vector> using namespace numeric; struct FixedPointTest : public cudf::test::BaseFixture {}; template <typename T> struct FixedPointTestAllReps : public cudf::test::BaseFixture {}; using RepresentationTypes = ::testing::Types<int32_t, int64_t, __int128_t>; TYPED_TEST_SUITE(FixedPointTestAllReps, RepresentationTypes); TYPED_TEST(FixedPointTestAllReps, DecimalXXThrust) { using decimalXX = fixed_point<TypeParam, Radix::BASE_10>; std::vector<decimalXX> vec1(1000); std::vector<int32_t> vec2(1000); std::iota(std::begin(vec1), std::end(vec1), decimalXX{0, scale_type{-2}}); std::iota(std::begin(vec2), std::end(vec2), 0); auto const res1 = thrust::reduce(std::cbegin(vec1), std::cend(vec1), decimalXX{0, scale_type{-2}}); auto const res2 = std::accumulate(std::cbegin(vec2), std::cend(vec2), 0); EXPECT_EQ(static_cast<int32_t>(res1), res2); std::vector<int32_t> vec3(vec1.size()); thrust::transform(std::cbegin(vec1), std::cend(vec1), std::begin(vec3), [](auto const& e) { return static_cast<int32_t>(e); }); EXPECT_EQ(vec2, vec3); } struct cast_to_int32_fn { using decimal32 = fixed_point<int32_t, Radix::BASE_10>; int32_t __host__ __device__ operator()(decimal32 fp) { return static_cast<int32_t>(fp); } }; TEST_F(FixedPointTest, DecimalXXThrustOnDevice) { using decimal32 = fixed_point<int32_t, Radix::BASE_10>; std::vector<decimal32> vec1(1000, decimal32{1, scale_type{-2}}); auto d_vec1 = cudf::detail::make_device_uvector_sync( vec1, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const sum = thrust::reduce(rmm::exec_policy(cudf::get_default_stream()), std::cbegin(d_vec1), std::cend(d_vec1), decimal32{0, scale_type{-2}}); EXPECT_EQ(static_cast<int32_t>(sum), 1000); // TODO: Once nvbugs/1990211 is fixed (ExclusiveSum initial_value = 0 bug) // change inclusive scan to run on device (avoid copying to host) thrust::inclusive_scan(std::cbegin(vec1), std::cend(vec1), std::begin(vec1)); d_vec1 = cudf::detail::make_device_uvector_sync( vec1, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); std::vector<int32_t> vec2(1000); std::iota(std::begin(vec2), std::end(vec2), 1); auto const res1 = thrust::reduce(rmm::exec_policy(cudf::get_default_stream()), std::cbegin(d_vec1), std::cend(d_vec1), decimal32{0, scale_type{-2}}); auto const res2 = std::accumulate(std::cbegin(vec2), std::cend(vec2), 0); EXPECT_EQ(static_cast<int32_t>(res1), res2); rmm::device_uvector<int32_t> d_vec3(1000, cudf::get_default_stream()); thrust::transform(rmm::exec_policy(cudf::get_default_stream()), std::cbegin(d_vec1), std::cend(d_vec1), std::begin(d_vec3), cast_to_int32_fn{}); auto vec3 = cudf::detail::make_std_vector_sync(d_vec3, cudf::get_default_stream()); EXPECT_EQ(vec2, vec3); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/fixed_point/fixed_point_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/binaryop.hpp> #include <cudf/fixed_point/fixed_point.hpp> #include <cudf/null_mask.hpp> #include <algorithm> #include <limits> #include <numeric> #include <type_traits> #include <vector> using namespace numeric; struct FixedPointTest : public cudf::test::BaseFixture {}; template <typename T> struct FixedPointTestAllReps : public cudf::test::BaseFixture {}; using RepresentationTypes = ::testing::Types<int32_t, int64_t>; TYPED_TEST_SUITE(FixedPointTestAllReps, RepresentationTypes); TYPED_TEST(FixedPointTestAllReps, SimpleDecimalXXConstruction) { using decimalXX = fixed_point<TypeParam, Radix::BASE_10>; decimalXX num0{1.234567, scale_type{0}}; decimalXX num1{1.234567, scale_type{-1}}; decimalXX num2{1.234567, scale_type{-2}}; decimalXX num3{1.234567, scale_type{-3}}; decimalXX num4{1.234567, scale_type{-4}}; decimalXX num5{1.234567, scale_type{-5}}; decimalXX num6{1.234567, scale_type{-6}}; EXPECT_EQ(1, static_cast<double>(num0)); EXPECT_EQ(1.2, static_cast<double>(num1)); EXPECT_EQ(1.23, static_cast<double>(num2)); EXPECT_EQ(1.234, static_cast<double>(num3)); EXPECT_EQ(1.2345, static_cast<double>(num4)); EXPECT_EQ(1.23456, static_cast<double>(num5)); EXPECT_EQ(1.234567, static_cast<double>(num6)); } TYPED_TEST(FixedPointTestAllReps, SimpleNegativeDecimalXXConstruction) { using decimalXX = fixed_point<TypeParam, Radix::BASE_10>; decimalXX num0{-1.234567, scale_type{0}}; decimalXX num1{-1.234567, scale_type{-1}}; decimalXX num2{-1.234567, scale_type{-2}}; decimalXX num3{-1.234567, scale_type{-3}}; decimalXX num4{-1.234567, scale_type{-4}}; decimalXX num5{-1.234567, scale_type{-5}}; decimalXX num6{-1.234567, scale_type{-6}}; EXPECT_EQ(-1, static_cast<double>(num0)); EXPECT_EQ(-1.2, static_cast<double>(num1)); EXPECT_EQ(-1.23, static_cast<double>(num2)); EXPECT_EQ(-1.234, static_cast<double>(num3)); EXPECT_EQ(-1.2345, static_cast<double>(num4)); EXPECT_EQ(-1.23456, static_cast<double>(num5)); EXPECT_EQ(-1.234567, static_cast<double>(num6)); } TYPED_TEST(FixedPointTestAllReps, PaddedDecimalXXConstruction) { using decimalXX = fixed_point<TypeParam, Radix::BASE_10>; decimalXX a{1.1, scale_type{-1}}; decimalXX b{1.01, scale_type{-2}}; decimalXX c{1.001, scale_type{-3}}; decimalXX d{1.0001, scale_type{-4}}; decimalXX e{1.00001, scale_type{-5}}; decimalXX f{1.000001, scale_type{-6}}; decimalXX x{1.000123, scale_type{-8}}; decimalXX y{0.000123, scale_type{-8}}; EXPECT_EQ(1.1, static_cast<double>(a)); EXPECT_EQ(1.01, static_cast<double>(b)); EXPECT_EQ(1, static_cast<double>(c)); // intentional (inherited problem from floating point) EXPECT_EQ(1.0001, static_cast<double>(d)); EXPECT_EQ(1.00001, static_cast<double>(e)); EXPECT_EQ(1, static_cast<double>(f)); // intentional (inherited problem from floating point) EXPECT_TRUE(1.000123 - static_cast<double>(x) < std::numeric_limits<double>::epsilon()); EXPECT_EQ(0.000123, static_cast<double>(y)); } TYPED_TEST(FixedPointTestAllReps, SimpleBinaryFPConstruction) { using binary_fp = fixed_point<TypeParam, Radix::BASE_2>; binary_fp num0{10, scale_type{0}}; binary_fp num1{10, scale_type{1}}; binary_fp num2{10, scale_type{2}}; binary_fp num3{10, scale_type{3}}; binary_fp num4{10, scale_type{4}}; binary_fp num5{1.24, scale_type{0}}; binary_fp num6{1.24, scale_type{-1}}; binary_fp num7{1.32, scale_type{-2}}; binary_fp num8{1.41, scale_type{-3}}; binary_fp num9{1.45, scale_type{-4}}; EXPECT_EQ(10, static_cast<double>(num0)); EXPECT_EQ(10, static_cast<double>(num1)); EXPECT_EQ(8, static_cast<double>(num2)); EXPECT_EQ(8, static_cast<double>(num3)); EXPECT_EQ(0, static_cast<double>(num4)); EXPECT_EQ(1, static_cast<double>(num5)); EXPECT_EQ(1, static_cast<double>(num6)); EXPECT_EQ(1.25, static_cast<double>(num7)); EXPECT_EQ(1.375, static_cast<double>(num8)); EXPECT_EQ(1.4375, static_cast<double>(num9)); } TYPED_TEST(FixedPointTestAllReps, MoreSimpleBinaryFPConstruction) { using binary_fp = fixed_point<TypeParam, Radix::BASE_2>; binary_fp num0{1.25, scale_type{-2}}; binary_fp num1{2.1, scale_type{-4}}; EXPECT_EQ(1.25, static_cast<double>(num0)); EXPECT_EQ(2.0625, static_cast<double>(num1)); } TYPED_TEST(FixedPointTestAllReps, SimpleDecimalXXMath) { using decimalXX = fixed_point<TypeParam, Radix::BASE_10>; decimalXX ONE{1, scale_type{-2}}; decimalXX TWO{2, scale_type{-2}}; decimalXX THREE{3, scale_type{-2}}; decimalXX SIX{6, scale_type{-2}}; EXPECT_TRUE(ONE + ONE == TWO); EXPECT_EQ(ONE + ONE, TWO); EXPECT_EQ(ONE * TWO, TWO); EXPECT_EQ(THREE * TWO, SIX); EXPECT_EQ(THREE - TWO, ONE); EXPECT_EQ(TWO / ONE, TWO); EXPECT_EQ(SIX / TWO, THREE); decimalXX a{1.23, scale_type{-2}}; decimalXX b{0, scale_type{0}}; EXPECT_EQ(a + b, a); EXPECT_EQ(a - b, a); } TYPED_TEST(FixedPointTestAllReps, ComparisonOperators) { using decimalXX = fixed_point<TypeParam, Radix::BASE_10>; decimalXX ONE{1, scale_type{-1}}; decimalXX TWO{2, scale_type{-2}}; decimalXX THREE{3, scale_type{-3}}; decimalXX SIX{6, scale_type{-4}}; EXPECT_TRUE(ONE + ONE >= TWO); EXPECT_TRUE(ONE + ONE <= TWO); EXPECT_TRUE(ONE * TWO < THREE); EXPECT_TRUE(THREE * TWO > THREE); EXPECT_TRUE(THREE - TWO >= ONE); EXPECT_TRUE(TWO / ONE < THREE); EXPECT_TRUE(SIX / TWO >= ONE); } TYPED_TEST(FixedPointTestAllReps, DecimalXXTrickyDivision) { using decimalXX = fixed_point<TypeParam, Radix::BASE_10>; decimalXX ONE_1{1, scale_type{1}}; decimalXX SIX_0{6, scale_type{0}}; decimalXX SIX_1{6, scale_type{1}}; decimalXX TEN_0{10, scale_type{0}}; decimalXX TEN_1{10, scale_type{1}}; decimalXX SIXTY_1{60, scale_type{1}}; EXPECT_EQ(static_cast<int32_t>(ONE_1), 0); EXPECT_EQ(static_cast<int32_t>(SIX_1), 0); EXPECT_EQ(static_cast<int32_t>(TEN_0), 10); EXPECT_EQ(static_cast<int32_t>(SIXTY_1), 60); EXPECT_EQ(SIXTY_1 / TEN_0, ONE_1); EXPECT_EQ(SIXTY_1 / TEN_1, SIX_0); decimalXX A{34.56, scale_type{-2}}; decimalXX B{1.234, scale_type{-3}}; decimalXX C{1, scale_type{-2}}; EXPECT_EQ(static_cast<int32_t>(A / B), 20); EXPECT_EQ(static_cast<int32_t>((A * C) / B), 28); decimalXX n{28, scale_type{1}}; EXPECT_EQ(static_cast<int32_t>(n), 20); } TYPED_TEST(FixedPointTestAllReps, DecimalXXRounding) { using decimalXX = fixed_point<TypeParam, Radix::BASE_10>; decimalXX ZERO_0{0, scale_type{0}}; decimalXX ZERO_1{4, scale_type{1}}; decimalXX THREE_0{3, scale_type{0}}; decimalXX FOUR_0{4, scale_type{0}}; decimalXX FIVE_0{5, scale_type{0}}; decimalXX TEN_0{10, scale_type{0}}; decimalXX TEN_1{10, scale_type{1}}; decimalXX FOURTEEN_0{14, scale_type{0}}; decimalXX FIFTEEN_0{15, scale_type{0}}; EXPECT_EQ(ZERO_0, ZERO_1); EXPECT_EQ(TEN_0, TEN_1); EXPECT_EQ(ZERO_1 + TEN_1, TEN_1); EXPECT_EQ(FOUR_0 + TEN_1, FOURTEEN_0); EXPECT_TRUE(ZERO_0 == ZERO_1); EXPECT_TRUE(FIVE_0 != TEN_1); EXPECT_TRUE(FIVE_0 + FIVE_0 + FIVE_0 == FIFTEEN_0); EXPECT_TRUE(FIVE_0 + FIVE_0 + FIVE_0 != TEN_1); EXPECT_TRUE(FIVE_0 * THREE_0 == FIFTEEN_0); EXPECT_TRUE(FIVE_0 * THREE_0 != TEN_1); } TYPED_TEST(FixedPointTestAllReps, ArithmeticWithDifferentScales) { using decimalXX = fixed_point<TypeParam, Radix::BASE_10>; decimalXX a{1, scale_type{0}}; decimalXX b{1.2, scale_type{-1}}; decimalXX c{1.23, scale_type{-2}}; decimalXX d{1.111, scale_type{-3}}; decimalXX x{2.2, scale_type{-1}}; decimalXX y{3.43, scale_type{-2}}; decimalXX z{4.541, scale_type{-3}}; decimalXX xx{0.2, scale_type{-1}}; decimalXX yy{0.03, scale_type{-2}}; decimalXX zz{0.119, scale_type{-3}}; EXPECT_EQ(a + b, x); EXPECT_EQ(a + b + c, y); EXPECT_EQ(a + b + c + d, z); EXPECT_EQ(b - a, xx); EXPECT_EQ(c - b, yy); EXPECT_EQ(c - d, zz); } TYPED_TEST(FixedPointTestAllReps, RescaledTest) { using decimalXX = fixed_point<TypeParam, Radix::BASE_10>; decimalXX num0{1, scale_type{0}}; decimalXX num1{1.2, scale_type{-1}}; decimalXX num2{1.23, scale_type{-2}}; decimalXX num3{1.234, scale_type{-3}}; decimalXX num4{1.2345, scale_type{-4}}; decimalXX num5{1.23456, scale_type{-5}}; decimalXX num6{1.234567, scale_type{-6}}; EXPECT_EQ(num0, num6.rescaled(scale_type{0})); EXPECT_EQ(num1, num6.rescaled(scale_type{-1})); EXPECT_EQ(num2, num6.rescaled(scale_type{-2})); EXPECT_EQ(num3, num6.rescaled(scale_type{-3})); EXPECT_EQ(num4, num6.rescaled(scale_type{-4})); EXPECT_EQ(num5, num6.rescaled(scale_type{-5})); } TYPED_TEST(FixedPointTestAllReps, RescaledRounding) { using decimalXX = fixed_point<TypeParam, Radix::BASE_10>; decimalXX num0{1500, scale_type{0}}; decimalXX num1{1499, scale_type{0}}; decimalXX num2{-1499, scale_type{0}}; decimalXX num3{-1500, scale_type{0}}; EXPECT_EQ(1000, static_cast<TypeParam>(num0.rescaled(scale_type{3}))); EXPECT_EQ(1000, static_cast<TypeParam>(num1.rescaled(scale_type{3}))); EXPECT_EQ(-1000, static_cast<TypeParam>(num2.rescaled(scale_type{3}))); EXPECT_EQ(-1000, static_cast<TypeParam>(num3.rescaled(scale_type{3}))); } TYPED_TEST(FixedPointTestAllReps, BoolConversion) { using decimalXX = fixed_point<TypeParam, Radix::BASE_10>; decimalXX truthy_value{1.234567, scale_type{0}}; decimalXX falsy_value{0, scale_type{0}}; // Test explicit conversions EXPECT_EQ(static_cast<bool>(truthy_value), true); EXPECT_EQ(static_cast<bool>(falsy_value), false); // These operators also *explicitly* convert to bool EXPECT_EQ(truthy_value && true, true); EXPECT_EQ(true && truthy_value, true); EXPECT_EQ(falsy_value || false, false); EXPECT_EQ(false || falsy_value, false); EXPECT_EQ(!truthy_value, false); EXPECT_EQ(!falsy_value, true); } // These two overflow tests only work in a Debug build. // Unfortunately, in a full debug build, the test will each take about // an hour to run. // Therefore they are disabled here and can be enabled in an appropriate // debug build when required. TEST_F(FixedPointTest, DISABLED_OverflowDecimal32) { // This flag is needed to avoid warnings with ASSERT_DEATH ::testing::FLAGS_gtest_death_test_style = "threadsafe"; using decimal32 = fixed_point<int32_t, Radix::BASE_10>; decimal32 num0{2, scale_type{-9}}; decimal32 num1{-2, scale_type{-9}}; ASSERT_DEATH(num0 + num0, ".*"); ASSERT_DEATH(num1 - num0, ".*"); decimal32 min{std::numeric_limits<int32_t>::min(), scale_type{0}}; decimal32 max{std::numeric_limits<int32_t>::max(), scale_type{0}}; decimal32 NEG_ONE{-1, scale_type{0}}; decimal32 ONE{1, scale_type{0}}; decimal32 TWO{2, scale_type{0}}; ASSERT_DEATH(min / NEG_ONE, ".*"); ASSERT_DEATH(max * TWO, ".*"); ASSERT_DEATH(min * TWO, ".*"); ASSERT_DEATH(max + ONE, ".*"); ASSERT_DEATH(max - NEG_ONE, ".*"); ASSERT_DEATH(min - ONE, ".*"); ASSERT_DEATH(max - NEG_ONE, ".*"); } // See comment above for OverflowDecimal32 test. TEST_F(FixedPointTest, DISABLED_OverflowDecimal64) { // This flag is needed to avoid warnings with ASSERT_DEATH ::testing::FLAGS_gtest_death_test_style = "threadsafe"; using decimal64 = fixed_point<int64_t, Radix::BASE_10>; decimal64 num0{5, scale_type{-18}}; decimal64 num1{-5, scale_type{-18}}; ASSERT_DEATH(num0 + num0, ".*"); ASSERT_DEATH(num1 - num0, ".*"); decimal64 min{std::numeric_limits<int64_t>::min(), scale_type{0}}; decimal64 max{std::numeric_limits<int64_t>::max(), scale_type{0}}; decimal64 NEG_ONE{-1, scale_type{0}}; decimal64 ONE{1, scale_type{0}}; decimal64 TWO{2, scale_type{0}}; ASSERT_DEATH(min / NEG_ONE, ".*"); ASSERT_DEATH(max * TWO, ".*"); ASSERT_DEATH(min * TWO, ".*"); ASSERT_DEATH(max + ONE, ".*"); ASSERT_DEATH(max - NEG_ONE, ".*"); ASSERT_DEATH(min - ONE, ".*"); ASSERT_DEATH(max - NEG_ONE, ".*"); } template <typename ValueType, typename Binop> void integer_vector_test(ValueType const initial_value, int32_t const size, int32_t const scale, Binop binop) { using decimal32 = fixed_point<int32_t, Radix::BASE_10>; std::vector<decimal32> vec1(size); std::vector<ValueType> vec2(size); std::iota(std::begin(vec1), std::end(vec1), decimal32{initial_value, scale_type{scale}}); std::iota(std::begin(vec2), std::end(vec2), initial_value); auto const res1 = std::accumulate(std::cbegin(vec1), std::cend(vec1), decimal32{0, scale_type{scale}}); auto const res2 = std::accumulate(std::cbegin(vec2), std::cend(vec2), static_cast<ValueType>(0)); EXPECT_EQ(static_cast<int32_t>(res1), res2); std::vector<ValueType> vec3(vec1.size()); std::transform(std::cbegin(vec1), std::cend(vec1), std::begin(vec3), [](auto const& e) { return static_cast<int32_t>(e); }); EXPECT_EQ(vec2, vec3); } TEST_F(FixedPointTest, Decimal32IntVector) { integer_vector_test(0, 10, -2, std::plus<>()); integer_vector_test(0, 1000, -2, std::plus<>()); integer_vector_test(1, 10, 0, std::multiplies<>()); integer_vector_test(2, 20, 0, std::multiplies<>()); } template <typename ValueType, typename Binop> void float_vector_test(ValueType const initial_value, int32_t const size, int32_t const scale, Binop binop) { using decimal32 = fixed_point<int32_t, Radix::BASE_10>; std::vector<decimal32> vec1(size); std::vector<ValueType> vec2(size); std::iota(std::begin(vec1), std::end(vec1), decimal32{initial_value, scale_type{scale}}); std::iota(std::begin(vec2), std::end(vec2), initial_value); auto equal = std::equal( std::cbegin(vec1), std::cend(vec1), std::cbegin(vec2), [](auto const& a, auto const& b) { return static_cast<double>(a) - b <= std::numeric_limits<ValueType>::epsilon(); }); EXPECT_TRUE(equal); } TEST_F(FixedPointTest, Decimal32FloatVector) { float_vector_test(0.1, 1000, -2, std::plus<>()); float_vector_test(0.15, 1000, -2, std::plus<>()); float_vector_test(0.1, 10, -2, std::multiplies<>()); float_vector_test(0.15, 20, -2, std::multiplies<>()); } struct cast_to_int32_fn { using decimal32 = fixed_point<int32_t, Radix::BASE_10>; int32_t __host__ __device__ operator()(decimal32 fp) { return static_cast<int32_t>(fp); } }; TYPED_TEST(FixedPointTestAllReps, FixedPointColumnWrapper) { using namespace numeric; using decimalXX = fixed_point<TypeParam, Radix::BASE_10>; using RepType = TypeParam; // fixed_point_column_wrapper auto const w = cudf::test::fixed_point_column_wrapper<RepType>{{1, 2, 3, 4}, scale_type{0}}; // fixed_width_column_wrapper auto const ONE = decimalXX{1, scale_type{0}}; auto const TWO = decimalXX{2, scale_type{0}}; auto const THREE = decimalXX{3, scale_type{0}}; auto const FOUR = decimalXX{4, scale_type{0}}; auto const vec = std::vector<decimalXX>{ONE, TWO, THREE, FOUR}; auto const col = cudf::test::fixed_width_column_wrapper<decimalXX>(vec.begin(), vec.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(col, w); } TYPED_TEST(FixedPointTestAllReps, NoScaleOrWrongTypeID) { EXPECT_THROW(cudf::make_fixed_point_column(cudf::data_type{cudf::type_id::INT32}, 0), cudf::logic_error); } TYPED_TEST(FixedPointTestAllReps, SimpleFixedPointColumnWrapper) { using RepType = cudf::device_storage_type_t<TypeParam>; auto const a = cudf::test::fixed_point_column_wrapper<RepType>{{11, 22, 33}, scale_type{-1}}; auto const b = cudf::test::fixed_point_column_wrapper<RepType>{{110, 220, 330}, scale_type{-2}}; CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(a, b); } TEST_F(FixedPointTest, PositiveScaleWithValuesOutsideUnderlyingType32) { // This is testing fixed_point values outside the range of its underlying type. // For example, 100,000,000 with scale of 6 is 100,000,000,000,000 (100 trillion) and this is // outside the range of a int32_t using fp_wrapper = cudf::test::fixed_point_column_wrapper<int32_t>; auto const a = fp_wrapper{{100000000}, scale_type{6}}; auto const b = fp_wrapper{{5000000}, scale_type{7}}; auto const c = fp_wrapper{{2}, scale_type{0}}; auto const expected1 = fp_wrapper{{150000000}, scale_type{6}}; auto const expected2 = fp_wrapper{{50000000}, scale_type{6}}; auto const type = cudf::data_type{cudf::type_id::DECIMAL32, 6}; auto const result1 = cudf::binary_operation(a, b, cudf::binary_operator::ADD, type); auto const result2 = cudf::binary_operation(a, c, cudf::binary_operator::DIV, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected1, result1->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected2, result2->view()); } TEST_F(FixedPointTest, PositiveScaleWithValuesOutsideUnderlyingType64) { // This is testing fixed_point values outside the range of its underlying type. // For example, 100,000,000 with scale of 100 is 10 ^ 108 and this is far outside the // range of a int64_t using fp_wrapper = cudf::test::fixed_point_column_wrapper<int64_t>; auto const a = fp_wrapper{{100000000}, scale_type{100}}; auto const b = fp_wrapper{{5000000}, scale_type{101}}; auto const c = fp_wrapper{{2}, scale_type{0}}; auto const expected1 = fp_wrapper{{150000000}, scale_type{100}}; auto const expected2 = fp_wrapper{{50000000}, scale_type{100}}; auto const type = cudf::data_type{cudf::type_id::DECIMAL64, 100}; auto const result1 = cudf::binary_operation(a, b, cudf::binary_operator::ADD, type); auto const result2 = cudf::binary_operation(a, c, cudf::binary_operator::DIV, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected1, result1->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected2, result2->view()); } TYPED_TEST(FixedPointTestAllReps, ExtremelyLargeNegativeScale) { // This is testing fixed_point values with an extremely large negative scale. The fixed_point // implementation should be able to handle any scale representable by an int32_t using decimalXX = fixed_point<TypeParam, Radix::BASE_10>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<TypeParam>; auto const a = fp_wrapper{{10}, scale_type{-201}}; auto const b = fp_wrapper{{50}, scale_type{-202}}; auto const c = fp_wrapper{{2}, scale_type{0}}; auto const expected1 = fp_wrapper{{150}, scale_type{-202}}; auto const expected2 = fp_wrapper{{5}, scale_type{-201}}; auto const type1 = cudf::data_type{cudf::type_to_id<decimalXX>(), -202}; auto const result1 = cudf::binary_operation(a, b, cudf::binary_operator::ADD, type1); auto const type2 = cudf::data_type{cudf::type_to_id<decimalXX>(), -201}; auto const result2 = cudf::binary_operation(a, c, cudf::binary_operator::DIV, type2); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected1, result1->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected2, result2->view()); } CUDF_TEST_PROGRAM_MAIN()
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/round/round_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/round.hpp> #include <limits> struct RoundTests : public cudf::test::BaseFixture {}; template <typename T> struct RoundTestsIntegerTypes : public cudf::test::BaseFixture {}; template <typename T> struct RoundTestsFixedPointTypes : public cudf::test::BaseFixture {}; template <typename T> struct RoundTestsFloatingPointTypes : public cudf::test::BaseFixture {}; using IntegerTypes = cudf::test::Types<int16_t, int32_t, int64_t>; TYPED_TEST_SUITE(RoundTestsIntegerTypes, IntegerTypes); TYPED_TEST_SUITE(RoundTestsFixedPointTypes, cudf::test::FixedPointTypes); TYPED_TEST_SUITE(RoundTestsFloatingPointTypes, cudf::test::FloatingPointTypes); TYPED_TEST(RoundTestsFixedPointTypes, SimpleFixedPointTestHalfUpZero) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const input = fp_wrapper{ {1140, 1150, 1160, 1240, 1250, 1260, -1140, -1150, -1160, -1240, -1250, -1260}, scale_type{-2}}; auto const expected = fp_wrapper{{11, 12, 12, 12, 13, 13, -11, -12, -12, -12, -13, -13}, scale_type{0}}; auto const result = cudf::round(input); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFixedPointTypes, SimpleFixedPointTestHalfUpZeroNoOp) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const input = fp_wrapper{ {1125, 1150, 1160, 1240, 1250, 1260, -1125, -1150, -1160, -1240, -1250, -1260}, scale_type{0}}; auto const result = cudf::round(input); CUDF_TEST_EXPECT_COLUMNS_EQUAL(input, result->view()); } TYPED_TEST(RoundTestsFixedPointTypes, SimpleFixedPointTestHalfUpZeroNullMask) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const null_mask = std::vector<int>{1, 1, 0, 1}; auto const input = fp_wrapper{{1150, 1160, 1240, 1250}, null_mask.cbegin(), scale_type{-2}}; auto const expected = fp_wrapper{{12, 12, 1240, 13}, null_mask.cbegin(), scale_type{0}}; auto const result = cudf::round(input); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFixedPointTypes, SimpleFixedPointTestHalfEvenZero) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const input = fp_wrapper{ {1140, 1150, 1160, 1240, 1250, 1260, -1140, -1150, -1160, -1240, -1250, -1260}, scale_type{-2}}; auto const expected = fp_wrapper{{11, 12, 12, 12, 12, 13, -11, -12, -12, -12, -12, -13}, scale_type{0}}; auto const result = cudf::round(input, 0, cudf::rounding_method::HALF_EVEN); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFixedPointTypes, SimpleFixedPointTestHalfUp) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const input = fp_wrapper{{1140, 1150, 1160, -1140, -1150, -1160}, scale_type{-3}}; auto const expected = fp_wrapper{{11, 12, 12, -11, -12, -12}, scale_type{-1}}; auto const result = cudf::round(input, 1, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFixedPointTypes, SimpleFixedPointTestHalfUp2) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const input = fp_wrapper{{114, 115, 116, -114, -115, -116}, scale_type{-2}}; auto const expected = fp_wrapper{{11, 12, 12, -11, -12, -12}, scale_type{-1}}; auto const result = cudf::round(input, 1, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFixedPointTypes, SimpleFixedPointTestHalfUp3) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const input = fp_wrapper{{1, 2, 3, -1, -2, -3}, scale_type{1}}; auto const expected = fp_wrapper{{100, 200, 300, -100, -200, -300}, scale_type{-1}}; auto const result = cudf::round(input, 1, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFixedPointTypes, SimpleFixedPointTestHalfEven) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const input = fp_wrapper{ {1140, 1150, 1160, 1240, 1250, 1260, -1140, -1150, -1160, -1240, -1250, -1260}, scale_type{-3}}; auto const expected = fp_wrapper{{11, 12, 12, 12, 12, 13, -11, -12, -12, -12, -12, -13}, scale_type{-1}}; auto const result = cudf::round(input, 1, cudf::rounding_method::HALF_EVEN); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFixedPointTypes, SimpleFixedPointTestHalfEven2) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const input = fp_wrapper{{114, 115, 116, 124, 125, 126, -114, -115, -116, -124, -125, -126}, scale_type{-2}}; auto const expected = fp_wrapper{{11, 12, 12, 12, 12, 13, -11, -12, -12, -12, -12, -13}, scale_type{-1}}; auto const result = cudf::round(input, 1, cudf::rounding_method::HALF_EVEN); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFixedPointTypes, SimpleFixedPointTestHalfEven3) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const input = fp_wrapper{{1, 2, 3, -1, -2, -3}, scale_type{1}}; auto const expected = fp_wrapper{{100, 200, 300, -100, -200, -300}, scale_type{-1}}; auto const result = cudf::round(input, 1, cudf::rounding_method::HALF_EVEN); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFixedPointTypes, EmptyFixedPointTypeTest) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const input = fp_wrapper{{}, scale_type{1}}; auto const expected = fp_wrapper{{}, scale_type{-1}}; auto const expected_type = cudf::data_type{cudf::type_to_id<decimalXX>(), scale_type{-1}}; auto const result = cudf::round(input, 1, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); EXPECT_EQ(result->view().type(), expected_type); } TYPED_TEST(RoundTestsFixedPointTypes, SimpleFixedPointTestNegHalfUp) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const input = fp_wrapper{{14, 15, 16, 24, 25, 26, -14, -15, -16, -24, -25, -26}, scale_type{2}}; auto const expected = fp_wrapper{{1, 2, 2, 2, 3, 3, -1, -2, -2, -2, -3, -3}, scale_type{3}}; auto const result = cudf::round(input, -3, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFixedPointTypes, SimpleFixedPointTestNegHalfUp2) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const input = fp_wrapper{{14, 15, 16, 24, 25, 26, -14, -15, -16, -24, -25, -26}, scale_type{3}}; auto const expected = fp_wrapper{{1, 2, 2, 2, 3, 3, -1, -2, -2, -2, -3, -3}, scale_type{4}}; auto const result = cudf::round(input, -4, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFixedPointTypes, SimpleFixedPointTestHalfNegUp3) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const input = fp_wrapper{{1, 2, 3, -1, -2, -3}, scale_type{2}}; auto const expected = fp_wrapper{{10, 20, 30, -10, -20, -30}, scale_type{1}}; auto const result = cudf::round(input, -1, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFixedPointTypes, SimpleFixedPointTestNegHalfEven) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const input = fp_wrapper{{14, 15, 16, 24, 25, 26, -14, -15, -16, -24, -25, -26}, scale_type{2}}; auto const expected = fp_wrapper{{1, 2, 2, 2, 2, 3, -1, -2, -2, -2, -2, -3}, scale_type{3}}; auto const result = cudf::round(input, -3, cudf::rounding_method::HALF_EVEN); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFixedPointTypes, SimpleFixedPointTestNegHalfEven2) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const input = fp_wrapper{{14, 15, 16, 24, 25, 26, -14, -15, -16, -24, -25, -26}, scale_type{3}}; auto const expected = fp_wrapper{{1, 2, 2, 2, 2, 3, -1, -2, -2, -2, -2, -3}, scale_type{4}}; auto const result = cudf::round(input, -4, cudf::rounding_method::HALF_EVEN); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFixedPointTypes, SimpleFixedPointTestHalfNegEven3) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const input = fp_wrapper{{1, 2, 3, -1, -2, -3}, scale_type{2}}; auto const expected = fp_wrapper{{10, 20, 30, -10, -20, -30}, scale_type{1}}; auto const result = cudf::round(input, -1, cudf::rounding_method::HALF_EVEN); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFixedPointTypes, TestForBlog) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const input = fp_wrapper{{25649999}, scale_type{-5}}; auto const expected = fp_wrapper{{256}, scale_type{0}}; auto const result = cudf::round(input); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFixedPointTypes, TestScaleMovementExceedingMaxPrecision) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; // max precision of int32 = 9 // scale movement = -(-11) -1 = 10 > 9 // max precision of int64 = 18 // scale movement = -(-20) -1 = 19 > 18 // max precision of int128 = 38 // scale movement = -(-40) -1 = 39 > 38 auto const target_scale = cuda::std::numeric_limits<RepType>::digits10 + 1 + 1; auto const input = fp_wrapper{{14, 15, 16, 24, 25, 26, -14, -15, -16, -24, -25, -26}, scale_type{1}}; auto const expected = fp_wrapper{{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, scale_type{target_scale}}; auto const result = cudf::round(input, -target_scale, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); auto const input_even = fp_wrapper{{14, 15, 16, 24, 25, 26, -14, -15, -16, -24, -25, -26}, scale_type{1}}; auto const expected_even = fp_wrapper{{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, scale_type{target_scale}}; auto const result_even = cudf::round(input, -target_scale, cudf::rounding_method::HALF_EVEN); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_even, result_even->view()); const std::initializer_list<bool> validity = {1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0}; auto const input_null = fp_wrapper{{14, 15, 16, 24, 25, 26, -14, -15, -16, -24, -25, -26}, validity, scale_type{1}}; auto const expected_null = fp_wrapper{{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, validity, scale_type{target_scale}}; auto const result_null = cudf::round(input_null, -target_scale, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_null, result_null->view()); } TYPED_TEST(RoundTestsFloatingPointTypes, SimpleFloatingPointTestHalfUp0) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; auto const input = fw_wrapper{1.4, 1.5, 1.6}; auto const expected = fw_wrapper{1, 2, 2}; auto const result = cudf::round(input); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFloatingPointTypes, SimpleFloatingPointTestHalfUp1) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; auto const input = fw_wrapper{1.24, 1.25, 1.26}; auto const expected = fw_wrapper{1.2, 1.3, 1.3}; auto const result = cudf::round(input, 1, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFloatingPointTypes, SimpleFloatingPointTestHalfEven0) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; auto const input = fw_wrapper{1.4, 1.5, 1.6, 2.4, 2.5, 2.6}; auto const expected = fw_wrapper{1, 2, 2, 2, 2, 3}; auto const result = cudf::round(input, 0, cudf::rounding_method::HALF_EVEN); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFloatingPointTypes, SimpleFloatingPointTestHalfEven1) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; auto const input = fw_wrapper{1.24, 1.25, 1.26, 1.34, 1.35, 1.36}; auto const expected = fw_wrapper{1.2, 1.2, 1.3, 1.3, 1.4, 1.4}; auto const result = cudf::round(input, 1, cudf::rounding_method::HALF_EVEN); } TYPED_TEST(RoundTestsFloatingPointTypes, SimpleFloatingPointTestWithNullsHalfUp) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; auto const input = fw_wrapper{{1.24, 1.25, 1.26}, {1, 0, 1}}; auto const expected = fw_wrapper{{1.2, 1.3, 1.3}, {1, 0, 1}}; auto const result = cudf::round(input, 1, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFloatingPointTypes, SimpleFloatingPointTestNegHalfUp1) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; auto const input = fw_wrapper{5, 12, 15, 135, 1454, 1455, 1456}; auto const expected = fw_wrapper{10, 10, 20, 140, 1450, 1460, 1460}; auto const result = cudf::round(input, -1, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFloatingPointTypes, SimpleFloatingPointTestNegHalfEven1) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; auto const input = fw_wrapper{5, 12, 15, 135, 1454, 1455, 1456}; auto const expected = fw_wrapper{0, 10, 20, 140, 1450, 1460, 1460}; auto const result = cudf::round(input, -1, cudf::rounding_method::HALF_EVEN); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFloatingPointTypes, SimpleFloatingPointTestNegHalfUp2) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; auto const input = fw_wrapper{12, 135, 1454, 1455, 1500}; auto const expected = fw_wrapper{0, 100, 1500, 1500, 1500}; auto const result = cudf::round(input, -2, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFloatingPointTypes, LargeFloatingPointHalfUp) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; auto transform = [](int i) -> float { return i % 2 == 0 ? i + 0.44 : i + 0.56; }; auto begin = cudf::detail::make_counting_transform_iterator(0, transform); auto const input = fw_wrapper(begin, begin + 2000); auto transform2 = [](int i) { return i % 2 == 0 ? i + 0.4 : i + 0.6; }; auto begin2 = cudf::detail::make_counting_transform_iterator(0, transform2); auto const expected = fw_wrapper(begin2, begin2 + 2000); auto const result = cudf::round(input, 1, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsIntegerTypes, LargeIntegerHalfEven) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; auto transform = [](int i) -> float { return 10 * i + 5; }; auto begin = cudf::detail::make_counting_transform_iterator(1, transform); auto const input = fw_wrapper(begin, begin + 2000); auto transform2 = [](int i) { return i % 2 == 0 ? 10 * i : 10 + 10 * i; }; auto begin2 = cudf::detail::make_counting_transform_iterator(1, transform2); auto const expected = fw_wrapper(begin2, begin2 + 2000); auto const result = cudf::round(input, -1, cudf::rounding_method::HALF_EVEN); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsFloatingPointTypes, SameSignificatDigitsHalfUp) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; auto const input = fw_wrapper{9.87654321}; auto const expected = fw_wrapper{9.88}; auto const result = cudf::round(input, 2, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); auto const input2 = fw_wrapper{987.654321}; auto const expected2 = fw_wrapper{988}; auto const result2 = cudf::round(input2); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected2, result2->view()); auto const input3 = fw_wrapper{987654.321}; auto const expected3 = fw_wrapper{988000}; auto const result3 = cudf::round(input3, -3, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected3, result3->view()); auto const input4 = fw_wrapper{9876543.21}; auto const expected4 = fw_wrapper{9880000}; auto const result4 = cudf::round(input4, -4, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected4, result4->view()); auto const input5 = fw_wrapper{0.0000987654321}; auto const expected5 = fw_wrapper{0.0000988}; auto const result5 = cudf::round(input5, 7, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected5, result5->view()); } TEST_F(RoundTests, FloatMaxTestHalfUp) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<float>; auto const input = fw_wrapper{std::numeric_limits<float>::max()}; // 3.40282e+38 auto const expected = fw_wrapper{3.4e+38}; auto const result = cudf::round(input, -37, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TEST_F(RoundTests, DoubleMaxTestHalfUp) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<double>; auto const input = fw_wrapper{std::numeric_limits<double>::max() - 5e+306}; // 1.74769e+308 auto const expected = fw_wrapper{1.7e+308}; auto const result = cudf::round(input, -307, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TEST_F(RoundTests, AvoidOverFlowTestHalfUp) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<double>; auto const input = fw_wrapper{std::numeric_limits<double>::max()}; auto const expected = fw_wrapper{std::numeric_limits<double>::max()}; auto const result = cudf::round(input, 2, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsIntegerTypes, SimpleIntegerTestNegHalfUp2) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; auto const input = fw_wrapper{12, 135, 1454, 1455, 1500}; auto const expected = fw_wrapper{0, 100, 1500, 1500, 1500}; auto const result = cudf::round(input, -2, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsIntegerTypes, SimpleIntegerTestNegHalfEven) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; auto const input = fw_wrapper{12, 135, 1450, 1550, 1650}; auto const expected = fw_wrapper{0, 100, 1400, 1600, 1600}; auto const result = cudf::round(input, -2, cudf::rounding_method::HALF_EVEN); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsIntegerTypes, SimpleNegativeIntegerHalfUp) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; auto const input = fw_wrapper{-12, -135, -1454, -1455, -1500, -140, -150, -160}; auto const expected = fw_wrapper{0, -100, -1500, -1500, -1500, -100, -200, -200}; auto const result = cudf::round(input, -2, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsIntegerTypes, SimpleNegativeIntegerHalfEven) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; auto const input = fw_wrapper{-12, -135, -145, -146, -1454, -1455, -1500}; auto const expected = fw_wrapper{-10, -140, -140, -150, -1450, -1460, -1500}; auto const result = cudf::round(input, -1, cudf::rounding_method::HALF_EVEN); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TEST_F(RoundTests, SimpleNegativeIntegerWithUnsignedNumbersHalfUp) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<uint32_t>; auto const input = fw_wrapper{12, 135, 1454, 1455, 1500, 140, 150, 160}; auto const expected = fw_wrapper{0, 100, 1500, 1500, 1500, 100, 200, 200}; auto const result = cudf::round(input, -2, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TEST_F(RoundTests, SimpleNegativeInt8HalfEven) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<int8_t>; auto const input = fw_wrapper{12, 35, 36, 15, 16, 24, 25, 26}; auto const expected = fw_wrapper{10, 40, 40, 20, 20, 20, 20, 30}; auto const result = cudf::round(input, -1, cudf::rounding_method::HALF_EVEN); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TEST_F(RoundTests, SimpleNegativeInt8HalfUp) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<int8_t>; auto const input = fw_wrapper{12, 35, 36, 15, 16, 24, 25, 26}; auto const expected = fw_wrapper{10, 40, 40, 20, 20, 20, 30, 30}; auto const result = cudf::round(input, -1, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(RoundTestsIntegerTypes, SimplePositiveIntegerHalfUp) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; auto const input = fw_wrapper{-12, -135, -1454, -1455, -1500}; auto const expected = fw_wrapper{-12, -135, -1454, -1455, -1500}; auto const result = cudf::round(input, 2, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TEST_F(RoundTests, Int64AtBoundaryHalfUp) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<int64_t>; auto const m = std::numeric_limits<int64_t>::max(); // 9223372036854775807 auto const input = fw_wrapper{m}; auto const expected = fw_wrapper{9223372036854775800}; auto const result = cudf::round(input, -2, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); auto const expected2 = fw_wrapper{9223372036850000000}; auto const result2 = cudf::round(input, -7, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected2, result2->view()); auto const expected3 = fw_wrapper{9223372000000000000}; auto const result3 = cudf::round(input, -11, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected3, result3->view()); auto const result4 = cudf::round(input, -12, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected3, result4->view()); auto const expected5 = fw_wrapper{9000000000000000000}; auto const result5 = cudf::round(input, -18, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected5, result5->view()); } TEST_F(RoundTests, FixedPoint128HalfUp) { using namespace numeric; using RepType = cudf::device_storage_type_t<decimal128>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; { auto const input = fp_wrapper{{-160714515306}, scale_type{-13}}; auto const expected = fp_wrapper{{-16071451531}, scale_type{-12}}; auto const result = cudf::round(input, 12, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } } TEST_F(RoundTests, FixedPointAtBoundaryTestHalfUp) { using namespace numeric; using RepType = cudf::device_storage_type_t<decimal128>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const m = std::numeric_limits<RepType>::max(); // 170141183460469231731687303715884105727 { auto const input = fp_wrapper{{m}, scale_type{0}}; auto const expected = fp_wrapper{{m / 100000}, scale_type{5}}; auto const result = cudf::round(input, -5, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } { auto const input = fp_wrapper{{m}, scale_type{0}}; auto const expected = fp_wrapper{{m / 100000000000}, scale_type{11}}; auto const result = cudf::round(input, -11, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } { auto const input = fp_wrapper{{m}, scale_type{0}}; auto const expected = fp_wrapper{{m / 1000000000000000}, scale_type{15}}; auto const result = cudf::round(input, -15, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } } TEST_F(RoundTests, BoolTestHalfUp) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<bool>; auto const input = fw_wrapper{0, 1, 0}; EXPECT_THROW(cudf::round(input, -2, cudf::rounding_method::HALF_UP), cudf::logic_error); } // Use __uint128_t for demonstration. constexpr __uint128_t operator""_uint128_t(const char* s) { __uint128_t ret = 0; for (int i = 0; s[i] != '\0'; ++i) { ret *= 10; if ('0' <= s[i] && s[i] <= '9') { ret += s[i] - '0'; } } return ret; } TEST_F(RoundTests, HalfEvenErrorsA) { using namespace numeric; using RepType = cudf::device_storage_type_t<decimal128>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; { // 0.5 at scale -37 should round HALF_EVEN to 0, because 0 is an even number auto const input = fp_wrapper{{5000000000000000000000000000000000000_uint128_t}, scale_type{-37}}; auto const expected = fp_wrapper{{0}, scale_type{0}}; auto const result = cudf::round(input, 0, cudf::rounding_method::HALF_EVEN); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } } TEST_F(RoundTests, HalfEvenErrorsB) { using namespace numeric; using RepType = cudf::device_storage_type_t<decimal128>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; { // 0.125 at scale -37 should round HALF_EVEN to 0.12, because 2 is an even number auto const input = fp_wrapper{{1250000000000000000000000000000000000_uint128_t}, scale_type{-37}}; auto const expected = fp_wrapper{{12}, scale_type{-2}}; auto const result = cudf::round(input, 2, cudf::rounding_method::HALF_EVEN); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } } TEST_F(RoundTests, HalfEvenErrorsC) { using namespace numeric; using RepType = cudf::device_storage_type_t<decimal128>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; { // 0.0625 at scale -37 should round HALF_EVEN to 0.062, because 2 is an even number auto const input = fp_wrapper{{0625000000000000000000000000000000000_uint128_t}, scale_type{-37}}; auto const expected = fp_wrapper{{62}, scale_type{-3}}; auto const result = cudf::round(input, 3, cudf::rounding_method::HALF_EVEN); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } } TEST_F(RoundTests, HalfUpErrorsA) { using namespace numeric; using RepType = cudf::device_storage_type_t<decimal128>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; { // 0.25 at scale -37 should round HALF_UP to 0.3 auto const input = fp_wrapper{{2500000000000000000000000000000000000_uint128_t}, scale_type{-37}}; auto const expected = fp_wrapper{{3}, scale_type{-1}}; auto const result = cudf::round(input, 1, cudf::rounding_method::HALF_UP); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } } CUDF_TEST_PROGRAM_MAIN()
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/sample_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf/column/column.hpp> #include <cudf/copying.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/sorting.hpp> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> struct SampleTest : public cudf::test::BaseFixture {}; TEST_F(SampleTest, FailCaseRowMultipleSampling) { cudf::test::fixed_width_column_wrapper<int16_t> col1{1, 2, 3, 4, 5}; // size of input table is smaller than number of samples // and sampling same row multiple times is disallowed, // this combination can't work. cudf::size_type const n_samples = 10; cudf::table_view input({col1}); EXPECT_THROW(cudf::sample(input, n_samples, cudf::sample_with_replacement::FALSE, 0), cudf::logic_error); } TEST_F(SampleTest, RowMultipleSamplingDisallowed) { cudf::size_type const n_samples = 1024; auto data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i; }); cudf::test::fixed_width_column_wrapper<int16_t> col1(data, data + n_samples); cudf::table_view input({col1}); for (int i = 0; i < 10; i++) { auto out_table = cudf::sample(input, n_samples, cudf::sample_with_replacement::FALSE, i); auto sorted_out = cudf::sort(out_table->view()); CUDF_TEST_EXPECT_TABLES_EQUAL(input, sorted_out->view()); } } TEST_F(SampleTest, TestReproducibilityWithSeed) { cudf::size_type const n_samples = 1024; auto data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i; }); cudf::test::fixed_width_column_wrapper<int16_t> col1(data, data + n_samples); cudf::table_view input({col1}); auto expected_1 = cudf::sample(input, n_samples, cudf::sample_with_replacement::FALSE, 1); for (int i = 0; i < 2; i++) { auto out = cudf::sample(input, n_samples, cudf::sample_with_replacement::FALSE, 1); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_1->view(), out->view()); } auto expected_2 = cudf::sample(input, n_samples, cudf::sample_with_replacement::TRUE, 1); for (int i = 0; i < 2; i++) { auto out = cudf::sample(input, n_samples, cudf::sample_with_replacement::TRUE, 1); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_2->view(), out->view()); } } struct SampleBasicTest : public SampleTest, public ::testing::WithParamInterface< std::tuple<cudf::size_type, cudf::sample_with_replacement>> {}; TEST_P(SampleBasicTest, CombinationOfParameters) { cudf::size_type const table_size = 1024; auto const [n_samples, multi_smpl] = GetParam(); auto data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i; }); cudf::test::fixed_width_column_wrapper<int16_t> col1(data, data + table_size); cudf::test::fixed_width_column_wrapper<float> col2(data, data + table_size); cudf::table_view input({col1, col2}); auto out_table = cudf::sample(input, n_samples, multi_smpl, 0); EXPECT_EQ(out_table->num_rows(), n_samples); } INSTANTIATE_TEST_CASE_P( SampleTest, SampleBasicTest, ::testing::Values(std::make_tuple(0, cudf::sample_with_replacement::TRUE), std::make_tuple(0, cudf::sample_with_replacement::FALSE), std::make_tuple(512, cudf::sample_with_replacement::TRUE), std::make_tuple(512, cudf::sample_with_replacement::FALSE), std::make_tuple(1024, cudf::sample_with_replacement::TRUE), std::make_tuple(1024, cudf::sample_with_replacement::FALSE), std::make_tuple(2048, cudf::sample_with_replacement::TRUE)));
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/reverse_tests.cpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/copying.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/scalar/scalar.hpp> #include <cudf/scalar/scalar_factories.hpp> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> #include <thrust/execution_policy.h> #include <thrust/host_vector.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/tabulate.h> constexpr cudf::test::debug_output_level verbosity{cudf::test::debug_output_level::ALL_ERRORS}; template <typename T> class ReverseTypedTestFixture : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(ReverseTypedTestFixture, cudf::test::AllTypes); TYPED_TEST(ReverseTypedTestFixture, ReverseTable) { using T = TypeParam; constexpr cudf::size_type num_values{10}; auto input = cudf::test::fixed_width_column_wrapper<T, int32_t>( thrust::make_counting_iterator(0), thrust::make_counting_iterator(0) + num_values); auto expected_elements = cudf::detail::make_counting_transform_iterator( 0, [num_values] __device__(auto i) { return num_values - i - 1; }); auto expected = cudf::test::fixed_width_column_wrapper<T, typename decltype(expected_elements)::value_type>( expected_elements, expected_elements + num_values); auto input_table = cudf::table_view{{input}}; auto const p_ret = cudf::reverse(input_table); EXPECT_EQ(p_ret->num_columns(), 1); CUDF_TEST_EXPECT_COLUMNS_EQUAL(p_ret->view().column(0), expected, verbosity); } TYPED_TEST(ReverseTypedTestFixture, ReverseColumn) { using T = TypeParam; constexpr cudf::size_type num_values{10}; auto input = cudf::test::fixed_width_column_wrapper<T, int32_t>( thrust::make_counting_iterator(0), thrust::make_counting_iterator(0) + num_values); auto expected_elements = cudf::detail::make_counting_transform_iterator( 0, [num_values] __device__(auto i) { return num_values - i - 1; }); auto expected = cudf::test::fixed_width_column_wrapper<T, typename decltype(expected_elements)::value_type>( expected_elements, expected_elements + num_values); auto const column_ret = cudf::reverse(input); CUDF_TEST_EXPECT_COLUMNS_EQUAL(column_ret->view(), expected, verbosity); } TYPED_TEST(ReverseTypedTestFixture, ReverseNullable) { using T = TypeParam; constexpr cudf::size_type num_values{20}; std::vector<int64_t> input_values(num_values); std::iota(input_values.begin(), input_values.end(), 1); thrust::host_vector<bool> input_valids(num_values); thrust::tabulate( thrust::seq, input_valids.begin(), input_valids.end(), [](auto i) { return not(i % 2); }); std::vector<T> expected_values(input_values.size()); thrust::host_vector<bool> expected_valids(input_valids.size()); std::transform(std::make_reverse_iterator(input_values.end()), std::make_reverse_iterator(input_values.begin()), expected_values.begin(), [](auto i) { return cudf::test::make_type_param_scalar<T>(i); }); std::reverse_copy(input_valids.begin(), input_valids.end(), expected_valids.begin()); cudf::test::fixed_width_column_wrapper<T, int64_t> input( input_values.begin(), input_values.end(), input_valids.begin()); cudf::test::fixed_width_column_wrapper<T> expected( expected_values.begin(), expected_values.end(), expected_valids.begin()); cudf::table_view input_table{{input}}; auto p_ret = cudf::reverse(input_table); EXPECT_EQ(p_ret->num_columns(), 1); CUDF_TEST_EXPECT_COLUMNS_EQUAL(p_ret->view().column(0), expected); } TYPED_TEST(ReverseTypedTestFixture, ZeroSizeInput) { using T = TypeParam; cudf::test::fixed_width_column_wrapper<T, int32_t> input(thrust::make_counting_iterator(0), thrust::make_counting_iterator(0)); cudf::test::fixed_width_column_wrapper<T, int32_t> expected(thrust::make_counting_iterator(0), thrust::make_counting_iterator(0)); cudf::table_view input_table{{input}}; auto p_ret = cudf::reverse(input_table); EXPECT_EQ(p_ret->num_columns(), 1); CUDF_TEST_EXPECT_COLUMNS_EQUAL(p_ret->view().column(0), expected); } class ReverseStringTestFixture : public cudf::test::BaseFixture {}; TEST_F(ReverseStringTestFixture, ReverseNullable) { constexpr cudf::size_type num_values{20}; std::vector<std::string> input_values(num_values); thrust::host_vector<bool> input_valids(num_values); thrust::tabulate(thrust::seq, input_values.begin(), input_values.end(), [](auto i) { return "#" + std::to_string(i); }); thrust::tabulate( thrust::seq, input_valids.begin(), input_valids.end(), [](auto i) { return not(i % 2); }); std::vector<std::string> expected_values(input_values.size()); thrust::host_vector<bool> expected_valids(input_valids.size()); std::reverse_copy(input_values.begin(), input_values.end(), expected_values.begin()); std::reverse_copy(input_valids.begin(), input_valids.end(), expected_valids.begin()); auto input = cudf::test::strings_column_wrapper( input_values.begin(), input_values.end(), input_valids.begin()); auto expected = cudf::test::strings_column_wrapper( expected_values.begin(), expected_values.end(), expected_valids.begin()); cudf::table_view input_table{{input}}; auto p_ret = cudf::reverse(input_table); EXPECT_EQ(p_ret->num_columns(), 1); CUDF_TEST_EXPECT_COLUMNS_EQUAL(p_ret->view().column(0), expected); } TEST_F(ReverseStringTestFixture, ZeroSizeInput) { std::vector<std::string> input_values{}; auto input = cudf::test::strings_column_wrapper(input_values.begin(), input_values.end()); auto count = cudf::test::fixed_width_column_wrapper<cudf::size_type>( thrust::make_counting_iterator(0), thrust::make_counting_iterator(0)); auto expected = cudf::test::strings_column_wrapper(input_values.begin(), input_values.end()); cudf::table_view input_table{{input}}; auto p_ret = cudf::reverse(input_table); EXPECT_EQ(p_ret->num_columns(), 1); CUDF_TEST_EXPECT_COLUMNS_EQUAL(p_ret->view().column(0), expected); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/segmented_gather_list_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/column/column_view.hpp> #include <cudf/copying.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/detail/null_mask.hpp> #include <cudf/lists/gather.hpp> #include <cudf/lists/lists_column_view.hpp> #include <stdexcept> template <typename T> class SegmentedGatherTest : public cudf::test::BaseFixture {}; using FixedWidthTypesNotBool = cudf::test::Concat<cudf::test::IntegralTypesNotBool, cudf::test::FloatingPointTypes, cudf::test::DurationTypes, cudf::test::TimestampTypes>; TYPED_TEST_SUITE(SegmentedGatherTest, FixedWidthTypesNotBool); // to disambiguate between {} == 0 and {} == List{0} // Also, see note about compiler issues when declaring nested // empty lists in lists_column_wrapper documentation template <typename T> using LCW = cudf::test::lists_column_wrapper<T, int32_t>; using namespace cudf::test::iterators; auto constexpr NULLIFY = cudf::out_of_bounds_policy::NULLIFY; TYPED_TEST(SegmentedGatherTest, Gather) { using T = TypeParam; // List<T> LCW<T> list{{1, 2, 3, 4}, {5}, {6, 7}, {8, 9, 10}}; { // Straight-line case. auto const gather_map = LCW<int>{{3, 2, 1, 0}, {0}, {0, 1}, {0, 2, 1}}; auto const expected = LCW<T>{{4, 3, 2, 1}, {5}, {6, 7}, {8, 10, 9}}; auto const results = cudf::lists::segmented_gather(cudf::lists_column_view{list}, cudf::lists_column_view{gather_map}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected); } { // Nullify out-of-bounds values. auto const gather_map = LCW<int>{{3, 2, 4, 0}, {0}, {0, -3}, {0, 2, 1}}; auto const expected = LCW<T>{{{4, 3, 2, 1}, null_at(2)}, {5}, {{6, 7}, null_at(1)}, {8, 10, 9}}; auto const results = cudf::lists::segmented_gather( cudf::lists_column_view{list}, cudf::lists_column_view{gather_map}, NULLIFY); CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected); } } TYPED_TEST(SegmentedGatherTest, GatherNothing) { using T = TypeParam; // List<T> { auto const list = LCW<T>{{1, 2, 3, 4}, {5}, {6, 7}, {8, 9, 10}}; auto const gather_map = LCW<int>{LCW<int>{}, LCW<int>{}, LCW<int>{}, LCW<int>{}}; auto const results = cudf::lists::segmented_gather(cudf::lists_column_view{list}, cudf::lists_column_view{gather_map}); auto const expected = LCW<T>{LCW<T>{}, LCW<T>{}, LCW<T>{}, LCW<T>{}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } // List<List<T>> { auto const list = LCW<T>{{{1, 2, 3, 4}, {5}}, {{6, 7}}, {{}, {8, 9, 10}}}; auto const gather_map = LCW<int>{LCW<int>{}, LCW<int>{}, LCW<int>{}}; auto const results = cudf::lists::segmented_gather(cudf::lists_column_view{list}, cudf::lists_column_view{gather_map}); // hack to get column of empty list of list auto const expected_dummy = LCW<T>{{{1, 2, 3, 4}, {5}}, LCW<T>{}, LCW<T>{}, LCW<T>{}}; auto const expected = cudf::split(expected_dummy, {1})[1]; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } // List<List<List<T>>> { auto const list = LCW<T>{{{{1, 2, 3, 4}, {5}}}, {{{6, 7}, {8, 9, 10}}}}; auto const gather_map = LCW<int>{LCW<int>{}, LCW<int>{}}; auto const results = cudf::lists::segmented_gather(cudf::lists_column_view{list}, cudf::lists_column_view{gather_map}); // hack to get column of empty list of list of list auto const expected_dummy = LCW<T>{{{{1, 2, 3, 4}}}, LCW<T>{}, LCW<T>{}}; auto const expected = cudf::split(expected_dummy, {1})[1]; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); // the result should preserve the full List<List<List<int>>> hierarchy // even though it is empty past the first level cudf::lists_column_view lcv(results->view()); EXPECT_EQ(lcv.size(), 2); EXPECT_EQ(lcv.child().type().id(), cudf::type_id::LIST); EXPECT_EQ(lcv.child().size(), 0); EXPECT_EQ(cudf::lists_column_view(lcv.child()).child().type().id(), cudf::type_id::LIST); EXPECT_EQ(cudf::lists_column_view(lcv.child()).child().size(), 0); EXPECT_EQ( cudf::lists_column_view(cudf::lists_column_view(lcv.child()).child()).child().type().id(), cudf::type_to_id<T>()); EXPECT_EQ(cudf::lists_column_view(cudf::lists_column_view(lcv.child()).child()).child().size(), 0); } } TYPED_TEST(SegmentedGatherTest, GatherNulls) { using T = TypeParam; auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); // List<T> auto const list = LCW<T>{{{1, 2, 3, 4}, valids}, {5}, {{6, 7}, valids}, {{8, 9, 10}, valids}}; { // Test gathering on lists that contain nulls. auto const gather_map = LCW<int>{{0, 1}, LCW<int>{}, {1}, {2, 1, 0}}; auto const results = cudf::lists::segmented_gather(cudf::lists_column_view{list}, cudf::lists_column_view{gather_map}); auto const expected = LCW<T>{{{1, 2}, valids}, LCW<T>{}, {{7}, valids + 1}, {{10, 9, 8}, valids}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected); } { // Test gathering on lists that contain nulls, with out-of-bounds indices. auto const gather_map = LCW<int>{{10, -10}, LCW<int>{}, {1}, {2, -10, 0}}; auto const results = cudf::lists::segmented_gather( cudf::lists_column_view{list}, cudf::lists_column_view{gather_map}, NULLIFY); auto const expected = LCW<T>{{{0, 0}, nulls_at({0, 1})}, LCW<T>{}, {{7}, valids + 1}, {{10, 0, 8}, null_at(1)}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected); } } TYPED_TEST(SegmentedGatherTest, GatherNested) { using T = TypeParam; // List<List<T>> { // clang-format off auto const list = LCW<T>{{{2, 3}, {4, 5}}, {{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}, {{15, 16}, {17, 18}, {17, 18}, {17, 18}, {-17, -18}}}; auto const gather_map = LCW<int>{{0, -2, -2}, {1}, {1, 0, -1, -5}}; auto const results = cudf::lists::segmented_gather(cudf::lists_column_view{list}, cudf::lists_column_view{gather_map}); auto const expected = LCW<T>{{{2, 3}, {2, 3}, {2, 3}}, {{9, 10, 11}}, {{17, 18}, {15, 16}, {-17, -18}, {15, 16}}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected); // clang-format on } // List<List<T>>, with out-of-bounds gather indices. { // clang-format off auto const list = LCW<T>{{{2, 3}, {4, 5}}, {{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}, {{15, 16}, {17, 18}, {17, 18}, {17, 18}, {-17, -18}}}; auto const gather_map = LCW<int>{{0, 2, -2}, {1}, {1, 0, -1, -6}}; auto const results = cudf::lists::segmented_gather(cudf::lists_column_view{list}, cudf::lists_column_view{gather_map}, NULLIFY); auto const expected = LCW<T>{{{{2, 3}, LCW<T>{}, {2, 3}}, null_at(1)}, {{9, 10, 11}}, {{{17, 18}, {15, 16}, {-17, -18}, LCW<T>{}}, null_at(3)}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected); // clang-format on } // List<List<List<T>>> { // clang-format off auto const list = LCW<T>{{{{2, 3}, {4, 5}}, {{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}}, {{{15, 16}, {17, 18}, {17, 18}, {17, 18}, {17, 18}}}, {{LCW<T>{0}}}, {{{10}, {20, 30, 40, 50}, {60, 70, 80}}, {{0, 1, 3}, {5}}, {{11, 12, 13, 14, 15}, {16, 17}, {0}}}, {{{10, 20}}, {LCW<T>{30}}, {{40, 50}, {60, 70, 80}}}}; auto const gather_map = LCW<int>{{1}, LCW<int>{}, {0}, {1}, {0, -1, 1}}; auto const results = cudf::lists::segmented_gather(cudf::lists_column_view{list}, cudf::lists_column_view{gather_map}); auto const expected = LCW<T>{{{{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}}, LCW<T>{}, {{LCW<T>{0}}}, {{{0, 1, 3}, {5}}}, {{{10, 20}}, {{40, 50}, {60, 70, 80}}, {LCW<T>{30}}}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected); // clang-format on } // List<List<List<T>>>, with out-of-bounds gather indices. { auto const list = LCW<T>{{{{2, 3}, {4, 5}}, {{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}}, {{{15, 16}, {17, 18}, {17, 18}, {17, 18}, {17, 18}}}, {{LCW<T>{0}}}, {{{10}, {20, 30, 40, 50}, {60, 70, 80}}, {{0, 1, 3}, {5}}, {{11, 12, 13, 14, 15}, {16, 17}, {0}}}, {{{10, 20}}, {LCW<T>{30}}, {{40, 50}, {60, 70, 80}}}}; auto const gather_map = LCW<int>{{1}, LCW<int>{}, {0}, {1}, {0, -1, 3, -4}}; auto const results = cudf::lists::segmented_gather( cudf::lists_column_view{list}, cudf::lists_column_view{gather_map}, NULLIFY); auto const expected = LCW<T>{{{{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}}, LCW<T>{}, {{LCW<T>{0}}}, {{{0, 1, 3}, {5}}}, {{{{10, 20}}, {{40, 50}, {60, 70, 80}}, LCW<T>{}, LCW<T>{}}, nulls_at({2, 3})}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected); // clang-format on } } TYPED_TEST(SegmentedGatherTest, GatherOutOfOrder) { using T = TypeParam; // List<List<T>> { // clang-format off auto const list = LCW<T>{{{2, 3}, {4, 5}}, {{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}, {{15, 16}, {17, 18}, {17, 18}, {17, 18}, {17, 18}}}; auto const gather_map = LCW<int>{{1, 0}, {1, 2, 0}, {4, 3, 2, 1, 0}}; auto const results = cudf::lists::segmented_gather(cudf::lists_column_view{list}, cudf::lists_column_view{gather_map}); auto const expected = LCW<T>{{{4, 5}, {2, 3}}, {{9, 10, 11}, {12, 13, 14}, {6, 7, 8}}, {{17, 18}, {17, 18}, {17, 18}, {17, 18}, {15, 16}}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected); // clang-format on } // List<List<T>>, with out-of-bounds gather indices. { // clang-format off auto const list = LCW<T>{{{2, 3}, {4, 5}}, {{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}, {{15, 16}, {17, 18}, {17, 18}, {17, 18}, {17, 18}}}; auto const gather_map = LCW<int>{{1, 0}, {3, -1, -4}, {5, 4, 3, 2, 1, 0}}; auto const results = cudf::lists::segmented_gather(cudf::lists_column_view{list}, cudf::lists_column_view{gather_map}, NULLIFY); auto const expected = LCW<T>{{{4, 5}, {2, 3}}, {{LCW<T>{}, {12, 13, 14}, LCW<T>{}}, nulls_at({0, 2})}, {{LCW<T>{}, {17, 18}, {17, 18}, {17, 18}, {17, 18}, {15, 16}}, null_at(0)}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected); // clang-format on } } TYPED_TEST(SegmentedGatherTest, GatherNegatives) { using T = TypeParam; // List<List<T>> { // clang-format off auto const list = LCW<T>{{{2, 3}, {4, 5}}, {{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}, {{15, 16}, {17, 18}, {17, 18}, {17, 18}, {17, 18}}}; auto const gather_map = LCW<int>{{-1, 0}, {-2, -1, 0}, {-5, -4, -3, -2, -1, 0}}; auto const results = cudf::lists::segmented_gather(cudf::lists_column_view{list}, cudf::lists_column_view{gather_map}); auto const expected = LCW<T>{{{4, 5}, {2, 3}}, {{9, 10, 11}, {12, 13, 14}, {6, 7, 8}}, {{15, 16}, {17, 18}, {17, 18}, {17, 18}, {17, 18}, {15, 16}}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected); // clang-format on } // List<List<T>>, with out-of-bounds gather indices. { // clang-format off auto const list = LCW<T>{{{2, 3}, {4, 5}}, {{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}, {{15, 16}, {17, 18}, {17, 18}, {17, 18}, {17, 18}}}; auto const gather_map = LCW<int>{{-1, 0}, {-2, -1, -4}, {-6, -4, -3, -2, -1, 0}}; auto const results = cudf::lists::segmented_gather(cudf::lists_column_view{list}, cudf::lists_column_view{gather_map}, NULLIFY); auto const expected = LCW<T>{{{4, 5}, {2, 3}}, {{{9, 10, 11}, {12, 13, 14}, LCW<T>{}}, null_at(2)}, {{LCW<T>{}, {17, 18}, {17, 18}, {17, 18}, {17, 18}, {15, 16}}, null_at(0)}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected); // clang-format on } } TYPED_TEST(SegmentedGatherTest, GatherOnNonCompactedNullLists) { using T = TypeParam; auto constexpr X = -1; // Signifies null value. // List<T> auto list = LCW<T>{{{1, 2, 3, 4}, {5}, {6, 7}, {8, 9, 0}, {}, {1, 2}, {3, 4, 5}}, no_nulls()}; auto const input = list.release(); // Set non-empty list row at index 5 to null. cudf::detail::set_null_mask( input->mutable_view().null_mask(), 5, 6, false, cudf::get_default_stream()); auto const gather_map = LCW<int>{{-1, 2, 1, -4}, {0}, {-2, 1}, {0, 2, 1}, {}, {0}, {1, 2}}; auto const expected = LCW<T>{{{4, 3, 2, 1}, {5}, {6, 7}, {8, 0, 9}, {}, {{X}, all_nulls()}, {4, 5}}, null_at(5)}; auto const results = cudf::lists::segmented_gather(cudf::lists_column_view{*input}, cudf::lists_column_view{gather_map}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), expected); } TYPED_TEST(SegmentedGatherTest, GatherNestedNulls) { using T = TypeParam; auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); // List<List<T>> { // clang-format off auto const list = LCW<T>{{{{2, 3}, valids}, {4, 5}}, {{{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}, valids}, {{15, 16}, {17, 18}, {17, 18}, {17, 18}, {17, 18}}, {{{{25, 26}, valids}, {27, 28}, {{29, 30}, valids}, {31, 32}, {33, 34}}, valids}}; auto const gather_map = LCW<int>{{0, 1}, {0, 2}, LCW<int>{}, {0, 1, 4}}; auto const results = cudf::lists::segmented_gather(cudf::lists_column_view{list}, cudf::lists_column_view{gather_map}); auto const expected = LCW<T>{{{{2, 3}, valids}, {4, 5}}, {{{6, 7, 8}, {12, 13, 14}}, no_nulls()}, LCW<T>{}, {{{{25, 26}, valids}, {27, 28}, {33, 34}}, valids}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected); // clang-format on } // List<List<List<List<T>>>> { // clang-format off auto const list = LCW<T>{{{{{2, 3}, {4, 5}}, {{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}}, {{{15, 16}, {{27, 28}, valids}, {{37, 38}, valids}, {47, 48}, {57, 58}}}, {{LCW<T>{0}}}, {{{10}, {20, 30, 40, 50}, {60, 70, 80}}, {{0, 1, 3}, {5}}, {{11, 12, 13, 14, 15}, {16, 17}, {0}}}, {{{{{10, 20}, valids}}, {LCW<T>{30}}, {{40, 50}, {60, 70, 80}}}, valids}}}; auto const gather_map = LCW<int>{{1, 2, 4}}; auto const results = cudf::lists::segmented_gather(cudf::lists_column_view{list}, cudf::lists_column_view{gather_map}); auto const expected = LCW<T>{{{{{15, 16}, {{27, 28}, valids}, {{37, 38}, valids}, {47, 48}, {57, 58}}}, {{LCW<T>{0}}}, {{{{{10, 20}, valids}}, {LCW<T>{30}}, {{40, 50}, {60, 70, 80}}}, valids}}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected); // clang-format on } } TYPED_TEST(SegmentedGatherTest, GatherNestedWithEmpties) { using T = TypeParam; auto const list = LCW<T>{{{2, 3}, LCW<T>{}}, {{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}, {LCW<T>{}}}; auto const gather_map = LCW<int>{LCW<int>{0}, LCW<int>{0}, LCW<int>{0}}; auto results = cudf::lists::segmented_gather(cudf::lists_column_view{list}, cudf::lists_column_view{gather_map}); auto const expected = LCW<T>{{{2, 3}}, {{6, 7, 8}}, {LCW<T>{}}}; // skip one null, gather one null. CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected); } TYPED_TEST(SegmentedGatherTest, GatherSliced) { using T = TypeParam; { auto const a = LCW<T>{ {{1, 1, 1}, {2, 2}, {3, 3}}, {{4, 4, 4}, {5, 5}, {6, 6}}, {{7, 7, 7}, {8, 8}, {9, 9}}, {{10, 10, 10}, {11, 11}, {12, 12}}, {{20, 20, 20, 20}, {25}}, {{30, 30, 30, 30}, {40}}, {{50, 50, 50, 50}, {6, 13}}, {{70, 70, 70, 70}, {80}}, }; auto const split_a = cudf::split(a, {3}); { auto const list = LCW<int>{{1, 2}, {0, 2}, {0, 1}}; auto const gather_map = cudf::lists_column_view{list}; auto const result = cudf::lists::segmented_gather(cudf::lists_column_view{split_a[0]}, gather_map); auto const expected = LCW<T>{ {{2, 2}, {3, 3}}, {{4, 4, 4}, {6, 6}}, {{7, 7, 7}, {8, 8}}, }; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } { auto const list = LCW<int>{{0, 1}, LCW<int>{}, LCW<int>{}, {0, 1}, LCW<int>{}}; auto const gather_map = cudf::lists_column_view{list}; auto const result = cudf::lists::segmented_gather(cudf::lists_column_view{split_a[1]}, gather_map); auto const expected = LCW<T>{{{10, 10, 10}, {11, 11}}, LCW<T>{}, LCW<T>{}, {{50, 50, 50, 50}, {6, 13}}, LCW<T>{}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } } auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); // List<List<List<T>>> { LCW<T> list{ // slice 0 {{{2, 3}, {4, 5}}, {{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}}, {{{15, 16}, {{27, 28}, valids}, {{37, 38}, valids}, {47, 48}, {57, 58}}, {{11, 12}, {{42, 43, 44}, valids}, {{77, 78}, valids}}}, // slice 1 {{LCW<T>{0}}}, {{{10}, {20, 30, 40, 50}, {60, 70, 80}}, {{0, 1, 3}, {5}}, {{11, 12, 13, 14, 15}, {16, 17}, {0}}}, {{{{1, 6}, {60, 70, 80, 100}}, {{10, 11, 13}, {15}}, {{11, 12, 13, 14, 15}}}, valids}, // slice 2 {{{{{10, 20}, valids}}, {LCW<T>{30}}, {{40, 50}, {60, 70, 80}}}, valids}, {{{{10, 20, 30}}, {LCW<T>{30}}, {{{20, 30}, valids}, {62, 72, 82}}}, valids}}; auto sliced = cudf::slice(list, {0, 1, 2, 5, 5, 7}); // gather from slice 0 { LCW<int> map{{0, 1}}; auto result = cudf::lists::segmented_gather(cudf::lists_column_view{sliced[0]}, cudf::lists_column_view{map}); LCW<T> expected{{{{2, 3}, {4, 5}}, {{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}}}; CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result->view()); } // gather from slice 1 { LCW<int16_t> map{{0}, {1, 2, 0, 1}, {0, 1, 2}}; auto result = cudf::lists::segmented_gather(cudf::lists_column_view{sliced[1]}, cudf::lists_column_view{map}); LCW<T> expected{ {{LCW<T>{0}}}, {{{0, 1, 3}, {5}}, {{11, 12, 13, 14, 15}, {16, 17}, {0}}, {{10}, {20, 30, 40, 50}, {60, 70, 80}}, {{0, 1, 3}, {5}}}, {{{{1, 6}, {60, 70, 80, 100}}, {{10, 11, 13}, {15}}, {{11, 12, 13, 14, 15}}}, valids}, }; CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result->view()); } // gather from slice 2 { LCW<int> map{{1, 0, 0, 1, 1, 0}, {1, 0, 0, 1, 1, 2}}; auto result = cudf::lists::segmented_gather(cudf::lists_column_view{sliced[2]}, cudf::lists_column_view{map}); std::vector<bool> expected_valids = {false, true, true, false, false, true}; LCW<T> expected{{{{LCW<T>{30}}, {{{10, 20}, valids}}, {{{10, 20}, valids}}, {LCW<T>{30}}, {LCW<T>{30}}, {{{10, 20}, valids}}}, expected_valids.begin()}, {{{LCW<T>{30}}, {{10, 20, 30}}, {{10, 20, 30}}, {LCW<T>{30}}, {LCW<T>{30}}, {{{20, 30}, valids}, {62, 72, 82}}}, expected_valids.begin()}}; CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result->view()); } } } using SegmentedGatherTestString = SegmentedGatherTest<cudf::string_view>; TEST_F(SegmentedGatherTestString, StringGather) { using T = cudf::string_view; // List<T> { auto const list = LCW<T>{{"a", "b", "c", "d"}, {"1", "22", "333", "4"}, {"x", "y", "z"}}; auto const gather_map = LCW<int8_t>{{0, 1, 3, 2}, {1, 0, 3, 2}, LCW<int8_t>{}}; auto const expected = LCW<T>{{"a", "b", "d", "c"}, {"22", "1", "4", "333"}, LCW<T>{}}; auto const result = cudf::lists::segmented_gather(cudf::lists_column_view{list}, cudf::lists_column_view{gather_map}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } // List<T>, with out-of-order gather indices. { auto const list = LCW<T>{{"a", "b", "c", "d"}, {"1", "22", "333", "4"}, {"x", "y", "z"}}; auto const gather_map = LCW<int8_t>{{0, 1, 3, 4}, {1, -5, 3, 2}, LCW<int8_t>{}}; auto const expected = LCW<T>{{{"a", "b", "d", "c"}, cudf::test::iterators::null_at(3)}, {{"22", "1", "4", "333"}, cudf::test::iterators::null_at(1)}, LCW<T>{}}; auto result = cudf::lists::segmented_gather( cudf::lists_column_view{list}, cudf::lists_column_view{gather_map}, NULLIFY); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } } using SegmentedGatherTestFloat = SegmentedGatherTest<float>; TEST_F(SegmentedGatherTestFloat, GatherMapSliced) { using T = float; // List<T> { auto const list = LCW<T>{{1, 2, 3, 4}, {5}, {6, 7}, {8, 9, 10}, {11, 12}, {13, 14, 15, 16}}; auto const gather_map = LCW<int>{{3, 2, 1, 0}, {0}, {0, 1}, {0, 2, 1}, {0}, {1}}; // gather_map.offset: 0, 4, 5, 7, 10, 11, 12 auto const expected = LCW<T>{{4, 3, 2, 1}, {5}, {6, 7}, {8, 10, 9}, {11}, {14}}; auto const results = cudf::lists::segmented_gather(cudf::lists_column_view{list}, cudf::lists_column_view{gather_map}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected); auto const sliced = cudf::split(list, {1, 4}); auto const split_m = cudf::split(gather_map, {1, 4}); auto const split_e = cudf::split(expected, {1, 4}); auto result0 = cudf::lists::segmented_gather(cudf::lists_column_view{sliced[0]}, cudf::lists_column_view{split_m[0]}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(split_e[0], result0->view()); auto result1 = cudf::lists::segmented_gather(cudf::lists_column_view{sliced[1]}, cudf::lists_column_view{split_m[1]}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(split_e[1], result1->view()); auto result2 = cudf::lists::segmented_gather(cudf::lists_column_view{sliced[2]}, cudf::lists_column_view{split_m[2]}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(split_e[2], result2->view()); } // List<T>, with out-of-bounds gather indices. { auto const list = LCW<T>{{1, 2, 3, 4}, {5}, {6, 7}, {8, 9, 10}, {11, 12}, {13, 14, 15, 16}}; auto const gather_map = LCW<int>{{3, -5, 1, 0}, {0}, {0, 1}, {0, 2, 3}, {0}, {1}}; // gather_map.offset: 0, 4, 5, 7, 10, 11, 12 auto const expected = LCW<T>{{{4, 0, 2, 1}, null_at(1)}, {5}, {6, 7}, {{8, 10, 9}, null_at(2)}, {11}, {14}}; auto results = cudf::lists::segmented_gather( cudf::lists_column_view{list}, cudf::lists_column_view{gather_map}, NULLIFY); CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected); auto const sliced = cudf::split(list, {1, 4}); auto const split_m = cudf::split(gather_map, {1, 4}); auto const split_e = cudf::split(expected, {1, 4}); auto const result0 = cudf::lists::segmented_gather( cudf::lists_column_view{sliced[0]}, cudf::lists_column_view{split_m[0]}, NULLIFY); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(split_e[0], result0->view()); auto const result1 = cudf::lists::segmented_gather( cudf::lists_column_view{sliced[1]}, cudf::lists_column_view{split_m[1]}, NULLIFY); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(split_e[1], result1->view()); auto const result2 = cudf::lists::segmented_gather( cudf::lists_column_view{sliced[2]}, cudf::lists_column_view{split_m[2]}, NULLIFY); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(split_e[2], result2->view()); } } TEST_F(SegmentedGatherTestFloat, Fails) { using T = float; // List<T> LCW<T> list{{1, 2, 3, 4}, {5}, {6, 7}, {8, 9, 10}}; LCW<int8_t> size_mismatch_map{{3, 2, 1, 0}, {0}, {0, 1}}; cudf::test::fixed_width_column_wrapper<int> nonlist_map0{1, 2, 0, 1}; cudf::test::strings_column_wrapper nonlist_map1{"1", "2", "0", "1"}; LCW<cudf::string_view> nonlist_map2{{"1", "2", "0", "1"}}; // Input must be a list of integer indices. It should fail for integers, // strings, or lists containing anything other than integers. EXPECT_THROW(cudf::lists::segmented_gather(cudf::lists_column_view{list}, cudf::lists_column_view{nonlist_map0}), cudf::logic_error); EXPECT_THROW(cudf::lists::segmented_gather(cudf::lists_column_view{list}, cudf::lists_column_view{nonlist_map1}), cudf::logic_error); EXPECT_THROW(cudf::lists::segmented_gather(cudf::lists_column_view{list}, cudf::lists_column_view{nonlist_map2}), cudf::logic_error); auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); LCW<int8_t> nulls_map{{{3, 2, 1, 0}, {0}, {0}, {0, 1}}, valids}; // Nulls are not supported in the gather map. EXPECT_THROW(cudf::lists::segmented_gather(cudf::lists_column_view{list}, cudf::lists_column_view{nulls_map}), std::invalid_argument); // Gather map and list column sizes must be the same. EXPECT_THROW(cudf::lists::segmented_gather(cudf::lists_column_view{list}, cudf::lists_column_view{size_mismatch_map}), cudf::logic_error); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/utility_tests.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/column/column_factories.hpp> #include <cudf/copying.hpp> #include <cudf/strings/detail/utilities.hpp> #include <cudf/table/table.hpp> #include <cudf/utilities/type_dispatcher.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <thrust/iterator/transform_iterator.h> #include <string> template <typename T> struct EmptyLikeTest : public cudf::test::BaseFixture {}; using numeric_types = cudf::test::NumericTypes; TYPED_TEST_SUITE(EmptyLikeTest, numeric_types); TYPED_TEST(EmptyLikeTest, ColumnNumericTests) { cudf::size_type size = 10; cudf::mask_state state = cudf::mask_state::ALL_VALID; auto input = make_numeric_column(cudf::data_type{cudf::type_to_id<TypeParam>()}, size, state); auto expected = make_numeric_column(cudf::data_type{cudf::type_to_id<TypeParam>()}, 0); auto got = cudf::empty_like(input->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*expected, *got); } struct EmptyLikeStringTest : public EmptyLikeTest<std::string> {}; void check_empty_string_columns(cudf::column_view lhs, cudf::column_view rhs) { EXPECT_EQ(lhs.type(), rhs.type()); EXPECT_EQ(lhs.size(), 0); EXPECT_EQ(lhs.null_count(), 0); EXPECT_EQ(lhs.nullable(), false); EXPECT_EQ(lhs.has_nulls(), false); // An empty column is not required to have children } TEST_F(EmptyLikeStringTest, ColumnStringTest) { std::vector<char const*> h_strings{"the quick brown fox jumps over the lazy dog", "thé result does not include the value in the sum in", "", nullptr, "absent stop words"}; cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(), thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; })); auto got = cudf::empty_like(strings); check_empty_string_columns(got->view(), strings); } template <typename T> struct EmptyLikeScalarTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(EmptyLikeScalarTest, cudf::test::FixedWidthTypes); TYPED_TEST(EmptyLikeScalarTest, FixedWidth) { // make a column auto input = make_fixed_width_column( cudf::data_type{cudf::type_to_id<TypeParam>()}, 1, rmm::device_buffer{}, 0); // get a scalar out of it std::unique_ptr<cudf::scalar> sc = cudf::get_element(*input, 0); // empty_like(column) -> column auto expected = cudf::empty_like(*input); // empty_like(scalar) -> column auto result = cudf::empty_like(*sc); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *result); } struct EmptyLikeScalarStringTest : public EmptyLikeScalarTest<std::string> {}; TEST_F(EmptyLikeScalarStringTest, String) { // make a column cudf::test::strings_column_wrapper input{"abc"}; // get a scalar out of it std::unique_ptr<cudf::scalar> sc = cudf::get_element(input, 0); // empty_like(column) -> column auto expected = cudf::empty_like(input); // empty_like(scalar) -> column auto result = cudf::empty_like(*sc); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *result); } struct EmptyLikeScalarListTest : public EmptyLikeScalarTest<cudf::list_view> {}; TEST_F(EmptyLikeScalarListTest, List) { // make a column cudf::test::lists_column_wrapper<cudf::string_view> input{{{"abc", "def"}, {"h", "ijk"}}, {{"123", "456"}, {"78"}}}; // get a scalar out of it std::unique_ptr<cudf::scalar> sc = cudf::get_element(input, 0); // empty_like(column) -> column auto expected = cudf::empty_like(input); // empty_like(scalar) -> column auto result = cudf::empty_like(*sc); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *result); } struct EmptyLikeScalarStructTest : public EmptyLikeScalarTest<cudf::struct_view> {}; TEST_F(EmptyLikeScalarStructTest, Struct) { cudf::test::lists_column_wrapper<cudf::string_view> col0{{{"abc", "def"}, {"h", "ijk"}}}; cudf::test::strings_column_wrapper col1{"abc"}; cudf::test::fixed_width_column_wrapper<float> col2{1.0f}; // scalar. TODO: make cudf::get_element() work for struct scalars cudf::table_view tbl({col0, col1, col2}); cudf::struct_scalar sc(tbl); // column cudf::test::structs_column_wrapper input({col0, col1, col2}); // empty_like(column) -> column auto expected = cudf::empty_like(input); // empty_like(scalar) -> column auto result = cudf::empty_like(sc); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *result); } std::unique_ptr<cudf::table> create_table(cudf::size_type size, cudf::mask_state state) { auto num_column_1 = make_numeric_column(cudf::data_type{cudf::type_id::INT64}, size, state); auto num_column_2 = make_numeric_column(cudf::data_type{cudf::type_id::INT32}, size, state); auto num_column_3 = make_numeric_column(cudf::data_type{cudf::type_id::FLOAT64}, size, state); auto num_column_4 = make_numeric_column(cudf::data_type{cudf::type_id::FLOAT32}, size, state); std::vector<std::unique_ptr<cudf::column>> columns; columns.push_back(std::move(num_column_1)); columns.push_back(std::move(num_column_2)); columns.push_back(std::move(num_column_3)); columns.push_back(std::move(num_column_4)); return std::make_unique<cudf::table>(std::move(columns)); } struct EmptyLikeTableTest : public cudf::test::BaseFixture {}; TEST_F(EmptyLikeTableTest, TableTest) { cudf::mask_state state = cudf::mask_state::ALL_VALID; cudf::size_type size = 10; auto input = create_table(size, state); auto expected = create_table(0, cudf::mask_state::ALL_VALID); auto got = cudf::empty_like(input->view()); CUDF_TEST_EXPECT_TABLES_EQUAL(got->view(), expected->view()); } template <typename T> struct AllocateLikeTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(AllocateLikeTest, numeric_types); TYPED_TEST(AllocateLikeTest, ColumnNumericTestSameSize) { // For same size as input cudf::size_type size = 10; auto input = make_numeric_column( cudf::data_type{cudf::type_to_id<TypeParam>()}, size, cudf::mask_state::UNALLOCATED); auto got = cudf::allocate_like(input->view()); CUDF_TEST_EXPECT_COLUMN_PROPERTIES_EQUAL(*input, *got); input = make_numeric_column( cudf::data_type{cudf::type_to_id<TypeParam>()}, size, cudf::mask_state::ALL_VALID); got = cudf::allocate_like(input->view()); CUDF_TEST_EXPECT_COLUMN_PROPERTIES_EQUAL(*input, *got); } TYPED_TEST(AllocateLikeTest, ColumnNumericTestSpecifiedSize) { // For different size as input cudf::size_type size = 10; cudf::size_type specified_size = 5; auto state = cudf::mask_state::UNALLOCATED; auto input = make_numeric_column(cudf::data_type{cudf::type_to_id<TypeParam>()}, size, state); auto expected = make_numeric_column(cudf::data_type{cudf::type_to_id<TypeParam>()}, specified_size, state); auto got = cudf::allocate_like(input->view(), specified_size); CUDF_TEST_EXPECT_COLUMN_PROPERTIES_EQUAL(*expected, *got); input = make_numeric_column( cudf::data_type{cudf::type_to_id<TypeParam>()}, size, cudf::mask_state::ALL_VALID); got = cudf::allocate_like(input->view(), specified_size); // Can't use CUDF_TEST_EXPECT_COLUMN_PROPERTIES_EQUAL because the sizes of // the two columns are different. EXPECT_EQ(input->type(), got->type()); EXPECT_EQ(specified_size, got->size()); EXPECT_EQ(0, got->null_count()); EXPECT_EQ(input->nullable(), got->nullable()); EXPECT_EQ(input->num_children(), got->num_children()); } CUDF_TEST_PROGRAM_MAIN()
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/detail_gather_tests.cu
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/column/column_view.hpp> #include <cudf/copying.hpp> #include <cudf/detail/gather.cuh> #include <cudf/detail/gather.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> #include <cudf/utilities/default_stream.hpp> #include <rmm/device_uvector.hpp> #include <thrust/execution_policy.h> #include <thrust/sequence.h> template <typename T> class GatherTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(GatherTest, cudf::test::NumericTypes); // This test exercises using different iterator types as gather map inputs // to cudf::detail::gather -- device_uvector and raw pointers. TYPED_TEST(GatherTest, GatherDetailDeviceVectorTest) { constexpr cudf::size_type source_size{1000}; rmm::device_uvector<cudf::size_type> gather_map(source_size, cudf::get_default_stream()); thrust::sequence( rmm::exec_policy_nosync(cudf::get_default_stream()), gather_map.begin(), gather_map.end()); auto data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i; }); cudf::test::fixed_width_column_wrapper<TypeParam> source_column(data, data + source_size); cudf::table_view source_table({source_column}); // test with device vector iterators { std::unique_ptr<cudf::table> result = cudf::detail::gather(source_table, gather_map.begin(), gather_map.end(), cudf::out_of_bounds_policy::DONT_CHECK, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); for (auto i = 0; i < source_table.num_columns(); ++i) { CUDF_TEST_EXPECT_COLUMNS_EQUAL(source_table.column(i), result->view().column(i)); } CUDF_TEST_EXPECT_TABLES_EQUAL(source_table, result->view()); } // test with raw pointers { std::unique_ptr<cudf::table> result = cudf::detail::gather(source_table, gather_map.begin(), gather_map.data() + gather_map.size(), cudf::out_of_bounds_policy::DONT_CHECK, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); for (auto i = 0; i < source_table.num_columns(); ++i) { CUDF_TEST_EXPECT_COLUMNS_EQUAL(source_table.column(i), result->view().column(i)); } CUDF_TEST_EXPECT_TABLES_EQUAL(source_table, result->view()); } } TYPED_TEST(GatherTest, GatherDetailInvalidIndexTest) { constexpr cudf::size_type source_size{1000}; auto data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i; }); cudf::test::fixed_width_column_wrapper<TypeParam> source_column(data, data + source_size); auto gather_map_data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return (i % 2) ? -1 : i; }); cudf::test::fixed_width_column_wrapper<int32_t> gather_map(gather_map_data, gather_map_data + (source_size * 2)); cudf::table_view source_table({source_column}); std::unique_ptr<cudf::table> result = cudf::detail::gather(source_table, gather_map, cudf::out_of_bounds_policy::NULLIFY, cudf::detail::negative_index_policy::NOT_ALLOWED, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto expect_data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return (i % 2) ? 0 : i; }); auto expect_valid = cudf::detail::make_counting_transform_iterator( 0, [](auto i) { return (i % 2) || (i >= source_size) ? 0 : 1; }); cudf::test::fixed_width_column_wrapper<TypeParam> expect_column( expect_data, expect_data + (source_size * 2), expect_valid); for (auto i = 0; i < source_table.num_columns(); ++i) { CUDF_TEST_EXPECT_COLUMNS_EQUAL(expect_column, result->view().column(i)); } }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/scatter_tests.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/copying.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/scalar/scalar_factories.hpp> #include <cudf/stream_compaction.hpp> class ScatterUntypedTests : public cudf::test::BaseFixture {}; // Throw logic error if scatter map is longer than source TEST_F(ScatterUntypedTests, ScatterMapTooLong) { cudf::test::fixed_width_column_wrapper<int32_t> source({1, 2, 3, 4, 5, 6}); cudf::test::fixed_width_column_wrapper<int32_t> target({10, 20, 30, 40, 50, 60, 70, 80}); cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({-3, 3, 1, -1, 0, 2, 4, 6}); auto const source_table = cudf::table_view({source, source}); auto const target_table = cudf::table_view({target, target}); EXPECT_THROW(cudf::scatter(source_table, scatter_map, target_table), cudf::logic_error); } // Throw logic error if scatter map has nulls TEST_F(ScatterUntypedTests, ScatterMapNulls) { cudf::test::fixed_width_column_wrapper<int32_t> source({1, 2, 3, 4, 5, 6}); cudf::test::fixed_width_column_wrapper<int32_t> target({10, 20, 30, 40, 50, 60, 70, 80}); cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({-3, 3, 1, -1}, {0, 1, 1, 1}); auto const source_table = cudf::table_view({source, source}); auto const target_table = cudf::table_view({target, target}); EXPECT_THROW(cudf::scatter(source_table, scatter_map, target_table), cudf::logic_error); } // Throw logic error if scatter map has nulls TEST_F(ScatterUntypedTests, ScatterScalarMapNulls) { auto const source = cudf::scalar_type_t<int32_t>{100}; std::reference_wrapper<const cudf::scalar> slr_ref{source}; std::vector<std::reference_wrapper<const cudf::scalar>> source_vector{slr_ref}; cudf::test::fixed_width_column_wrapper<int32_t> target({10, 20, 30, 40, 50, 60, 70, 80}); cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({-3, 3, 1, -1}, {0, 1, 1, 1}); auto const target_table = cudf::table_view({target}); EXPECT_THROW(cudf::scatter(source_vector, scatter_map, target_table), cudf::logic_error); } // Throw logic error if source and target have different number of columns TEST_F(ScatterUntypedTests, ScatterColumnNumberMismatch) { cudf::test::fixed_width_column_wrapper<int32_t> source({1, 2, 3, 4, 5, 6}); cudf::test::fixed_width_column_wrapper<int32_t> target({10, 20, 30, 40, 50, 60, 70, 80}); cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({-3, 3, 1, -1}); auto const source_table = cudf::table_view({source}); auto const target_table = cudf::table_view({target, target}); EXPECT_THROW(cudf::scatter(source_table, scatter_map, target_table), cudf::logic_error); } // Throw logic error if number of scalars doesn't match number of columns TEST_F(ScatterUntypedTests, ScatterScalarColumnNumberMismatch) { auto const source = cudf::scalar_type_t<int32_t>(100); std::reference_wrapper<const cudf::scalar> slr_ref{source}; std::vector<std::reference_wrapper<const cudf::scalar>> source_vector{slr_ref}; cudf::test::fixed_width_column_wrapper<int32_t> target({10, 20, 30, 40, 50, 60, 70, 80}); cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({-3, 3, 1, -1}); auto const target_table = cudf::table_view({target, target}); EXPECT_THROW(cudf::scatter(source_vector, scatter_map, target_table), cudf::logic_error); } // Throw logic error if source and target have different data types TEST_F(ScatterUntypedTests, ScatterDataTypeMismatch) { cudf::test::fixed_width_column_wrapper<int32_t> source({1, 2, 3, 4, 5, 6}); cudf::test::fixed_width_column_wrapper<float> target({10, 20, 30, 40, 50, 60, 70, 80}); cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({-3, 3, 1, -1}); auto const source_table = cudf::table_view({source}); auto const target_table = cudf::table_view({target}); EXPECT_THROW(cudf::scatter(source_table, scatter_map, target_table), cudf::logic_error); } // Throw logic error if source and target have different data types TEST_F(ScatterUntypedTests, ScatterScalarDataTypeMismatch) { auto const source = cudf::scalar_type_t<int32_t>(100); std::reference_wrapper<const cudf::scalar> slr_ref{source}; std::vector<std::reference_wrapper<const cudf::scalar>> source_vector{slr_ref}; cudf::test::fixed_width_column_wrapper<float> target({10, 20, 30, 40, 50, 60, 70, 80}); cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({-3, 3, 1, -1}); auto const target_table = cudf::table_view({target}); EXPECT_THROW(cudf::scatter(source_vector, scatter_map, target_table), cudf::logic_error); } template <typename T> class ScatterIndexTypeTests : public cudf::test::BaseFixture {}; using IndexTypes = cudf::test::Types<int8_t, int16_t, int32_t, int64_t>; TYPED_TEST_SUITE(ScatterIndexTypeTests, IndexTypes); // Validate that each of the index types work TYPED_TEST(ScatterIndexTypeTests, ScatterIndexType) { cudf::test::fixed_width_column_wrapper<TypeParam> source({1, 2, 3, 4, 5, 6}); cudf::test::fixed_width_column_wrapper<TypeParam> target({10, 20, 30, 40, 50, 60, 70, 80}); cudf::test::fixed_width_column_wrapper<TypeParam> scatter_map({-3, 3, 1, -1}); cudf::test::fixed_width_column_wrapper<TypeParam> expected({10, 3, 30, 2, 50, 1, 70, 4}); auto const source_table = cudf::table_view({source, source}); auto const target_table = cudf::table_view({target, target}); auto const expected_table = cudf::table_view({expected, expected}); auto const result = cudf::scatter(source_table, scatter_map, target_table); CUDF_TEST_EXPECT_TABLES_EQUAL(result->view(), expected_table); } // Validate that each of the index types work TYPED_TEST(ScatterIndexTypeTests, ScatterScalarIndexType) { auto const source = cudf::scalar_type_t<TypeParam>(100, true); std::reference_wrapper<const cudf::scalar> slr_ref{source}; std::vector<std::reference_wrapper<const cudf::scalar>> source_vector{slr_ref}; cudf::test::fixed_width_column_wrapper<TypeParam> target({10, 20, 30, 40, 50, 60, 70, 80}); cudf::test::fixed_width_column_wrapper<TypeParam> scatter_map({-3, 3, 1, -1}); cudf::test::fixed_width_column_wrapper<TypeParam> expected({10, 100, 30, 100, 50, 100, 70, 100}); auto const target_table = cudf::table_view({target}); auto const expected_table = cudf::table_view({expected}); auto const result = cudf::scatter(source_vector, scatter_map, target_table); CUDF_TEST_EXPECT_TABLES_EQUAL(result->view(), expected_table); } template <typename T> class ScatterInvalidIndexTypeTests : public cudf::test::BaseFixture {}; // NOTE string types hit static assert in fixed_width_column_wrapper using InvalidIndexTypes = cudf::test::Concat<cudf::test::Types<float, double, bool>, cudf::test::ChronoTypes, cudf::test::FixedPointTypes>; TYPED_TEST_SUITE(ScatterInvalidIndexTypeTests, InvalidIndexTypes); // Throw logic error if scatter map column has invalid data type TYPED_TEST(ScatterInvalidIndexTypeTests, ScatterInvalidIndexType) { cudf::test::fixed_width_column_wrapper<int32_t> source({1, 2, 3, 4, 5, 6}); cudf::test::fixed_width_column_wrapper<int32_t> target({10, 20, 30, 40, 50, 60, 70, 80}); cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> scatter_map({-3, 3, 1, -1}); auto const source_table = cudf::table_view({source, source}); auto const target_table = cudf::table_view({target, target}); EXPECT_THROW(cudf::scatter(source_table, scatter_map, target_table), cudf::logic_error); } // Throw logic error if scatter map column has invalid data type TYPED_TEST(ScatterInvalidIndexTypeTests, ScatterScalarInvalidIndexType) { auto const source = cudf::scalar_type_t<int32_t>(100, true); std::reference_wrapper<const cudf::scalar> slr_ref{source}; std::vector<std::reference_wrapper<const cudf::scalar>> source_vector{slr_ref}; cudf::test::fixed_width_column_wrapper<int32_t> target({10, 20, 30, 40, 50, 60, 70, 80}); cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> scatter_map({-3, 3, 1, -1}); auto const target_table = cudf::table_view({target}); EXPECT_THROW(cudf::scatter(source_vector, scatter_map, target_table), cudf::logic_error); } template <typename T> class ScatterDataTypeTests : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(ScatterDataTypeTests, cudf::test::FixedWidthTypes); // Empty scatter map returns copy of input TYPED_TEST(ScatterDataTypeTests, EmptyScatterMap) { cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> source({1, 2, 3, 4, 5, 6}); cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> target( {10, 20, 30, 40, 50, 60, 70, 80}); cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({}); auto const source_table = cudf::table_view({source, source}); auto const target_table = cudf::table_view({target, target}); auto const result = cudf::scatter(source_table, scatter_map, target_table); // Expect a copy of the input table CUDF_TEST_EXPECT_TABLES_EQUAL(result->view(), target_table); } // Empty scatter map returns copy of input TYPED_TEST(ScatterDataTypeTests, EmptyScalarScatterMap) { auto const source = cudf::scalar_type_t<TypeParam>(cudf::test::make_type_param_scalar<TypeParam>(100), true); std::reference_wrapper<const cudf::scalar> slr_ref{source}; std::vector<std::reference_wrapper<const cudf::scalar>> source_vector{slr_ref}; cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> target( {10, 20, 30, 40, 50, 60, 70, 80}); cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({}); auto const target_table = cudf::table_view({target}); auto const result = cudf::scatter(source_vector, scatter_map, target_table); // Expect a copy of the input table CUDF_TEST_EXPECT_TABLES_EQUAL(result->view(), target_table); } TYPED_TEST(ScatterDataTypeTests, ScatterNoNulls) { cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> source({1, 2, 3, 4, 5, 6}); cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> target( {10, 20, 30, 40, 50, 60, 70, 80}); cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({-3, 3, 1, -1}); cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> expected({10, 3, 30, 2, 50, 1, 70, 4}); auto const source_table = cudf::table_view({source, source}); auto const target_table = cudf::table_view({target, target}); auto const expected_table = cudf::table_view({expected, expected}); auto const result = cudf::scatter(source_table, scatter_map, target_table); CUDF_TEST_EXPECT_TABLES_EQUAL(result->view(), expected_table); } TYPED_TEST(ScatterDataTypeTests, ScatterBothNulls) { cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> source({2, 4, 6, 8}, {1, 1, 0, 0}); cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> target( {10, 20, 30, 40, 50, 60, 70, 80}, {0, 0, 0, 0, 1, 1, 1, 1}); cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({1, 3, -3, -1}); cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> expected({10, 2, 30, 4, 50, 6, 70, 8}, {0, 1, 0, 1, 1, 0, 1, 0}); auto const source_table = cudf::table_view({source, source}); auto const target_table = cudf::table_view({target, target}); auto const expected_table = cudf::table_view({expected, expected}); auto const result = cudf::scatter(source_table, scatter_map, target_table); CUDF_TEST_EXPECT_TABLES_EQUAL(result->view(), expected_table); } TYPED_TEST(ScatterDataTypeTests, ScatterSourceNulls) { cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> source({2, 4, 6, 8}, {1, 1, 0, 0}); cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> target( {10, 20, 30, 40, 50, 60, 70, 80}); cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({1, 3, -3, -1}); cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> expected({10, 2, 30, 4, 50, 6, 70, 8}, {1, 1, 1, 1, 1, 0, 1, 0}); auto const source_table = cudf::table_view({source, source}); auto const target_table = cudf::table_view({target, target}); auto const expected_table = cudf::table_view({expected, expected}); auto const result = cudf::scatter(source_table, scatter_map, target_table); CUDF_TEST_EXPECT_TABLES_EQUAL(result->view(), expected_table); } TYPED_TEST(ScatterDataTypeTests, ScatterTargetNulls) { cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> source({2, 4, 6, 8}); cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> target( {10, 20, 30, 40, 50, 60, 70, 80}, {0, 0, 0, 0, 1, 1, 1, 1}); cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({1, 3, -3, -1}); cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> expected({10, 2, 30, 4, 50, 6, 70, 8}, {0, 1, 0, 1, 1, 1, 1, 1}); auto const source_table = cudf::table_view({source, source}); auto const target_table = cudf::table_view({target, target}); auto const expected_table = cudf::table_view({expected, expected}); auto const result = cudf::scatter(source_table, scatter_map, target_table); CUDF_TEST_EXPECT_TABLES_EQUAL(result->view(), expected_table); } TYPED_TEST(ScatterDataTypeTests, ScatterScalarNoNulls) { using Type = cudf::device_storage_type_t<TypeParam>; auto const source = cudf::scalar_type_t<TypeParam>(cudf::test::make_type_param_scalar<Type>(100), true); std::reference_wrapper<const cudf::scalar> slr_ref{source}; std::vector<std::reference_wrapper<const cudf::scalar>> source_vector{slr_ref}; cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> target( {10, 20, 30, 40, 50, 60, 70, 80}); cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({-3, 3, 1, -1}); cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> expected( {10, 100, 30, 100, 50, 100, 70, 100}); auto const target_table = cudf::table_view({target}); auto const expected_table = cudf::table_view({expected}); auto const result = cudf::scatter(source_vector, scatter_map, target_table); CUDF_TEST_EXPECT_TABLES_EQUAL(result->view(), expected_table); } TYPED_TEST(ScatterDataTypeTests, ScatterScalarTargetNulls) { using Type = cudf::device_storage_type_t<TypeParam>; auto const source = cudf::scalar_type_t<TypeParam>(cudf::test::make_type_param_scalar<Type>(100), true); std::reference_wrapper<const cudf::scalar> slr_ref{source}; std::vector<std::reference_wrapper<const cudf::scalar>> source_vector{slr_ref}; cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> target( {10, 20, 30, 40, 50, 60, 70, 80}, {0, 0, 0, 0, 1, 1, 1, 1}); cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({-3, 3, 1, -1}); cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> expected( {10, 100, 30, 100, 50, 100, 70, 100}, {0, 1, 0, 1, 1, 1, 1, 1}); auto const target_table = cudf::table_view({target}); auto const expected_table = cudf::table_view({expected}); auto const result = cudf::scatter(source_vector, scatter_map, target_table); CUDF_TEST_EXPECT_TABLES_EQUAL(result->view(), expected_table); } TYPED_TEST(ScatterDataTypeTests, ScatterScalarSourceNulls) { using Type = cudf::device_storage_type_t<TypeParam>; auto const source = cudf::scalar_type_t<TypeParam>(cudf::test::make_type_param_scalar<Type>(100), false); std::reference_wrapper<const cudf::scalar> slr_ref{source}; std::vector<std::reference_wrapper<const cudf::scalar>> source_vector{slr_ref}; cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> target( {10, 20, 30, 40, 50, 60, 70, 80}); cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({-3, 3, 1, -1}); cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> expected( {10, 100, 30, 100, 50, 100, 70, 100}, {1, 0, 1, 0, 1, 0, 1, 0}); auto const target_table = cudf::table_view({target}); auto const expected_table = cudf::table_view({expected}); auto const result = cudf::scatter(source_vector, scatter_map, target_table); CUDF_TEST_EXPECT_TABLES_EQUAL(result->view(), expected_table); } TYPED_TEST(ScatterDataTypeTests, ScatterScalarBothNulls) { using Type = cudf::device_storage_type_t<TypeParam>; auto const source = cudf::scalar_type_t<TypeParam>(cudf::test::make_type_param_scalar<Type>(100), false); std::reference_wrapper<const cudf::scalar> slr_ref{source}; std::vector<std::reference_wrapper<const cudf::scalar>> source_vector{slr_ref}; cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> target( {10, 20, 30, 40, 50, 60, 70, 80}, {0, 0, 0, 0, 1, 1, 1, 1}); cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({-3, 3, 1, -1}); cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> expected( {10, 100, 30, 100, 50, 100, 70, 100}, {0, 0, 0, 0, 1, 0, 1, 0}); auto const target_table = cudf::table_view({target}); auto const expected_table = cudf::table_view({expected}); auto const result = cudf::scatter(source_vector, scatter_map, target_table); CUDF_TEST_EXPECT_TABLES_EQUAL(result->view(), expected_table); } TYPED_TEST(ScatterDataTypeTests, ScatterSourceNullsLarge) { constexpr cudf::size_type N{513}; cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> source({0, 0, 0, 0}, {0, 0, 0, 0}); cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({0, 1, 2, 3}); auto target_data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i; }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(target_data)::value_type> target(target_data, target_data + N); auto expect_data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i; }); auto expect_valid = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i > 3; }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(expect_data)::value_type> expected(expect_data, expect_data + N, expect_valid); auto const source_table = cudf::table_view({source, source}); auto const target_table = cudf::table_view({target, target}); auto const expected_table = cudf::table_view({expected, expected}); auto const result = cudf::scatter(source_table, scatter_map, target_table); CUDF_TEST_EXPECT_TABLES_EQUAL(result->view(), expected_table); } class ScatterStringsTests : public cudf::test::BaseFixture {}; TEST_F(ScatterStringsTests, ScatterNoNulls) { std::vector<char const*> h_source{"dog", "the", "jumps", "brown", "the"}; cudf::test::strings_column_wrapper source(h_source.begin(), h_source.end()); std::vector<char const*> h_target{ "a", "quick", "fire", "fox", "browses", "over", "a", "lazy", "web"}; cudf::test::strings_column_wrapper target(h_target.begin(), h_target.end()); cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({-1, -3, -5, 2, 0}); std::vector<char const*> h_expected{ "the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"}; cudf::test::strings_column_wrapper expected(h_expected.begin(), h_expected.end()); auto const source_table = cudf::table_view({source, source}); auto const target_table = cudf::table_view({target, target}); auto const expected_table = cudf::table_view({expected, expected}); auto const result = cudf::scatter(source_table, scatter_map, target_table); CUDF_TEST_EXPECT_TABLES_EQUAL(result->view(), expected_table); } TEST_F(ScatterStringsTests, ScatterScalarNoNulls) { auto const source = cudf::string_scalar("buffalo"); std::reference_wrapper<const cudf::scalar> slr_ref{source}; std::vector<std::reference_wrapper<const cudf::scalar>> source_vector{slr_ref}; std::vector<char const*> h_target{ "Buffalo", "bison", "Buffalo", "bison", "bully", "bully", "Buffalo", "bison"}; cudf::test::strings_column_wrapper target(h_target.begin(), h_target.end()); cudf::test::fixed_width_column_wrapper<int32_t> scatter_map({1, 3, -4, -3, -1}); std::vector<char const*> h_expected{ "Buffalo", "buffalo", "Buffalo", "buffalo", "buffalo", "buffalo", "Buffalo", "buffalo"}; cudf::test::strings_column_wrapper expected(h_expected.begin(), h_expected.end()); auto const target_table = cudf::table_view({target}); auto const expected_table = cudf::table_view({expected}); auto const result = cudf::scatter(source_vector, scatter_map, target_table); CUDF_TEST_EXPECT_TABLES_EQUAL(result->view(), expected_table); } TEST_F(ScatterStringsTests, EmptyStrings) { cudf::test::strings_column_wrapper input{"", "", ""}; cudf::table_view t({input}); // Test for issue 10717: all-empty-string column scatter auto map = cudf::test::fixed_width_column_wrapper<int32_t>({0}); auto result = cudf::scatter(t, map, t); CUDF_TEST_EXPECT_TABLES_EQUAL(result->view(), t); } template <typename T> class BooleanMaskScatter : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(BooleanMaskScatter, cudf::test::FixedWidthTypes); TYPED_TEST(BooleanMaskScatter, WithNoNullElementsInTarget) { using T = TypeParam; cudf::test::fixed_width_column_wrapper<T, int32_t> source({1, 5, 6, 8, 9}); cudf::test::fixed_width_column_wrapper<T, int32_t> target({2, 2, 3, 4, 11, 12, 7, 7, 10, 10}); cudf::test::fixed_width_column_wrapper<bool> mask( {true, false, false, false, true, true, false, true, true, false}); cudf::test::fixed_width_column_wrapper<T, int32_t> expected({1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); auto source_table = cudf::table_view({source}); auto target_table = cudf::table_view({target}); auto expected_table = cudf::table_view({expected}); auto got = cudf::boolean_mask_scatter(source_table, target_table, mask); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_table, got->view()); } TYPED_TEST(BooleanMaskScatter, WithNull) { using T = TypeParam; cudf::test::fixed_width_column_wrapper<T, int32_t> source_col1({1, 5, 6, 8, 9}, {1, 0, 1, 0, 1}); cudf::test::strings_column_wrapper source_col2({"This", "is", "cudf", "test", "column"}, {1, 0, 0, 1, 0}); cudf::test::fixed_width_column_wrapper<T, int32_t> target_col1({2, 2, 3, 4, 11, 12, 7, 7, 10, 10}, {1, 1, 0, 1, 1, 1, 1, 1, 1, 0}); cudf::test::strings_column_wrapper target_col2( {"a", "bc", "cd", "ef", "gh", "ij", "jk", "lm", "no", "pq"}, {1, 1, 0, 1, 1, 1, 1, 1, 1, 0}); cudf::test::fixed_width_column_wrapper<bool> mask( {true, false, false, false, true, true, false, true, true, false}); cudf::test::fixed_width_column_wrapper<T, int32_t> expected_col1({1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {1, 1, 0, 1, 0, 1, 1, 0, 1, 0}); cudf::test::strings_column_wrapper expected_col2( {"This", "bc", "cd", "ef", "is", "cudf", "jk", "test", "column", "pq"}, {1, 1, 0, 1, 0, 0, 1, 1, 0, 0}); auto source_table = cudf::table_view({source_col1, source_col2}); auto target_table = cudf::table_view({target_col1, target_col2}); auto expected_table = cudf::table_view({expected_col1, expected_col2}); auto got = cudf::boolean_mask_scatter(source_table, target_table, mask); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_table, got->view()); } class BooleanMaskScatterString : public cudf::test::BaseFixture {}; TEST_F(BooleanMaskScatterString, NoNUll) { cudf::test::strings_column_wrapper source({"This", "cudf"}); cudf::test::strings_column_wrapper target({"is", "is", "a", "udf", "api"}); cudf::test::fixed_width_column_wrapper<bool> mask({true, false, false, true, false}); cudf::test::strings_column_wrapper expected({"This", "is", "a", "cudf", "api"}); auto source_table = cudf::table_view({source}); auto target_table = cudf::table_view({target}); auto expected_table = cudf::table_view({expected}); auto got = cudf::boolean_mask_scatter(source_table, target_table, mask); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_table, got->view()); } TEST_F(BooleanMaskScatterString, WithNUll) { cudf::test::strings_column_wrapper source({"This", "cudf"}, {0, 1}); cudf::test::strings_column_wrapper target({"is", "is", "a", "udf", "api"}, {1, 0, 0, 1, 1}); cudf::test::fixed_width_column_wrapper<bool> mask({true, false, false, true, false}); cudf::test::strings_column_wrapper expected({"This", "is", "a", "cudf", "api"}, {0, 0, 0, 1, 1}); auto source_table = cudf::table_view({source}); auto target_table = cudf::table_view({target}); auto expected_table = cudf::table_view({expected}); auto got = cudf::boolean_mask_scatter(source_table, target_table, mask); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_table, got->view()); } class BooleanMaskScatterFails : public cudf::test::BaseFixture {}; TEST_F(BooleanMaskScatterFails, SourceAndTargetTypeMismatch) { cudf::test::fixed_width_column_wrapper<int32_t> source({1, 5, 6, 8, 9}); cudf::test::fixed_width_column_wrapper<int64_t> target({2, 2, 3, 4, 11, 12, 7, 7, 10, 10}); cudf::test::fixed_width_column_wrapper<bool> mask( {true, false, false, false, true, true, false, true, true, false}); auto source_table = cudf::table_view({source}); auto target_table = cudf::table_view({target}); EXPECT_THROW(cudf::boolean_mask_scatter(source_table, target_table, mask), cudf::logic_error); } TEST_F(BooleanMaskScatterFails, BooleanMaskTypeMismatch) { cudf::test::fixed_width_column_wrapper<int32_t> source({1, 5, 6, 8, 9}); cudf::test::fixed_width_column_wrapper<int32_t> target({2, 2, 3, 4, 11, 12, 7, 7, 10, 10}); cudf::test::fixed_width_column_wrapper<int8_t> mask( {true, false, false, false, true, true, false, true, true, false}); auto source_table = cudf::table_view({source}); auto target_table = cudf::table_view({target}); EXPECT_THROW(cudf::boolean_mask_scatter(source_table, target_table, mask), cudf::logic_error); } TEST_F(BooleanMaskScatterFails, BooleanMaskTargetSizeMismatch) { cudf::test::fixed_width_column_wrapper<int32_t> source({1, 5, 6, 8, 9}); cudf::test::fixed_width_column_wrapper<int32_t> target({2, 2, 3, 4, 11, 12, 7, 7, 10, 10}); cudf::test::fixed_width_column_wrapper<bool> mask( {true, false, false, false, true, true, false, true, true}); auto source_table = cudf::table_view({source}); auto target_table = cudf::table_view({target}); EXPECT_THROW(cudf::boolean_mask_scatter(source_table, target_table, mask), cudf::logic_error); } TEST_F(BooleanMaskScatterFails, NumberOfColumnMismatch) { cudf::test::fixed_width_column_wrapper<int32_t> source({1, 5, 6, 8, 9}); cudf::test::fixed_width_column_wrapper<int32_t> target({2, 2, 3, 4, 11, 12, 7, 7, 10, 10}); cudf::test::fixed_width_column_wrapper<bool> mask( {true, false, false, false, true, true, false, true, true}); auto source_table = cudf::table_view({source, source}); auto target_table = cudf::table_view({target}); EXPECT_THROW(cudf::boolean_mask_scatter(source_table, target_table, mask), cudf::logic_error); } TEST_F(BooleanMaskScatterFails, MoreTruesInMaskThanSourceSize) { cudf::test::fixed_width_column_wrapper<int32_t> source({1, 5, 6, 8, 9}); cudf::test::fixed_width_column_wrapper<int32_t> target({2, 2, 3, 4, 11, 12, 7, 7, 10, 10}); cudf::test::fixed_width_column_wrapper<bool> mask( {true, false, true, false, true, true, false, true, true}); auto source_table = cudf::table_view({source, source}); auto target_table = cudf::table_view({target}); EXPECT_THROW(cudf::boolean_mask_scatter(source_table, target_table, mask), cudf::logic_error); } template <typename T> struct BooleanMaskScalarScatter : public cudf::test::BaseFixture { std::unique_ptr<cudf::scalar> form_scalar(T value, bool validity = true) { using ScalarType = cudf::scalar_type_t<T>; std::unique_ptr<cudf::scalar> scalar{nullptr}; if (cudf::is_numeric<T>()) { scalar = cudf::make_numeric_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()})); } else if (cudf::is_timestamp<T>()) { scalar = cudf::make_timestamp_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()})); } else if (cudf::is_duration<T>()) { scalar = cudf::make_duration_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<T>()})); } static_cast<ScalarType*>(scalar.get())->set_value(value); static_cast<ScalarType*>(scalar.get())->set_valid_async(validity); return scalar; } }; TYPED_TEST_SUITE(BooleanMaskScalarScatter, cudf::test::FixedWidthTypesWithoutFixedPoint); TYPED_TEST(BooleanMaskScalarScatter, WithNoNullElementsInTarget) { using T = TypeParam; T source = cudf::test::make_type_param_scalar<T>(11); bool validity = true; auto scalar = this->form_scalar(source, validity); std::vector<std::reference_wrapper<const cudf::scalar>> scalar_vect; scalar_vect.push_back(*scalar); cudf::test::fixed_width_column_wrapper<T, int32_t> target({2, 2, 3, 4, 11, 12, 7, 7, 10, 10}); cudf::test::fixed_width_column_wrapper<bool> mask( {true, false, false, false, true, true, false, true, true, false}); cudf::test::fixed_width_column_wrapper<T, int32_t> expected({11, 2, 3, 4, 11, 11, 7, 11, 11, 10}); auto target_table = cudf::table_view({target}); auto expected_table = cudf::table_view({expected}); auto got = cudf::boolean_mask_scatter(scalar_vect, target_table, mask); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_table, got->view()); } TYPED_TEST(BooleanMaskScalarScatter, WithNull) { using T = TypeParam; T source = cudf::test::make_type_param_scalar<T>(11); bool validity = false; auto scalar_1 = this->form_scalar(source, validity); auto scalar_2 = cudf::make_string_scalar("cudf"); scalar_2->set_valid_async(true); std::vector<std::reference_wrapper<const cudf::scalar>> scalar_vect; scalar_vect.push_back(*scalar_1); scalar_vect.push_back(*scalar_2); cudf::test::fixed_width_column_wrapper<T, int32_t> target_col1({2, 2, 3, 4, 11, 12, 7, 7, 10, 10}, {1, 1, 0, 1, 1, 1, 1, 1, 1, 0}); cudf::test::strings_column_wrapper target_col2( {"a", "bc", "cd", "ef", "gh", "ij", "jk", "lm", "no", "pq"}, {1, 1, 0, 1, 1, 1, 1, 1, 1, 0}); cudf::test::fixed_width_column_wrapper<bool> mask( {true, false, false, false, true, true, false, true, true, false}); cudf::test::fixed_width_column_wrapper<T, int32_t> expected_col1( {11, 2, 3, 4, 11, 11, 7, 11, 11, 10}, {0, 1, 0, 1, 0, 0, 1, 0, 0, 0}); cudf::test::strings_column_wrapper expected_col2( {"cudf", "bc", "cd", "ef", "cudf", "cudf", "jk", "cudf", "cudf", "pq"}, {1, 1, 0, 1, 1, 1, 1, 1, 1, 0}); auto target_table = cudf::table_view({target_col1, target_col2}); auto expected_table = cudf::table_view({expected_col1, expected_col2}); auto got = cudf::boolean_mask_scatter(scalar_vect, target_table, mask); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_table, got->view()); } class BooleanMaskScatterScalarString : public cudf::test::BaseFixture {}; TEST_F(BooleanMaskScatterScalarString, NoNUll) { auto scalar = cudf::make_string_scalar("cudf"); scalar->set_valid_async(true); std::vector<std::reference_wrapper<const cudf::scalar>> scalar_vect; scalar_vect.push_back(*scalar); cudf::test::strings_column_wrapper target({"is", "is", "a", "udf", "api"}); cudf::test::fixed_width_column_wrapper<bool> mask({true, false, false, true, false}); cudf::test::strings_column_wrapper expected({"cudf", "is", "a", "cudf", "api"}); auto target_table = cudf::table_view({target}); auto expected_table = cudf::table_view({expected}); auto got = cudf::boolean_mask_scatter(scalar_vect, target_table, mask); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_table, got->view()); } TEST_F(BooleanMaskScatterScalarString, WithNUll) { auto scalar = cudf::make_string_scalar("cudf"); scalar->set_valid_async(true); std::vector<std::reference_wrapper<const cudf::scalar>> scalar_vect; scalar_vect.push_back(*scalar); cudf::test::strings_column_wrapper target({"is", "is", "a", "udf", "api"}, {1, 0, 0, 1, 1}); cudf::test::fixed_width_column_wrapper<bool> mask({true, false, true, true, false}); cudf::test::strings_column_wrapper expected({"cudf", "is", "cudf", "cudf", "api"}, {1, 0, 1, 1, 1}); auto target_table = cudf::table_view({target}); auto expected_table = cudf::table_view({expected}); auto got = cudf::boolean_mask_scatter(scalar_vect, target_table, mask); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_table, got->view()); } class BooleanMaskScatterScalarFails : public cudf::test::BaseFixture {}; TEST_F(BooleanMaskScatterScalarFails, SourceAndTargetTypeMismatch) { auto scalar = cudf::make_numeric_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<int32_t>()})); std::vector<std::reference_wrapper<const cudf::scalar>> scalar_vect; scalar_vect.push_back(*scalar); cudf::test::fixed_width_column_wrapper<int64_t> target({2, 2, 3, 4, 11, 12, 7, 7, 10, 10}); cudf::test::fixed_width_column_wrapper<bool> mask( {true, false, false, false, true, true, false, true, true, false}); auto target_table = cudf::table_view({target}); EXPECT_THROW(cudf::boolean_mask_scatter(scalar_vect, target_table, mask), cudf::logic_error); } TEST_F(BooleanMaskScatterScalarFails, BooleanMaskTypeMismatch) { auto scalar = cudf::make_numeric_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<int32_t>()})); std::vector<std::reference_wrapper<const cudf::scalar>> scalar_vect; scalar_vect.push_back(*scalar); cudf::test::fixed_width_column_wrapper<int32_t> target({2, 2, 3, 4, 11, 12, 7, 7, 10, 10}); cudf::test::fixed_width_column_wrapper<int8_t> mask( {true, false, false, false, true, true, false, true, true, false}); auto target_table = cudf::table_view({target}); EXPECT_THROW(cudf::boolean_mask_scatter(scalar_vect, target_table, mask), cudf::logic_error); } TEST_F(BooleanMaskScatterScalarFails, BooleanMaskTargetSizeMismatch) { auto scalar = cudf::make_numeric_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<int32_t>()})); std::vector<std::reference_wrapper<const cudf::scalar>> scalar_vect; scalar_vect.push_back(*scalar); cudf::test::fixed_width_column_wrapper<int32_t> target({2, 2, 3, 4, 11, 12, 7, 7, 10, 10}); cudf::test::fixed_width_column_wrapper<bool> mask( {true, false, false, false, true, true, false, true, true}); auto target_table = cudf::table_view({target}); EXPECT_THROW(cudf::boolean_mask_scatter(scalar_vect, target_table, mask), cudf::logic_error); } TEST_F(BooleanMaskScatterScalarFails, NumberOfColumnAndScalarMismatch) { auto scalar = cudf::make_numeric_scalar(cudf::data_type(cudf::data_type{cudf::type_to_id<int32_t>()})); std::vector<std::reference_wrapper<const cudf::scalar>> scalar_vect; scalar_vect.push_back(*scalar); scalar_vect.push_back(*scalar); cudf::test::fixed_width_column_wrapper<int32_t> target({2, 2, 3, 4, 11, 12, 7, 7, 10, 10}); cudf::test::fixed_width_column_wrapper<bool> mask( {true, false, false, false, true, true, false, true, true}); auto target_table = cudf::table_view({target}); EXPECT_THROW(cudf::boolean_mask_scatter(scalar_vect, target_table, mask), cudf::logic_error); } template <typename T> struct FixedPointTestAllReps : public cudf::test::BaseFixture {}; template <typename T> using wrapper = cudf::test::fixed_width_column_wrapper<T>; TYPED_TEST_SUITE(FixedPointTestAllReps, cudf::test::FixedPointTypes); TYPED_TEST(FixedPointTestAllReps, FixedPointScatter) { using namespace numeric; using decimalXX = TypeParam; auto const ONE = decimalXX{1, scale_type{0}}; auto const TWO = decimalXX{2, scale_type{0}}; auto const THREE = decimalXX{3, scale_type{0}}; auto const FOUR = decimalXX{4, scale_type{0}}; auto const FIVE = decimalXX{5, scale_type{0}}; auto const source = wrapper<decimalXX>({ONE, TWO, THREE, FOUR, FIVE}); auto const target = wrapper<decimalXX>({ONE, TWO, THREE, FOUR, FIVE, FOUR, THREE, TWO, ONE}); auto const scatter_map = wrapper<int32_t>({1, 2, -1, -3, -4}); auto const expected = wrapper<decimalXX>({ONE, ONE, TWO, FOUR, FIVE, FIVE, FOUR, TWO, THREE}); auto const source_table = cudf::table_view({source, source}); auto const target_table = cudf::table_view({target, target}); auto const expected_table = cudf::table_view({expected, expected}); auto const result = cudf::scatter(source_table, scatter_map, target_table); CUDF_TEST_EXPECT_TABLES_EQUAL(expected_table, result->view()); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/slice_tests.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/column/column_factories.hpp> #include <cudf/copying.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/strings/strings_column_view.hpp> #include <cudf/utilities/type_dispatcher.hpp> #include <cudf/wrappers/timestamps.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <tests/copying/slice_tests.cuh> #include <string> #include <vector> template <typename T> struct SliceTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(SliceTest, cudf::test::NumericTypes); TYPED_TEST(SliceTest, NumericColumnsWithNulls) { using T = TypeParam; cudf::size_type start = 0; cudf::size_type size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::test::fixed_width_column_wrapper<T> col = create_fixed_columns<T>(start, size, valids); std::vector<cudf::size_type> indices{1, 3, 2, 2, 5, 9}; std::vector<cudf::test::fixed_width_column_wrapper<T>> expected = create_expected_columns<T>(indices, true); std::vector<cudf::column_view> result = cudf::slice(col, indices); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected[index], result[index]); } } TYPED_TEST(SliceTest, NumericColumnsWithNullsAsColumn) { using T = TypeParam; cudf::size_type start = 0; cudf::size_type size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::test::fixed_width_column_wrapper<T> input = create_fixed_columns<T>(start, size, valids); std::vector<cudf::size_type> indices{1, 3, 2, 2, 5, 9}; std::vector<cudf::test::fixed_width_column_wrapper<T>> expected = create_expected_columns<T>(indices, true); std::vector<cudf::column_view> result = cudf::slice(input, indices); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { auto col = cudf::column(result[index]); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected[index], col); } } struct SliceStringTest : public SliceTest<std::string> {}; TEST_F(SliceStringTest, StringWithNulls) { std::vector<std::string> strings{ "", "this", "is", "a", "column", "of", "strings", "with", "in", "valid"}; auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); cudf::test::strings_column_wrapper s(strings.begin(), strings.end(), valids); std::vector<cudf::size_type> indices{1, 3, 2, 4, 1, 9}; std::vector<cudf::test::strings_column_wrapper> expected = create_expected_string_columns(strings, indices, true); std::vector<cudf::column_view> result = cudf::slice(s, indices); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected[index], result[index]); } } TEST_F(SliceStringTest, StringWithNullsAsColumn) { std::vector<std::string> strings{ "", "this", "is", "a", "column", "of", "strings", "with", "in", "valid"}; auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); cudf::test::strings_column_wrapper s(strings.begin(), strings.end(), valids); std::vector<cudf::size_type> indices{1, 3, 2, 4, 1, 9}; std::vector<cudf::test::strings_column_wrapper> expected = create_expected_string_columns(strings, indices, true); std::vector<cudf::column_view> result = cudf::slice(s, indices); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { // this materializes a column to test slicing + materialization auto result_col = cudf::column(result[index]); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected[index], result_col); } } struct SliceListTest : public SliceTest<int> {}; TEST_F(SliceListTest, Lists) { using LCW = cudf::test::lists_column_wrapper<int>; { cudf::test::lists_column_wrapper<int> list{{1, 2, 3}, {4, 5}, {6}, {7, 8}, {9, 10, 11}, LCW{}, LCW{}, {-1, -2, -3, -4, -5}, {-10}, {-100, -200}}; std::vector<cudf::size_type> indices{1, 3, 2, 4, 1, 9}; std::vector<cudf::test::lists_column_wrapper<int>> expected; expected.push_back(LCW{{4, 5}, {6}}); expected.push_back(LCW{{6}, {7, 8}}); expected.push_back( LCW{{4, 5}, {6}, {7, 8}, {9, 10, 11}, LCW{}, LCW{}, {-1, -2, -3, -4, -5}, {-10}}); std::vector<cudf::column_view> result = cudf::slice(list, indices); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected[index], result[index]); } } { cudf::test::lists_column_wrapper<int> list{{{1, 2, 3}, {4, 5}}, {LCW{}, LCW{}, {7, 8}, LCW{}}, {{{6}}}, {{7, 8}, {9, 10, 11}, LCW{}}, {LCW{}, {-1, -2, -3, -4, -5}}, {LCW{}}, {{-10}, {-100, -200}}}; std::vector<cudf::size_type> indices{1, 3, 3, 6}; std::vector<cudf::test::lists_column_wrapper<int>> expected; expected.push_back(LCW{{LCW{}, LCW{}, {7, 8}, LCW{}}, {{{6}}}}); expected.push_back(LCW{{{7, 8}, {9, 10, 11}, LCW{}}, {LCW{}, {-1, -2, -3, -4, -5}}, {LCW{}}}); std::vector<cudf::column_view> result = cudf::slice(list, indices); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected[index], result[index]); } } } TEST_F(SliceListTest, ListsWithNulls) { using LCW = cudf::test::lists_column_wrapper<int>; auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); { cudf::test::lists_column_wrapper<int> list{{1, 2, 3}, {4, 5}, {6}, {{7, 8}, valids}, {9, 10, 11}, LCW{}, LCW{}, {{-1, -2, -3, -4, -5}, valids}, {-10}, {{-100, -200}, valids}}; std::vector<cudf::size_type> indices{1, 3, 2, 4, 1, 9}; std::vector<cudf::test::lists_column_wrapper<int>> expected; expected.push_back(LCW{{4, 5}, {6}}); expected.push_back(LCW{{6}, {{7, 8}, valids}}); expected.push_back(LCW{{4, 5}, {6}, {{7, 8}, valids}, {9, 10, 11}, LCW{}, LCW{}, {{-1, -2, -3, -4, -5}, valids}, {-10}}); std::vector<cudf::column_view> result = cudf::slice(list, indices); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected[index], result[index]); } } { cudf::test::lists_column_wrapper<int> list{{{{1, 2, 3}, valids}, {4, 5}}, {{LCW{}, LCW{}, {7, 8}, LCW{}}, valids}, {{{6}}}, {{{7, 8}, {{9, 10, 11}, valids}, LCW{}}, valids}, {{LCW{}, {-1, -2, -3, -4, -5}}, valids}, {LCW{}}, {{-10}, {-100, -200}}}; std::vector<cudf::size_type> indices{1, 3, 3, 6}; std::vector<cudf::test::lists_column_wrapper<int>> expected; expected.push_back(LCW{{{LCW{}, LCW{}, {7, 8}, LCW{}}, valids}, {{{6}}}}); expected.push_back(LCW{{{{7, 8}, {{9, 10, 11}, valids}, LCW{}}, valids}, {{LCW{}, {-1, -2, -3, -4, -5}}, valids}, {LCW{}}}); std::vector<cudf::column_view> result = cudf::slice(list, indices); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected[index], result[index]); } } } struct SliceCornerCases : public SliceTest<int8_t> {}; TEST_F(SliceCornerCases, EmptyColumn) { cudf::column col{}; std::vector<cudf::size_type> indices{0, 0, 0, 0, 0, 0}; std::vector<cudf::column_view> result = cudf::slice(col.view(), indices); unsigned long expected = 3; EXPECT_EQ(expected, result.size()); auto type_match_count = std::count_if(result.cbegin(), result.cend(), [](auto const& col) { return col.type().id() == cudf::type_id::EMPTY; }); EXPECT_EQ(static_cast<std::size_t>(type_match_count), expected); } TEST_F(SliceCornerCases, EmptyIndices) { cudf::size_type start = 0; cudf::size_type size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::test::fixed_width_column_wrapper<int8_t> col = create_fixed_columns<int8_t>(start, size, valids); std::vector<cudf::size_type> indices{}; std::vector<cudf::column_view> result = cudf::slice(col, indices); unsigned long expected = 0; EXPECT_EQ(expected, result.size()); } TEST_F(SliceCornerCases, InvalidSetOfIndices) { cudf::size_type start = 0; cudf::size_type size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::test::fixed_width_column_wrapper<int8_t> col = create_fixed_columns<int8_t>(start, size, valids); std::vector<cudf::size_type> indices{11, 12}; EXPECT_THROW(cudf::slice(col, indices), cudf::logic_error); } TEST_F(SliceCornerCases, ImproperRange) { cudf::size_type start = 0; cudf::size_type size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::test::fixed_width_column_wrapper<int8_t> col = create_fixed_columns<int8_t>(start, size, valids); std::vector<cudf::size_type> indices{5, 4}; EXPECT_THROW(cudf::slice(col, indices), cudf::logic_error); } TEST_F(SliceCornerCases, NegativeOffset) { cudf::size_type start = 0; cudf::size_type size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::test::fixed_width_column_wrapper<int8_t> col = create_fixed_columns<int8_t>(start, size, valids); std::vector<cudf::size_type> indices{-1, 4}; EXPECT_THROW(cudf::slice(col, indices), cudf::logic_error); } template <typename T> struct SliceTableTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(SliceTableTest, cudf::test::NumericTypes); TYPED_TEST(SliceTableTest, NumericColumnsWithNulls) { using T = TypeParam; cudf::size_type start = 0; cudf::size_type col_size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::size_type num_cols = 5; cudf::table src_table = create_fixed_table<T>(num_cols, start, col_size, valids); std::vector<cudf::size_type> indices{1, 3, 2, 2, 5, 9}; std::vector<cudf::table> expected = create_expected_tables<T>(num_cols, indices, true); std::vector<cudf::table_view> result = cudf::slice(src_table, indices); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { CUDF_TEST_EXPECT_TABLES_EQUAL(expected[index], result[index]); } } struct SliceStringTableTest : public SliceTableTest<std::string> {}; TEST_F(SliceStringTableTest, StringWithNulls) { auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); std::vector<std::string> strings[2] = { {"", "this", "is", "a", "column", "of", "strings", "with", "in", "valid"}, {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}}; cudf::test::strings_column_wrapper sw[2] = {{strings[0].begin(), strings[0].end(), valids}, {strings[1].begin(), strings[1].end(), valids}}; std::vector<std::unique_ptr<cudf::column>> scols; scols.push_back(sw[0].release()); scols.push_back(sw[1].release()); cudf::table src_table(std::move(scols)); std::vector<cudf::size_type> indices{1, 3, 2, 4, 1, 9}; std::vector<cudf::table> expected = create_expected_string_tables(strings, indices, true); std::vector<cudf::table_view> result = cudf::slice(src_table, indices); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { CUDF_TEST_EXPECT_TABLE_PROPERTIES_EQUAL(expected[index], result[index]); } } struct SliceTableCornerCases : public SliceTableTest<int8_t> {}; TEST_F(SliceTableCornerCases, EmptyTable) { std::vector<cudf::size_type> indices{1, 3, 2, 4, 5, 9}; cudf::table src_table{}; std::vector<cudf::table_view> result = cudf::slice(src_table.view(), indices); unsigned long expected = 3; EXPECT_EQ(expected, result.size()); } TEST_F(SliceTableCornerCases, EmptyIndices) { cudf::size_type start = 0; cudf::size_type col_size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::size_type num_cols = 5; cudf::table src_table = create_fixed_table<int8_t>(num_cols, start, col_size, valids); std::vector<cudf::size_type> indices{}; std::vector<cudf::table_view> result = cudf::slice(src_table, indices); unsigned long expected = 0; EXPECT_EQ(expected, result.size()); } TEST_F(SliceTableCornerCases, InvalidSetOfIndices) { cudf::size_type start = 0; cudf::size_type col_size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::size_type num_cols = 5; cudf::table src_table = create_fixed_table<int8_t>(num_cols, start, col_size, valids); std::vector<cudf::size_type> indices{11, 12}; EXPECT_THROW(cudf::slice(src_table, indices), cudf::logic_error); } TEST_F(SliceTableCornerCases, ImproperRange) { cudf::size_type start = 0; cudf::size_type col_size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::size_type num_cols = 5; cudf::table src_table = create_fixed_table<int8_t>(num_cols, start, col_size, valids); std::vector<cudf::size_type> indices{5, 4}; EXPECT_THROW(cudf::slice(src_table, indices), cudf::logic_error); } TEST_F(SliceTableCornerCases, NegativeOffset) { cudf::size_type start = 0; cudf::size_type col_size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::size_type num_cols = 5; cudf::table src_table = create_fixed_table<int8_t>(num_cols, start, col_size, valids); std::vector<cudf::size_type> indices{-1, 4}; EXPECT_THROW(cudf::slice(src_table, indices), cudf::logic_error); } TEST_F(SliceTableCornerCases, MiscOffset) { cudf::test::fixed_width_column_wrapper<int32_t> col2{ {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0}}; cudf::test::fixed_width_column_wrapper<int32_t> col3{ {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0}}; std::vector<cudf::size_type> indices{19, 38}; std::vector<cudf::column_view> result = cudf::slice(col2, indices); cudf::column result_column(result[0]); CUDF_TEST_EXPECT_COLUMNS_EQUAL(col3, result_column); } TEST_F(SliceTableCornerCases, PreSlicedInputs) { { using LCW = cudf::test::lists_column_wrapper<float>; cudf::test::fixed_width_column_wrapper<int> a{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 0, 1, 1, 1, 0, 0, 1, 0}}; cudf::test::fixed_width_column_wrapper<int> b{{0, -1, -2, -3, -4, -5, -6, -7, -8, -9}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}; cudf::test::strings_column_wrapper c{{"aa", "b", "", "ccc", "ddd", "e", "ff", "", "", "gggg"}, {0, 0, 1, 1, 0, 0, 1, 1, 1, 0}}; std::vector<bool> list_validity{1, 0, 1, 0, 1, 1, 0, 0, 1, 1}; cudf::test::lists_column_wrapper<float> d{ {{0, 1}, {2}, {3, 4, 5}, {6}, {7, 7}, {8, 9}, {10, 11}, {12, 13}, {}, {14, 15, 16}}, list_validity.begin()}; cudf::table_view t({a, b, c, d}); auto pre_sliced = cudf::slice(t, {0, 4, 4, 10}); auto result = cudf::slice(pre_sliced[1], {0, 1, 1, 6}); cudf::test::fixed_width_column_wrapper<int> e0_a({4}, {1}); cudf::test::fixed_width_column_wrapper<int> e0_b({-4}, {0}); cudf::test::strings_column_wrapper e0_c({""}, {0}); std::vector<bool> e0_list_validity{1}; cudf::test::lists_column_wrapper<float> e0_d({LCW{7, 7}}, e0_list_validity.begin()); cudf::table_view expected0({e0_a, e0_b, e0_c, e0_d}); CUDF_TEST_EXPECT_TABLES_EQUAL(result[0], expected0); cudf::test::fixed_width_column_wrapper<int> e1_a{{5, 6, 7, 8, 9}, {1, 0, 0, 1, 0}}; cudf::test::fixed_width_column_wrapper<int> e1_b{{-5, -6, -7, -8, -9}, {0, 0, 0, 0, 0}}; cudf::test::strings_column_wrapper e1_c{{"e", "ff", "", "", "gggg"}, {0, 1, 1, 1, 0}}; std::vector<bool> e1_list_validity{1, 0, 0, 1, 1}; cudf::test::lists_column_wrapper<float> e1_d{{{8, 9}, {10, 11}, {12, 13}, {}, {14, 15, 16}}, e1_list_validity.begin()}; cudf::table_view expected1({e1_a, e1_b, e1_c, e1_d}); CUDF_TEST_EXPECT_TABLES_EQUAL(result[1], expected1); } }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/scatter_struct_scalar_tests.cpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/column/column_factories.hpp> #include <cudf/copying.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/scalar/scalar_factories.hpp> constexpr cudf::test::debug_output_level verbosity{cudf::test::debug_output_level::ALL_ERRORS}; constexpr int32_t null{0}; // Mark for null child elements constexpr int32_t XXX{0}; // Mark for null struct elements using structs_col = cudf::test::structs_column_wrapper; template <typename T> struct TypedStructScalarScatterTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(TypedStructScalarScatterTest, cudf::test::FixedWidthTypes); cudf::column scatter_single_scalar(cudf::scalar const& slr, cudf::column_view scatter_map, cudf::column_view target) { auto result = cudf::scatter({slr}, scatter_map, cudf::table_view{{target}}); return result->get_column(0); } TYPED_TEST(TypedStructScalarScatterTest, Basic) { using fixed_width_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; // Source scalar fixed_width_wrapper slr_f0{777}; cudf::test::strings_column_wrapper slr_f1{"hello"}; auto slr = cudf::make_struct_scalar(cudf::table_view{{slr_f0, slr_f1}}); // Scatter map cudf::test::fixed_width_column_wrapper<cudf::size_type> scatter_map{2}; // Target column fixed_width_wrapper field0{11, 11, 22, 22, 33}; cudf::test::strings_column_wrapper field1{"aa", "aa", "bb", "bb", "cc"}; structs_col target{field0, field1}; // Expect column fixed_width_wrapper ef0{11, 11, 777, 22, 33}; cudf::test::strings_column_wrapper ef1{"aa", "aa", "hello", "bb", "cc"}; structs_col expected{ef0, ef1}; auto got = scatter_single_scalar(*slr, scatter_map, target); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, got, verbosity); } TYPED_TEST(TypedStructScalarScatterTest, FillNulls) { using fixed_width_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; // Source scalar fixed_width_wrapper slr_f0{777}; auto slr = cudf::make_struct_scalar(cudf::table_view{{slr_f0}}); // Scatter map cudf::test::fixed_width_column_wrapper<cudf::size_type> scatter_map{3, 4}; // Target column fixed_width_wrapper field0({11, 11, 22, null, XXX}, cudf::test::iterators::null_at(3)); structs_col target({field0}, cudf::test::iterators::null_at(4)); // Expect column fixed_width_wrapper ef0{11, 11, 22, 777, 777}; structs_col expected{ef0}; auto got = scatter_single_scalar(*slr, scatter_map, target); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, got, verbosity); } TYPED_TEST(TypedStructScalarScatterTest, ScatterNullElements) { using fixed_width_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; // Source scalar fixed_width_wrapper slr_f0{777}; std::vector<cudf::column_view> source_fields{slr_f0}; auto slr = std::make_unique<cudf::struct_scalar>(source_fields, false); // Scatter map cudf::test::fixed_width_column_wrapper<cudf::size_type> scatter_map{0, 3, 4}; // Target column fixed_width_wrapper field0({11, 11, 22, null, XXX}, cudf::test::iterators::null_at(3)); structs_col target({field0}, cudf::test::iterators::null_at(4)); // Expect column fixed_width_wrapper ef0{XXX, 11, 22, XXX, XXX}; structs_col expected({ef0}, {false, true, true, false, false}); auto got = scatter_single_scalar(*slr, scatter_map, target); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, got, verbosity); } TYPED_TEST(TypedStructScalarScatterTest, ScatterNullFields) { using fixed_width_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; // Source scalar fixed_width_wrapper slr_f0({null}, {false}); auto slr = cudf::make_struct_scalar(cudf::table_view{{slr_f0}}); // Scatter map cudf::test::fixed_width_column_wrapper<cudf::size_type> scatter_map{0, 2}; // Target column fixed_width_wrapper field0({11, 11, 22, null, XXX}, cudf::test::iterators::null_at(3)); structs_col target({field0}, cudf::test::iterators::null_at(4)); // Expect column fixed_width_wrapper ef0({null, 11, null, null, XXX}, {false, true, false, false, true}); structs_col expected({ef0}, cudf::test::iterators::null_at(4)); auto got = scatter_single_scalar(*slr, scatter_map, target); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, got, verbosity); } TYPED_TEST(TypedStructScalarScatterTest, NegativeIndices) { using fixed_width_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; // Source scalar fixed_width_wrapper slr_f0{777}; auto slr = cudf::make_struct_scalar(cudf::table_view{{slr_f0}}); // Scatter map cudf::test::fixed_width_column_wrapper<cudf::size_type> scatter_map{-1, -5}; // Target column fixed_width_wrapper field0({11, 11, 22, null, XXX}, cudf::test::iterators::null_at(3)); structs_col target({field0}, cudf::test::iterators::null_at(4)); // Expect column fixed_width_wrapper ef0({777, 11, 22, null, 777}, cudf::test::iterators::null_at(3)); structs_col expected{ef0}; auto got = scatter_single_scalar(*slr, scatter_map, target); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, got, verbosity); } TYPED_TEST(TypedStructScalarScatterTest, EmptyInputTest) { using fixed_width_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; // Source scalar fixed_width_wrapper slr_f0{777}; auto slr = cudf::make_struct_scalar(cudf::table_view{{slr_f0}}); // Scatter map cudf::test::fixed_width_column_wrapper<cudf::size_type> scatter_map{}; // Target column fixed_width_wrapper field0{}; structs_col target{field0}; // Expect column fixed_width_wrapper ef0{}; structs_col expected{ef0}; auto got = scatter_single_scalar(*slr, scatter_map, target); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, got, verbosity); } TYPED_TEST(TypedStructScalarScatterTest, EmptyScatterMapTest) { using fixed_width_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; // Source scalar fixed_width_wrapper slr_f0{777}; auto slr = cudf::make_struct_scalar(cudf::table_view{{slr_f0}}); // Scatter map cudf::test::fixed_width_column_wrapper<cudf::size_type> scatter_map{}; // Target column fixed_width_wrapper field0({11, 11, 22, null, XXX}, cudf::test::iterators::null_at(3)); structs_col target({field0}, cudf::test::iterators::null_at(4)); auto got = scatter_single_scalar(*slr, scatter_map, target); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(target, got, verbosity); } TYPED_TEST(TypedStructScalarScatterTest, FixedWidthStringTypes) { using fixed_width_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; // Source scalar fixed_width_wrapper slr_f0{777}; cudf::test::strings_column_wrapper slr_f1{"hello"}; auto slr = cudf::make_struct_scalar(cudf::table_view{{slr_f0, slr_f1}}); // Scatter map cudf::test::fixed_width_column_wrapper<cudf::size_type> scatter_map{0, 2, 4}; // Target column fixed_width_wrapper field0({11, 11, 22, null, XXX}, cudf::test::iterators::null_at(3)); cudf::test::strings_column_wrapper field1({"aa", "null", "ccc", "null", "XXX"}, {true, false, true, false, true}); structs_col target({field0, field1}, cudf::test::iterators::null_at(4)); // Expect column fixed_width_wrapper ef0({777, 11, 777, null, 777}, cudf::test::iterators::null_at(3)); cudf::test::strings_column_wrapper ef1({"hello", "null", "hello", "null", "hello"}, {true, false, true, false, true}); structs_col expected{ef0, ef1}; auto got = scatter_single_scalar(*slr, scatter_map, target); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, got, verbosity); } TYPED_TEST(TypedStructScalarScatterTest, StructOfLists) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; // Source scalar LCW slr_f0{777}; auto slr = cudf::make_struct_scalar(cudf::table_view{{slr_f0}}); // Scatter map cudf::test::fixed_width_column_wrapper<cudf::size_type> scatter_map{0, 1, 4}; // Target column LCW field0({LCW{XXX}, LCW{22}, LCW{33, 44}, LCW{null}, LCW{55}}, cudf::test::iterators::null_at(3)); structs_col target({field0}, cudf::test::iterators::null_at(0)); // Expect column LCW ef0({LCW{777}, LCW{777}, LCW{33, 44}, LCW{null}, LCW{777}}, cudf::test::iterators::null_at(3)); structs_col expected{ef0}; auto got = scatter_single_scalar(*slr, scatter_map, target); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, got, verbosity); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/scatter_list_scalar_tests.cpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/column/column_factories.hpp> #include <cudf/null_mask.hpp> #include <cudf/scalar/scalar_factories.hpp> using mask_vector = std::vector<cudf::valid_type>; using size_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>; class ScatterListScalarTests : public cudf::test::BaseFixture {}; std::unique_ptr<cudf::column> single_scalar_scatter(cudf::column_view const& target, cudf::scalar const& slr, cudf::column_view const& scatter_map) { std::vector<std::reference_wrapper<const cudf::scalar>> slrs{slr}; cudf::table_view targets{{target}}; auto result = cudf::scatter(slrs, scatter_map, targets); return std::move(result->release()[0]); } template <typename T> class ScatterListOfFixedWidthScalarTest : public ScatterListScalarTests {}; TYPED_TEST_SUITE(ScatterListOfFixedWidthScalarTest, cudf::test::FixedWidthTypesWithoutFixedPoint); // Test grid // Dim1 : {Fixed width, strings, lists, structs} // Dim2 : {Null scalar, Non-null empty scalar, Non-null non-empty scalar} // Dim3 : {Nullable target, non-nullable target row} TYPED_TEST(ScatterListOfFixedWidthScalarTest, Basic) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; using FCW = cudf::test::fixed_width_column_wrapper<TypeParam>; auto slr = std::make_unique<cudf::list_scalar>(FCW({2, 2, 2}, {1, 0, 1}), true); LCW col{LCW{1, 1, 1}, LCW{8, 8}, LCW{10, 10, 10, 10}, LCW{5}}; size_column scatter_map{3, 1, 0}; LCW expected{LCW({2, 2, 2}, mask_vector{1, 0, 1}.begin()), LCW({2, 2, 2}, mask_vector{1, 0, 1}.begin()), LCW{10, 10, 10, 10}, LCW({2, 2, 2}, mask_vector{1, 0, 1}.begin())}; auto result = single_scalar_scatter(col, *slr, scatter_map); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } TYPED_TEST(ScatterListOfFixedWidthScalarTest, EmptyValidScalar) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; using FCW = cudf::test::fixed_width_column_wrapper<TypeParam>; auto slr = std::make_unique<cudf::list_scalar>(FCW{}, true); LCW col{LCW{1, 1, 1}, LCW{8, 8}, LCW({10, 10, 10, 10}, mask_vector{1, 0, 1, 0}.begin()), LCW{5}, LCW{42, 42}}; size_column scatter_map{1, 0}; LCW expected{ LCW{}, LCW{}, LCW({10, 10, 10, 10}, mask_vector{1, 0, 1, 0}.begin()), LCW{5}, LCW{42, 42}}; auto result = single_scalar_scatter(col, *slr, scatter_map); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } TYPED_TEST(ScatterListOfFixedWidthScalarTest, NullScalar) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; using FCW = cudf::test::fixed_width_column_wrapper<TypeParam>; auto slr = std::make_unique<cudf::list_scalar>(FCW{}, false); LCW col{LCW({1, 1, 1}, mask_vector{0, 0, 1}.begin()), LCW{8, 8}, LCW{10, 10, 10, 10}, LCW{5}}; size_column scatter_map{3, 1}; LCW expected({LCW({1, 1, 1}, mask_vector{0, 0, 1}.begin()), LCW{}, LCW{10, 10, 10, 10}, LCW{}}, mask_vector{1, 0, 1, 0}.begin()); auto result = single_scalar_scatter(col, *slr, scatter_map); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } TYPED_TEST(ScatterListOfFixedWidthScalarTest, NullableTargetRow) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; using FCW = cudf::test::fixed_width_column_wrapper<TypeParam>; auto slr = std::make_unique<cudf::list_scalar>(FCW{9, 9}, true); LCW col({LCW{4, 4}, LCW{}, LCW{8, 8, 8}, LCW{}, LCW{9, 9, 9}}, mask_vector{1, 0, 1, 0, 1}.begin()); size_column scatter_map{0, 1}; LCW expected({LCW{9, 9}, LCW{9, 9}, LCW{8, 8, 8}, LCW{}, LCW{9, 9, 9}}, mask_vector{1, 1, 1, 0, 1}.begin()); auto result = single_scalar_scatter(col, *slr, scatter_map); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } class ScatterListOfStringScalarTest : public ScatterListScalarTests {}; TEST_F(ScatterListOfStringScalarTest, Basic) { using LCW = cudf::test::lists_column_wrapper<cudf::string_view, int32_t>; using StringCW = cudf::test::strings_column_wrapper; auto slr = std::make_unique<cudf::list_scalar>( StringCW({"Hello!", "", "你好!", "صباح الخير!", "", "こんにちは!"}, {true, false, true, true, false, true}), true); LCW col{LCW({"xx", "yy"}, mask_vector{0, 1}.begin()), LCW{""}, LCW{"a", "bab", "bacab"}}; size_column scatter_map{2, 1}; LCW expected{LCW({"xx", "yy"}, mask_vector{0, 1}.begin()), LCW({"Hello!", "", "你好!", "صباح الخير!", "", "こんにちは!"}, mask_vector{1, 0, 1, 1, 0, 1}.begin()), LCW({"Hello!", "", "你好!", "صباح الخير!", "", "こんにちは!"}, mask_vector{1, 0, 1, 1, 0, 1}.begin())}; auto result = single_scalar_scatter(col, *slr, scatter_map); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } TEST_F(ScatterListOfStringScalarTest, EmptyValidScalar) { using LCW = cudf::test::lists_column_wrapper<cudf::string_view, int32_t>; using StringCW = cudf::test::strings_column_wrapper; auto slr = std::make_unique<cudf::list_scalar>(StringCW{}, true); LCW col{LCW({"xx", "yy"}, mask_vector{0, 1}.begin()), LCW{""}, LCW{"a", "bab", "bacab"}, LCW{"888", "777"}}; size_column scatter_map{0, 3}; LCW expected{LCW{}, LCW{""}, LCW{"a", "bab", "bacab"}, LCW{}}; auto result = single_scalar_scatter(col, *slr, scatter_map); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } TEST_F(ScatterListOfStringScalarTest, NullScalar) { using LCW = cudf::test::lists_column_wrapper<cudf::string_view, int32_t>; using StringCW = cudf::test::strings_column_wrapper; auto slr = std::make_unique<cudf::list_scalar>(StringCW{}, false); LCW col{LCW{"xx", "yy"}, LCW({""}, mask_vector{0}.begin()), LCW{"a", "bab", "bacab"}, LCW{"888", "777"}}; size_column scatter_map{1, 2}; LCW expected({LCW{"xx", "yy"}, LCW{}, LCW{}, LCW{"888", "777"}}, mask_vector{1, 0, 0, 1}.begin()); auto result = single_scalar_scatter(col, *slr, scatter_map); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } TEST_F(ScatterListOfStringScalarTest, NullableTargetRow) { using LCW = cudf::test::lists_column_wrapper<cudf::string_view, int32_t>; using StringCW = cudf::test::strings_column_wrapper; auto slr = std::make_unique<cudf::list_scalar>( StringCW({"Hello!", "", "こんにちは!"}, {true, false, true}), true); LCW col({LCW{"xx", "yy"}, LCW({""}, mask_vector{0}.begin()), LCW{}, LCW{"888", "777"}}, mask_vector{1, 1, 0, 1}.begin()); size_column scatter_map{3, 2}; LCW expected({LCW{"xx", "yy"}, LCW({""}, mask_vector{0}.begin()), LCW({"Hello!", "", "こんにちは!"}, mask_vector{1, 0, 1}.begin()), LCW({"Hello!", "", "こんにちは!"}, mask_vector{1, 0, 1}.begin())}, mask_vector{1, 1, 1, 1}.begin()); auto result = single_scalar_scatter(col, *slr, scatter_map); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } template <typename T> class ScatterListOfListScalarTest : public ScatterListScalarTests {}; TYPED_TEST_SUITE(ScatterListOfListScalarTest, cudf::test::FixedWidthTypesWithoutFixedPoint); TYPED_TEST(ScatterListOfListScalarTest, Basic) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; auto slr = std::make_unique<cudf::list_scalar>( LCW({LCW{1, 2, 3}, LCW{4}, LCW{}, LCW{5, 6}}, mask_vector{1, 1, 0, 1}.begin()), true); LCW col({LCW({LCW{88, 88}, LCW{}, LCW{9, 9, 9}}, mask_vector{1, 0, 1}.begin()), LCW{LCW{66}, LCW{}, LCW({77, 77, 77, 77}, mask_vector{1, 0, 0, 1}.begin())}, LCW{LCW{55, 55}, LCW{}, LCW{10, 10, 10}}, LCW{LCW{44, 44}}}); size_column scatter_map{1, 2, 3}; LCW expected({LCW({LCW{88, 88}, LCW{}, LCW{9, 9, 9}}, mask_vector{1, 0, 1}.begin()), LCW({LCW{1, 2, 3}, LCW{4}, LCW{}, LCW{5, 6}}, mask_vector{1, 1, 0, 1}.begin()), LCW({LCW{1, 2, 3}, LCW{4}, LCW{}, LCW{5, 6}}, mask_vector{1, 1, 0, 1}.begin()), LCW({LCW{1, 2, 3}, LCW{4}, LCW{}, LCW{5, 6}}, mask_vector{1, 1, 0, 1}.begin())}); auto result = single_scalar_scatter(col, *slr, scatter_map); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } TYPED_TEST(ScatterListOfListScalarTest, EmptyValidScalar) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; auto slr = std::make_unique<cudf::list_scalar>(LCW{}, true); LCW col({LCW({LCW{88, 88}, LCW{}, LCW{9, 9, 9}}, mask_vector{1, 0, 1}.begin()), LCW{LCW{66}, LCW{}, LCW({77, 77, 77, 77}, mask_vector{1, 0, 0, 1}.begin())}, LCW{LCW{55, 55}, LCW{}, LCW{10, 10, 10}}, LCW{LCW{44, 44}}}); size_column scatter_map{3, 0}; LCW expected({LCW{}, LCW{LCW{66}, LCW{}, LCW({77, 77, 77, 77}, mask_vector{1, 0, 0, 1}.begin())}, LCW{LCW{55, 55}, LCW{}, LCW{10, 10, 10}}, LCW{}}); auto result = single_scalar_scatter(col, *slr, scatter_map); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } TYPED_TEST(ScatterListOfListScalarTest, NullScalar) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; auto slr = std::make_unique<cudf::list_scalar>(LCW{}, false); LCW col({LCW({LCW{88, 88}, LCW{}, LCW{9, 9, 9}}, mask_vector{1, 0, 1}.begin()), LCW{LCW{66}, LCW{}, LCW({77, 77, 77, 77}, mask_vector{1, 0, 0, 1}.begin())}, LCW{LCW{44, 44}}}); size_column scatter_map{1, 0}; LCW expected({LCW{}, LCW{}, LCW{LCW{44, 44}}}, mask_vector{0, 0, 1}.begin()); auto result = single_scalar_scatter(col, *slr, scatter_map); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } TYPED_TEST(ScatterListOfListScalarTest, NullableTargetRows) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; auto slr = std::make_unique<cudf::list_scalar>( LCW({LCW{1, 1, 1}, LCW{3, 3}, LCW{}, LCW{4}}, mask_vector{1, 1, 0, 1}.begin()), true); LCW col({LCW({LCW{88, 88}, LCW{}, LCW{9, 9, 9}}, mask_vector{1, 0, 1}.begin()), LCW{LCW{66}, LCW{}, LCW({77, 77, 77, 77}, mask_vector{1, 0, 0, 1}.begin())}, LCW{LCW{44, 44}}}, mask_vector{1, 0, 1}.begin()); size_column scatter_map{1}; LCW expected({LCW({LCW{88, 88}, LCW{}, LCW{9, 9, 9}}, mask_vector{1, 0, 1}.begin()), LCW({LCW{1, 1, 1}, LCW{3, 3}, LCW{}, LCW{4}}, mask_vector{1, 1, 0, 1}.begin()), LCW{LCW{44, 44}}}, mask_vector{1, 1, 1}.begin()); auto result = single_scalar_scatter(col, *slr, scatter_map); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } template <typename T> class ScatterListOfStructScalarTest : public ScatterListScalarTests { protected: cudf::test::structs_column_wrapper make_test_structs( cudf::test::fixed_width_column_wrapper<T> field0, cudf::test::strings_column_wrapper field1, cudf::test::lists_column_wrapper<T, int32_t> field2, std::vector<cudf::valid_type> mask) { return cudf::test::structs_column_wrapper({field0, field1, field2}, mask.begin()); } }; TYPED_TEST_SUITE(ScatterListOfStructScalarTest, cudf::test::FixedWidthTypesWithoutFixedPoint); TYPED_TEST(ScatterListOfStructScalarTest, Basic) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; using offset_t = cudf::test::fixed_width_column_wrapper<cudf::size_type>; auto data = this->make_test_structs({{42, 42, 42}, {1, 0, 1}}, {{"hello", "你好!", "bonjour!"}, {false, true, true}}, LCW({LCW{88}, LCW{}, LCW{99, 99}}, mask_vector{1, 0, 1}.begin()), {1, 1, 0}); auto slr = std::make_unique<cudf::list_scalar>(data, true); auto child = this->make_test_structs( {{1, 1, 2, 3, 3, 3}, {0, 1, 1, 1, 0, 0}}, {{"x", "x", "yy", "", "zzz", "zzz"}, {true, true, true, false, true, true}}, LCW({LCW{10, 10}, LCW{}, LCW{10}, LCW{20, 20}, LCW{}, LCW{30, 30}}, mask_vector{1, 0, 1, 1, 0, 1}.begin()), {1, 1, 0, 0, 1, 1}); offset_t offsets{0, 2, 2, 3, 6}; auto col = cudf::make_lists_column(4, offsets.release(), child.release(), 0, rmm::device_buffer{}); size_column scatter_map{1, 3}; auto ex_child = this->make_test_structs( {{1, 1, 42, 42, 42, 2, 42, 42, 42}, {0, 1, 1, 0, 1, 1, 1, 0, 1}}, {{"x", "x", "hello", "你好!", "bonjour!", "yy", "hello", "你好!", "bonjour!"}, {true, true, false, true, true, true, false, true, true}}, LCW({LCW{10, 10}, LCW{}, LCW{88}, LCW{}, LCW{99, 99}, LCW{10}, LCW{88}, LCW{}, LCW{99, 99}}, mask_vector{1, 0, 1, 0, 1, 1, 1, 0, 1}.begin()), {1, 1, 1, 1, 0, 0, 1, 1, 0}); offset_t ex_offsets{0, 2, 5, 6, 9}; auto expected = cudf::make_lists_column(4, ex_offsets.release(), ex_child.release(), 0, rmm::device_buffer{}); auto result = single_scalar_scatter(*col, *slr, scatter_map); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected); } TYPED_TEST(ScatterListOfStructScalarTest, EmptyValidScalar) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; using offset_t = cudf::test::fixed_width_column_wrapper<cudf::size_type>; auto data = this->make_test_structs({}, {}, LCW{}, {}); auto slr = std::make_unique<cudf::list_scalar>(data, true); auto child = this->make_test_structs( {{1, 1, 2, 3, 3, 3}, {0, 1, 1, 1, 0, 0}}, {{"x", "x", "yy", "", "zzz", "zzz"}, {true, true, true, false, true, true}}, LCW({LCW{10, 10}, LCW{}, LCW{10}, LCW{20, 20}, LCW{}, LCW{30, 30}}, mask_vector{1, 0, 1, 1, 0, 1}.begin()), {1, 1, 0, 0, 1, 1}); offset_t offsets{0, 2, 2, 3, 6}; auto col = cudf::make_lists_column(4, offsets.release(), child.release(), 0, rmm::device_buffer{}); size_column scatter_map{0, 2}; auto ex_child = this->make_test_structs({{3, 3, 3}, {1, 0, 0}}, {{"", "zzz", "zzz"}, {false, true, true}}, LCW({LCW{20, 20}, LCW{}, LCW{30, 30}}, mask_vector{1, 0, 1}.begin()), {0, 1, 1}); offset_t ex_offsets{0, 0, 0, 0, 3}; auto expected = cudf::make_lists_column(4, ex_offsets.release(), ex_child.release(), 0, rmm::device_buffer{}); auto result = single_scalar_scatter(*col, *slr, scatter_map); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected); } TYPED_TEST(ScatterListOfStructScalarTest, NullScalar) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; using offset_t = cudf::test::fixed_width_column_wrapper<cudf::size_type>; auto data = this->make_test_structs({}, {}, {}, {}); auto slr = std::make_unique<cudf::list_scalar>(data, false); auto child = this->make_test_structs( {{1, 1, 2, 3, 3, 3}, {0, 1, 1, 1, 0, 0}}, {{"x", "x", "yy", "", "zzz", "zzz"}, {true, true, true, false, true, true}}, LCW({LCW{10, 10}, LCW{}, LCW{10}, LCW{20, 20}, LCW{}, LCW{30, 30}}, mask_vector{1, 0, 1, 1, 0, 1}.begin()), {1, 1, 1, 0, 1, 1}); offset_t offsets{0, 2, 2, 3, 6}; auto col = cudf::make_lists_column(4, offsets.release(), child.release(), 0, rmm::device_buffer{}); size_column scatter_map{3, 1, 0}; auto ex_child = this->make_test_structs({2}, {"yy"}, LCW({10}, mask_vector{1}.begin()), {1}); offset_t ex_offsets{0, 0, 0, 1, 1}; auto null_mask = cudf::create_null_mask(4, cudf::mask_state::ALL_NULL); cudf::set_null_mask(static_cast<cudf::bitmask_type*>(null_mask.data()), 2, 3, true); auto expected = cudf::make_lists_column(4, ex_offsets.release(), ex_child.release(), 3, std::move(null_mask)); auto result = single_scalar_scatter(*col, *slr, scatter_map); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected); } TYPED_TEST(ScatterListOfStructScalarTest, NullableTargetRow) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; using offset_t = cudf::test::fixed_width_column_wrapper<cudf::size_type>; auto data = this->make_test_structs({{42, 42, 42}, {1, 0, 1}}, {{"hello", "你好!", "bonjour!"}, {false, true, true}}, LCW({LCW{88}, LCW{}, LCW{99, 99}}, mask_vector{1, 0, 1}.begin()), {1, 1, 0}); auto slr = std::make_unique<cudf::list_scalar>(data, true); auto child = this->make_test_structs( {{1, 1, 2, 3, 3, 3}, {0, 1, 1, 1, 0, 0}}, {{"x", "x", "yy", "", "zzz", "zzz"}, {true, true, true, false, true, true}}, LCW({LCW{10, 10}, LCW{}, LCW{10}, LCW{20, 20}, LCW{}, LCW{30, 30}}, mask_vector{1, 0, 1, 1, 0, 1}.begin()), {1, 1, 1, 0, 1, 1}); offset_t offsets{0, 2, 2, 3, 6}; auto null_mask = cudf::create_null_mask(4, cudf::mask_state::ALL_VALID); cudf::set_null_mask(static_cast<cudf::bitmask_type*>(null_mask.data()), 1, 3, false); auto col = cudf::make_lists_column(4, offsets.release(), child.release(), 2, std::move(null_mask)); size_column scatter_map{3, 2}; auto ex_child = this->make_test_structs( {{1, 1, 42, 42, 42, 42, 42, 42}, {0, 1, 1, 0, 1, 1, 0, 1}}, {{"x", "x", "hello", "你好!", "bonjour!", "hello", "你好!", "bonjour!"}, {true, true, false, true, true, false, true, true}}, LCW({LCW{10, 10}, LCW{}, LCW{88}, LCW{}, LCW{99, 99}, LCW{88}, LCW{}, LCW{99, 99}}, mask_vector{1, 0, 1, 0, 1, 1, 0, 1}.begin()), {1, 1, 1, 1, 0, 1, 1, 0}); offset_t ex_offsets{0, 2, 2, 5, 8}; auto ex_null_mask = cudf::create_null_mask(4, cudf::mask_state::ALL_VALID); cudf::set_null_mask(static_cast<cudf::bitmask_type*>(ex_null_mask.data()), 1, 2, false); auto expected = cudf::make_lists_column( 4, ex_offsets.release(), ex_child.release(), 1, std::move(ex_null_mask)); auto result = single_scalar_scatter(*col, *slr, scatter_map); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/slice_tests.cuh
/* * Copyright (c) 2019-2022, NVIDIA CORPORATION. * * Licensed 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. */ #pragma once #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> template <typename T, typename InputIterator> cudf::test::fixed_width_column_wrapper<T> create_fixed_columns(cudf::size_type start, cudf::size_type size, InputIterator valids) { auto iter = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return T(i); }); return cudf::test::fixed_width_column_wrapper<T>(iter, iter + size, valids); } template <typename T, typename InputIterator> cudf::table create_fixed_table(cudf::size_type num_cols, cudf::size_type start, cudf::size_type col_size, InputIterator valids) { std::vector<std::unique_ptr<cudf::column>> cols; for (int idx = 0; idx < num_cols; idx++) { cudf::test::fixed_width_column_wrapper<T> wrap = create_fixed_columns<T>(start + (idx * num_cols), col_size, valids); cols.push_back(wrap.release()); } return cudf::table(std::move(cols)); } template <typename T> std::vector<cudf::test::fixed_width_column_wrapper<T>> create_expected_columns( std::vector<cudf::size_type> const& indices, bool nullable) { std::vector<cudf::test::fixed_width_column_wrapper<T>> result = {}; for (unsigned long index = 0; index < indices.size(); index += 2) { auto iter = cudf::detail::make_counting_transform_iterator(indices[index], [](auto i) { return T(i); }); if (not nullable) { result.push_back(cudf::test::fixed_width_column_wrapper<T>( iter, iter + (indices[index + 1] - indices[index]))); } else { auto valids = cudf::detail::make_counting_transform_iterator( indices[index], [](auto i) { return i % 2 == 0; }); result.push_back(cudf::test::fixed_width_column_wrapper<T>( iter, iter + (indices[index + 1] - indices[index]), valids)); } } return result; } template <typename T> std::vector<cudf::test::fixed_width_column_wrapper<T>> create_expected_columns( std::vector<cudf::size_type> const& indices, std::vector<bool> const& validity) { std::vector<cudf::test::fixed_width_column_wrapper<T>> result = {}; for (unsigned long index = 0; index < indices.size(); index += 2) { auto iter = cudf::detail::make_counting_transform_iterator(indices[index], [](auto i) { return T(i); }); result.push_back(cudf::test::fixed_width_column_wrapper<T>( iter, iter + (indices[index + 1] - indices[index]), validity.begin() + indices[index])); } return result; } template <typename T, typename ElementIter> std::vector<cudf::test::fixed_width_column_wrapper<T>> create_expected_columns( std::vector<cudf::size_type> const& indices, ElementIter begin, bool nullable) { std::vector<cudf::test::fixed_width_column_wrapper<T>> result = {}; for (unsigned long index = 0; index < indices.size(); index += 2) { auto iter = begin + indices[index]; if (not nullable) { result.push_back(cudf::test::fixed_width_column_wrapper<T>( iter, iter + (indices[index + 1] - indices[index]))); } else { auto valids = cudf::detail::make_counting_transform_iterator( indices[index], [](auto i) { return i % 2 == 0; }); result.push_back(cudf::test::fixed_width_column_wrapper<T>( iter, iter + (indices[index + 1] - indices[index]), valids)); } } return result; } template <typename T, typename ElementIter> std::vector<cudf::test::fixed_width_column_wrapper<T>> create_expected_columns( std::vector<cudf::size_type> const& indices, ElementIter begin, std::vector<bool> const& validity) { std::vector<cudf::test::fixed_width_column_wrapper<T>> result = {}; for (unsigned long index = 0; index < indices.size(); index += 2) { auto iter = begin + indices[index]; result.push_back(cudf::test::fixed_width_column_wrapper<T>( iter, iter + (indices[index + 1] - indices[index]), validity.begin() + indices[index])); } return result; } template <typename T> std::vector<cudf::table> create_expected_tables(cudf::size_type num_cols, std::vector<cudf::size_type> const& indices, bool nullable) { std::vector<cudf::table> result; for (unsigned long index = 0; index < indices.size(); index += 2) { std::vector<std::unique_ptr<cudf::column>> cols = {}; for (int idx = 0; idx < num_cols; idx++) { auto iter = cudf::detail::make_counting_transform_iterator(indices[index] + (idx * num_cols), [](auto i) { return T(i); }); if (not nullable) { cudf::test::fixed_width_column_wrapper<T> wrap( iter, iter + (indices[index + 1] - indices[index])); cols.push_back(wrap.release()); } else { auto valids = cudf::detail::make_counting_transform_iterator( indices[index], [](auto i) { return i % 2 == 0; }); cudf::test::fixed_width_column_wrapper<T> wrap( iter, iter + (indices[index + 1] - indices[index]), valids); cols.push_back(wrap.release()); } } result.push_back(cudf::table(std::move(cols))); } return result; } inline std::vector<cudf::test::strings_column_wrapper> create_expected_string_columns( std::vector<std::string> const& strings, std::vector<cudf::size_type> const& indices, bool nullable) { std::vector<cudf::test::strings_column_wrapper> result = {}; for (unsigned long index = 0; index < indices.size(); index += 2) { if (not nullable) { result.push_back(cudf::test::strings_column_wrapper(strings.begin() + indices[index], strings.begin() + indices[index + 1])); } else { auto valids = cudf::detail::make_counting_transform_iterator( indices[index], [](auto i) { return i % 2 == 0; }); result.push_back(cudf::test::strings_column_wrapper( strings.begin() + indices[index], strings.begin() + indices[index + 1], valids)); } } return result; } inline std::vector<cudf::test::strings_column_wrapper> create_expected_string_columns( std::vector<std::string> const& strings, std::vector<cudf::size_type> const& indices, std::vector<bool> const& validity) { std::vector<cudf::test::strings_column_wrapper> result = {}; for (unsigned long index = 0; index < indices.size(); index += 2) { result.push_back(cudf::test::strings_column_wrapper(strings.begin() + indices[index], strings.begin() + indices[index + 1], validity.begin() + indices[index])); } return result; } inline std::vector<cudf::table> create_expected_string_tables( std::vector<std::string> const strings[2], std::vector<cudf::size_type> const& indices, bool nullable) { std::vector<cudf::table> result = {}; for (unsigned long index = 0; index < indices.size(); index += 2) { std::vector<std::unique_ptr<cudf::column>> cols = {}; for (int idx = 0; idx < 2; idx++) { if (not nullable) { cudf::test::strings_column_wrapper wrap(strings[idx].begin() + indices[index], strings[idx].begin() + indices[index + 1]); cols.push_back(wrap.release()); } else { auto valids = cudf::detail::make_counting_transform_iterator( indices[index], [](auto i) { return i % 2 == 0; }); cudf::test::strings_column_wrapper wrap( strings[idx].begin() + indices[index], strings[idx].begin() + indices[index + 1], valids); cols.push_back(wrap.release()); } } result.push_back(cudf::table(std::move(cols))); } return result; }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/scatter_struct_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/copying.hpp> #include <cudf/lists/lists_column_view.hpp> #include <cudf/table/table_view.hpp> using namespace cudf::test::iterators; using bools_col = cudf::test::fixed_width_column_wrapper<bool>; using int32s_col = cudf::test::fixed_width_column_wrapper<int32_t>; using structs_col = cudf::test::structs_column_wrapper; using strings_col = cudf::test::strings_column_wrapper; constexpr cudf::test::debug_output_level verbosity{cudf::test::debug_output_level::FIRST_ERROR}; constexpr int32_t null{0}; // Mark for null child elements constexpr int32_t XXX{0}; // Mark for null struct elements template <typename T> struct TypedStructScatterTest : public cudf::test::BaseFixture {}; using TestTypes = cudf::test::Concat<cudf::test::IntegralTypes, cudf::test::FloatingPointTypes, cudf::test::DurationTypes, cudf::test::TimestampTypes>; TYPED_TEST_SUITE(TypedStructScatterTest, TestTypes); namespace { auto scatter_structs(std::unique_ptr<cudf::column> const& structs_src, std::unique_ptr<cudf::column> const& structs_tgt, std::unique_ptr<cudf::column> const& scatter_map) { auto const source = cudf::table_view{std::vector<cudf::column_view>{structs_src->view()}}; auto const target = cudf::table_view{std::vector<cudf::column_view>{structs_tgt->view()}}; auto const result = cudf::scatter(source, scatter_map->view(), target); return result->get_column(0); } } // namespace // Test case when all input columns are empty TYPED_TEST(TypedStructScatterTest, EmptyInputTest) { using col_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto child_col_src = col_wrapper{}; auto const structs_src = structs_col{{child_col_src}}.release(); auto child_col_tgt = col_wrapper{}; auto const structs_tgt = structs_col{{child_col_tgt}}.release(); auto const scatter_map = int32s_col{}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *structs_src, scatter_structs(structs_src, structs_tgt, scatter_map), verbosity); } // Test case when only the scatter map is empty TYPED_TEST(TypedStructScatterTest, EmptyScatterMapTest) { using col_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto child_col_src = col_wrapper{{0, 1, 2, 3, null, XXX}, null_at(4)}; auto const structs_src = structs_col{{child_col_src}, null_at(5)}.release(); auto child_col_tgt = col_wrapper{{50, null, 70, XXX, 90, 100}, null_at(1)}; auto const structs_tgt = structs_col{{child_col_tgt}, null_at(3)}.release(); auto const scatter_map = int32s_col{}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *structs_tgt, scatter_structs(structs_src, structs_tgt, scatter_map), verbosity); } TYPED_TEST(TypedStructScatterTest, ScatterAsCopyTest) { using col_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto child_col_src = col_wrapper{{0, 1, 2, 3, null, XXX}, null_at(4)}; auto const structs_src = structs_col{{child_col_src}, null_at(5)}.release(); auto child_col_tgt = col_wrapper{{50, null, 70, XXX, 90, 100}, null_at(1)}; auto const structs_tgt = structs_col{{child_col_tgt}, null_at(3)}.release(); // Scatter as copy: the target should be the same as source auto const scatter_map = int32s_col{0, 1, 2, 3, 4, 5}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *structs_src, scatter_structs(structs_src, structs_tgt, scatter_map), verbosity); } TYPED_TEST(TypedStructScatterTest, ScatterAsLeftShiftTest) { using col_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto child_col_src = col_wrapper{{0, 1, 2, 3, null, XXX}, null_at(4)}; auto const structs_src = structs_col{{child_col_src}, null_at(5)}.release(); auto child_col_tgt = col_wrapper{{50, null, 70, XXX, 90, 100}, null_at(1)}; auto const structs_tgt = structs_col{{child_col_tgt}, null_at(3)}.release(); auto child_col_expected = col_wrapper{{2, 3, null, XXX, 0, 1}, null_at(2)}; auto structs_expected = structs_col{{child_col_expected}, null_at(3)}.release(); auto const scatter_map = int32s_col{-2, -1, 0, 1, 2, 3}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *structs_expected, scatter_structs(structs_src, structs_tgt, scatter_map), verbosity); } TYPED_TEST(TypedStructScatterTest, SimpleScatterTests) { using col_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; // Source data auto child_col_src = col_wrapper{{0, 1, 2, 3, null, XXX}, null_at(4)}; auto const structs_src = structs_col{{child_col_src}, null_at(5)}.release(); // Target data auto child_col_tgt = col_wrapper{{50, null, 70, XXX, 90, 100}, null_at(1)}; auto const structs_tgt = structs_col{{child_col_tgt}, null_at(3)}.release(); // Expected data auto child_col_expected1 = col_wrapper{{1, null, 70, XXX, 0, 2}, null_at(1)}; auto const structs_expected1 = structs_col{{child_col_expected1}, null_at(3)}.release(); auto const scatter_map1 = int32s_col{-2, 0, 5}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *structs_expected1, scatter_structs(structs_src, structs_tgt, scatter_map1), verbosity); // Expected data auto child_col_expected2 = col_wrapper{{1, null, 70, 3, 0, 2}, null_at(1)}; auto const structs_expected2 = structs_col{{child_col_expected2}, no_nulls()}.release(); auto const scatter_map2 = int32s_col{-2, 0, 5, 3}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *structs_expected2, scatter_structs(structs_src, structs_tgt, scatter_map2), verbosity); } TYPED_TEST(TypedStructScatterTest, ComplexDataScatterTest) { // Testing scatter() on struct<string, numeric, bool>. using col_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; // Source data auto names_column_src = strings_col{{"Newton", "Washington", "Cherry", "Kiwi", "Lemon", "Tomato" /*XXX*/}, no_nulls()}; auto ages_column_src = col_wrapper{{5, 10, 15, 20, null, XXX}, null_at(4)}; auto is_human_col_src = bools_col{{true, true, false, false /*null*/, false, false /*XXX*/}, null_at(3)}; auto const structs_src = structs_col{{names_column_src, ages_column_src, is_human_col_src}, null_at(5)}.release(); // Target data auto names_column_tgt = strings_col{ {"String 0" /*null*/, "String 1", "String 2" /*XXX*/, "String 3", "String 4", "String 5"}, null_at(0)}; auto ages_column_tgt = col_wrapper{{50, null, XXX, 80, 90, 100}, null_at(1)}; auto is_human_col_tgt = bools_col{{true, true, true /*XXX*/, true, true, true}, no_nulls()}; auto const structs_tgt = structs_col{{names_column_tgt, ages_column_tgt, is_human_col_tgt}, null_at(2)}.release(); // Expected data auto names_column_expected = strings_col{ {"String 0" /*null*/, "Lemon", "Kiwi", "Cherry", "Washington", "Newton"}, null_at(0)}; auto ages_column_expected = col_wrapper{{50, null, 20, 15, 10, 5}, null_at(1)}; auto is_human_col_expected = bools_col{{true, false, false /*null*/, false, true, true}, null_at(2)}; auto const structs_expected = structs_col{{names_column_expected, ages_column_expected, is_human_col_expected}, no_nulls()} .release(); // The first element of the target is not overwritten auto const scatter_map = int32s_col{-1, 4, 3, 2, 1}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *structs_expected, scatter_structs(structs_src, structs_tgt, scatter_map), verbosity); } TYPED_TEST(TypedStructScatterTest, ScatterStructOfListsTest) { // Testing scatter() on struct<list<numeric>> using lists_col = cudf::test::lists_column_wrapper<TypeParam, int32_t>; // Source data auto lists_col_src = lists_col{{{5}, {10, 15}, {20, 25, 30}, {35, 40, 45, 50}, {55, 60, 65}, {70, 75}, {80}, {}, {}}, // Valid for elements 0, 3, 6,... cudf::detail::make_counting_transform_iterator(0, [](auto i) { return !(i % 3); })}; auto const structs_src = structs_col{{lists_col_src}}.release(); // Target data auto lists_col_tgt = lists_col{{{1}, {2, 3}, {4, 5, 6}, {7, 8}, {9}, {10, 11, 12, 13}, {}, {14}, {15, 16}}, // Valid for elements 1, 3, 5, 7,... cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2; })}; auto const structs_tgt = structs_col{{lists_col_tgt}}.release(); // Expected data auto const validity_expected = std::vector<bool>{0, 1, 1, 0, 0, 1, 1, 0, 0}; auto lists_col_expected = lists_col{ {{1}, {2, 3}, {80}, {70, 75}, {55, 60, 65}, {35, 40, 45, 50}, {5}, {10, 15}, {20, 25, 30}}, validity_expected.begin()}; auto const structs_expected = structs_col{{lists_col_expected}}.release(); // The first 2 elements of the target is not overwritten auto const scatter_map = int32s_col{-3, -2, -1, 5, 4, 3, 2}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *structs_expected, scatter_structs(structs_src, structs_tgt, scatter_map), verbosity); } TYPED_TEST(TypedStructScatterTest, SourceSmallerThanTargetScatterTest) { using col_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto child_col_src = col_wrapper{22, 55}; auto const structs_src = structs_col{{child_col_src}}.release(); auto child_col_tgt = col_wrapper{0, 1, 2, 3, 4, 5, 6}; auto const structs_tgt = structs_col{{child_col_tgt}}.release(); auto child_col_expected = col_wrapper{0, 1, 22, 3, 4, 55, 6}; auto const structs_expected = structs_col{{child_col_expected}}.release(); auto const scatter_map = int32s_col{2, 5}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *structs_expected, scatter_structs(structs_src, structs_tgt, scatter_map), verbosity); } TYPED_TEST(TypedStructScatterTest, IntStructNullMaskRegression) { using col_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto child_tgt = col_wrapper({0, null, 2}, null_at(1)); auto struct_col_tgt = structs_col({child_tgt}).release(); auto child_src = col_wrapper{20}; auto struct_col_src = structs_col({child_src}).release(); auto scatter_map = int32s_col{2}.release(); auto expected_child = col_wrapper({0, null, 20}, null_at(1)); auto expected_struct = structs_col({expected_child}).release(); auto const result = scatter_structs(struct_col_src, struct_col_tgt, scatter_map); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*expected_struct, result, verbosity); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/copy_if_else_nested_tests.cpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/copying.hpp> #include <cudf/scalar/scalar_factories.hpp> using namespace cudf::test::iterators; struct CopyIfElseNestedTest : cudf::test::BaseFixture {}; template <typename T> struct TypedCopyIfElseNestedTest : CopyIfElseNestedTest {}; TYPED_TEST_SUITE(TypedCopyIfElseNestedTest, cudf::test::FixedWidthTypes); TYPED_TEST(TypedCopyIfElseNestedTest, Structs) { using T = TypeParam; using ints = cudf::test::fixed_width_column_wrapper<T, int32_t>; using strings = cudf::test::strings_column_wrapper; using structs = cudf::test::structs_column_wrapper; using bools = cudf::test::fixed_width_column_wrapper<bool, int32_t>; auto lhs_ints_child = ints{0, 1, 2, 3, 4, 5, 6}; auto lhs_strings_child = strings{"0", "1", "2", "3", "4", "5", "6"}; auto lhs_structs_column = structs{{lhs_ints_child, lhs_strings_child}}.release(); auto rhs_ints_child = ints{0, 11, 22, 33, 44, 55, 66}; auto rhs_strings_child = strings{"00", "11", "22", "33", "44", "55", "66"}; auto rhs_structs_column = structs{{rhs_ints_child, rhs_strings_child}}.release(); auto selector_column = bools{1, 1, 0, 1, 1, 0, 1}.release(); auto result_column = cudf::copy_if_else( lhs_structs_column->view(), rhs_structs_column->view(), selector_column->view()); auto expected_ints = ints{0, 1, 22, 3, 4, 55, 6}; auto expected_strings = strings{"0", "1", "22", "3", "4", "55", "6"}; auto expected_result = structs{{expected_ints, expected_strings}}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result_column->view(), expected_result->view()); } TYPED_TEST(TypedCopyIfElseNestedTest, StructsWithNulls) { using T = TypeParam; using ints = cudf::test::fixed_width_column_wrapper<T, int32_t>; using strings = cudf::test::strings_column_wrapper; using structs = cudf::test::structs_column_wrapper; using bools = cudf::test::fixed_width_column_wrapper<bool, int32_t>; auto null_at_0 = null_at(0); auto null_at_3 = null_at(3); auto null_at_5 = null_at(5); auto lhs_ints_child = ints{{0, 1, 2, 3, 4, 5, 6}, null_at_0}; auto lhs_strings_child = strings{"0", "1", "2", "3", "4", "5", "6"}; auto lhs_structs_column = structs{{lhs_ints_child, lhs_strings_child}, null_at_3}.release(); auto rhs_ints_child = ints{0, 11, 22, 33, 44, 55, 66}; auto rhs_strings_child = strings{{"00", "11", "22", "33", "44", "55", "66"}, null_at_5}; auto rhs_structs_column = structs{{rhs_ints_child, rhs_strings_child}}.release(); auto selector_column = bools{1, 1, 0, 1, 1, 0, 1}.release(); auto result_column = cudf::copy_if_else( lhs_structs_column->view(), rhs_structs_column->view(), selector_column->view()); auto null_at_0_3 = nulls_at(std::vector<cudf::size_type>{0, 3}); auto null_at_3_5 = nulls_at(std::vector<cudf::size_type>{3, 5}); auto expected_ints = ints{{-1, 1, 22, 3, 4, 55, 6}, null_at_0_3}; auto expected_strings = strings{{"0", "1", "22", "", "4", "", "6"}, null_at_3_5}; auto expected_result = structs{{expected_ints, expected_strings}, null_at_3}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result_column->view(), expected_result->view()); } TYPED_TEST(TypedCopyIfElseNestedTest, LongerStructsWithNulls) { using T = TypeParam; using ints = cudf::test::fixed_width_column_wrapper<T, int32_t>; using structs = cudf::test::structs_column_wrapper; using bools = cudf::test::fixed_width_column_wrapper<bool, int32_t>; auto selector_column = bools{1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0} .release(); auto lhs_child_1 = ints{{27, -80, -24, 76, -56, 42, 5, 13, -69, -77, 61, -77, 72, 0, 31, 118, -30, 86, 125, 0, 0, 0, 75, -49, 125, 60, 116, 118, 64, 20, -70, -18, 0, -25, 22, -46, -89, -9, 27, -56, -77, 123, 0, -90, 87, -113, -37, 22, -22, -53, 73, 99, 113, -2, -24, 113, 75, 6, 82, -58, 122, -123, -127, 19, -62, -24}, nulls_at(std::vector<cudf::size_type>{13, 19, 20, 21, 32, 42})}; auto lhs_structs_column = structs{{lhs_child_1}}.release(); auto result_column = cudf::copy_if_else( lhs_structs_column->view(), lhs_structs_column->view(), selector_column->view()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result_column->view(), lhs_structs_column->view()); } TYPED_TEST(TypedCopyIfElseNestedTest, ScalarStructBothInvalid) { using T = TypeParam; using ints = cudf::test::fixed_width_column_wrapper<T, int32_t>; using strings = cudf::test::strings_column_wrapper; using structs = cudf::test::structs_column_wrapper; using bools = cudf::test::fixed_width_column_wrapper<bool, int32_t>; auto lhs_child_ints = ints{11}; auto lhs_child_strings = strings{"11"}; auto lhs_children = std::vector<cudf::column_view>{{lhs_child_ints, lhs_child_strings}}; auto lhs_scalar = cudf::struct_scalar{lhs_children, false}; auto rhs_child_ints = ints{{22}, null_at(0)}; auto rhs_child_strings = strings{"22"}; auto rhs_children = std::vector<cudf::column_view>{{rhs_child_ints, rhs_child_strings}}; auto rhs_scalar = cudf::struct_scalar{rhs_children, false}; auto selector_column = bools{1, 1, 0, 1, 1, 0, 1}.release(); auto expected_ints = ints{-11, -11, -22, -11, -11, -22, -11}; auto expected_strings = strings{"-11", "-11", "-22", "-11", "-22", "-11", "-11"}; auto expected_result = structs{{expected_ints, expected_strings}, all_nulls()}.release(); auto result_column = cudf::copy_if_else(lhs_scalar, rhs_scalar, selector_column->view()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_column->view()); } TYPED_TEST(TypedCopyIfElseNestedTest, ScalarStructBothValid) { using T = TypeParam; using ints = cudf::test::fixed_width_column_wrapper<T, int32_t>; using strings = cudf::test::strings_column_wrapper; using structs = cudf::test::structs_column_wrapper; using bools = cudf::test::fixed_width_column_wrapper<bool, int32_t>; auto lhs_child_ints = ints{11}; auto lhs_child_strings = strings{{"11"}, null_at(0)}; auto lhs_children = std::vector<cudf::column_view>{{lhs_child_ints, lhs_child_strings}}; auto lhs_scalar = cudf::make_struct_scalar(lhs_children); auto rhs_child_ints = ints{{22}, null_at(0)}; auto rhs_child_strings = strings{"22"}; auto rhs_children = std::vector<cudf::column_view>{{rhs_child_ints, rhs_child_strings}}; auto rhs_scalar = cudf::make_struct_scalar(rhs_children); auto selector_column = bools{1, 1, 0, 1, 1, 0, 1}.release(); auto expected_ints = ints{{11, 11, -22, 11, 11, -22, 11}, nulls_at(std::vector<cudf::size_type>{2, 5})}; auto expected_strings = strings{{"NA", "NA", "22", "NA", "NA", "22", "NA"}, nulls_at(std::vector<cudf::size_type>{0, 1, 3, 4, 6})}; auto expected_result = structs{{expected_ints, expected_strings}}.release(); auto result_column = cudf::copy_if_else(*lhs_scalar, *rhs_scalar, selector_column->view()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_column->view()); } TYPED_TEST(TypedCopyIfElseNestedTest, ScalarStructLeft) { using T = TypeParam; using ints = cudf::test::fixed_width_column_wrapper<T, int32_t>; using strings = cudf::test::strings_column_wrapper; using structs = cudf::test::structs_column_wrapper; using bools = cudf::test::fixed_width_column_wrapper<bool, int32_t>; auto lhs_child_ints = ints{11}; auto lhs_child_strings = strings{{"11"}, null_at(0)}; auto lhs_children = std::vector<cudf::column_view>{{lhs_child_ints, lhs_child_strings}}; auto lhs_scalar = cudf::make_struct_scalar(lhs_children); auto rhs_child_ints = ints{{22, 22, 22, 22, 22, 22, 22}, null_at(2)}; auto rhs_child_strings = strings{"22", "22", "22", "22", "22", "22", "22"}; auto rhs_column = structs{{rhs_child_ints, rhs_child_strings}, null_at(5)}.release(); auto selector_column = bools{1, 1, 0, 1, 1, 0, 1}.release(); auto lhs_column = cudf::make_column_from_scalar(*lhs_scalar, selector_column->size()); auto expected_ints = ints{{11, 11, -22, 11, 11, 22, 11}, null_at(2)}; auto expected_strings = strings{{"NA", "NA", "22", "NA", "NA", "22", "NA"}, nulls_at(std::vector<cudf::size_type>{0, 1, 3, 4, 6})}; auto expected_result = structs{{expected_ints, expected_strings}, null_at(5)}.release(); auto result_column = cudf::copy_if_else(*lhs_scalar, rhs_column->view(), selector_column->view()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_column->view()); } TYPED_TEST(TypedCopyIfElseNestedTest, ScalarStructRight) { using T = TypeParam; using ints = cudf::test::fixed_width_column_wrapper<T, int32_t>; using strings = cudf::test::strings_column_wrapper; using structs = cudf::test::structs_column_wrapper; using bools = cudf::test::fixed_width_column_wrapper<bool, int32_t>; auto lhs_child_ints = ints{{11, 11, 11, 11, 11, 11, 11}, nulls_at(std::vector<cudf::size_type>{1, 4})}; auto lhs_child_strings = strings{"11", "11", "11", "11", "11", "11", "11"}; auto lhs_column = structs{{lhs_child_ints, lhs_child_strings}, null_at(6)}.release(); auto rhs_child_ints = ints{{22}, null_at(0)}; auto rhs_child_strings = strings{"22"}; auto rhs_children = std::vector<cudf::column_view>{{rhs_child_ints, rhs_child_strings}}; auto rhs_scalar = cudf::make_struct_scalar(rhs_children); auto selector_column = bools{1, 1, 0, 1, 1, 0, 1}.release(); auto expected_ints = ints{{11, 11, -22, 11, 11, -22, 11}, nulls_at(std::vector<cudf::size_type>{1, 2, 4, 5})}; auto expected_strings = strings{"11", "11", "22", "11", "11", "22", "11"}; auto expected_result = structs{{expected_ints, expected_strings}, null_at(6)}.release(); auto result_column = cudf::copy_if_else(lhs_column->view(), *rhs_scalar, selector_column->view()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_column->view()); } TYPED_TEST(TypedCopyIfElseNestedTest, Lists) { using T = TypeParam; using lcw = cudf::test::lists_column_wrapper<T, int32_t>; auto lhs = lcw{{0, 0}, {1, 1}, {2, 2}, {3, 3, 3}, {4, 4, 4, 4}, {5, 5, 5, 5, 5}, {6, 6, 6, 6, 6, 6}} .release(); auto rhs = lcw{{0, 0}, {11, 11}, {22, 22}, {33, 33, 33}, {44, 44, 44, 44}, {55, 55, 55, 55, 55}, {66, 66, 66, 66, 66, 66}} .release(); auto selector_column = cudf::test::fixed_width_column_wrapper<bool, int32_t>{1, 1, 0, 1, 1, 0, 1}.release(); auto result_column = cudf::copy_if_else(lhs->view(), rhs->view(), selector_column->view()); auto expected_output = lcw{{0, 0}, {1, 1}, {22, 22}, {3, 3, 3}, {4, 4, 4, 4}, {55, 55, 55, 55, 55}, {6, 6, 6, 6, 6, 6}} .release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result_column->view(), expected_output->view()); } TYPED_TEST(TypedCopyIfElseNestedTest, ListsWithNulls) { using T = TypeParam; using lcw = cudf::test::lists_column_wrapper<T, int32_t>; auto null_at_0 = null_at(0); auto null_at_4 = null_at(4); auto null_at_5 = null_at(5); auto lhs = lcw{{{0, 0}, {1, 1}, lcw{{2, 2}, null_at_0}, lcw{{3, 3, 3}, null_at_0}, {4, 4, 4, 4}, {5, 5, 5, 5, 5}, {6, 6, 6, 6, 6, 6}}, null_at_4} .release(); auto rhs = lcw{{{0, 0}, {11, 11}, {22, 22}, {33, 33, 33}, {44, 44, 44, 44}, {55, 55, 55, 55, 55}, {66, 66, 66, 66, 66, 66}}, null_at_5} .release(); auto selector_column = cudf::test::fixed_width_column_wrapper<bool, int32_t>{1, 1, 0, 1, 1, 0, 1}.release(); auto result_column = cudf::copy_if_else(lhs->view(), rhs->view(), selector_column->view()); auto null_at_4_5 = nulls_at(std::vector{4, 5}); auto expected_output = lcw{{{0, 0}, {1, 1}, {22, 22}, lcw{{3, 3, 3}, null_at_0}, {}, {}, {6, 6, 6, 6, 6, 6}}, null_at_4_5} .release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result_column->view(), expected_output->view()); } TYPED_TEST(TypedCopyIfElseNestedTest, ListsWithStructs) { using T = TypeParam; using ints = cudf::test::fixed_width_column_wrapper<T, int32_t>; using strings = cudf::test::strings_column_wrapper; using structs = cudf::test::structs_column_wrapper; using bools = cudf::test::fixed_width_column_wrapper<bool, int32_t>; using offsets = cudf::test::fixed_width_column_wrapper<cudf::size_type, int32_t>; auto const null_at_0 = null_at(0); auto const null_at_3 = null_at(3); auto const null_at_4 = null_at(4); auto const null_at_6 = null_at(6); auto const null_at_7 = null_at(7); auto const null_at_8 = null_at(8); auto lhs_ints = ints{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, null_at_3}; auto lhs_strings = strings{{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}, null_at_4}; auto lhs_structs = structs{{lhs_ints, lhs_strings}}.release(); auto lhs_offsets = offsets{0, 2, 4, 6, 10, 10}.release(); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(null_at_4, null_at_4 + 5); auto const lhs = cudf::make_lists_column( 5, std::move(lhs_offsets), std::move(lhs_structs), null_count, std::move(null_mask)); auto rhs_ints = ints{{0, 11, 22, 33, 44, 55, 66, 77, 88, 99}, null_at_6}; auto rhs_strings = strings{{"00", "11", "22", "33", "44", "55", "66", "77", "88", "99"}, null_at_7}; auto rhs_structs = structs{{rhs_ints, rhs_strings}, null_at_8}; auto rhs_offsets = offsets{0, 0, 4, 6, 8, 10}; std::tie(null_mask, null_count) = cudf::test::detail::make_null_mask(null_at_0, null_at_0 + 5); auto const rhs = cudf::make_lists_column( 5, rhs_offsets.release(), rhs_structs.release(), null_count, std::move(null_mask)); auto selector_column = bools{1, 0, 1, 0, 1}.release(); auto result_column = cudf::copy_if_else(lhs->view(), rhs->view(), selector_column->view()); auto const null_at_6_9 = nulls_at(std::vector{6, 9}); auto expected_ints = ints{{0, 1, 0, 11, 22, 33, 4, 5, -1, 77}, null_at_8}; auto expected_strings = strings{{"0", "1", "00", "11", "22", "33", "", "5", "66", ""}, null_at_6_9}; auto expected_structs = structs{{expected_ints, expected_strings}}; auto expected_offsets = offsets{0, 2, 6, 8, 10, 10}; std::tie(null_mask, null_count) = cudf::test::detail::make_null_mask(null_at_4, null_at_4 + 5); auto const expected = cudf::make_lists_column( 5, expected_offsets.release(), expected_structs.release(), null_count, std::move(null_mask)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result_column->view(), expected->view()); } TYPED_TEST(TypedCopyIfElseNestedTest, ScalarListBothInvalid) { using T = TypeParam; using ints = cudf::test::fixed_width_column_wrapper<T, int32_t>; using bools = cudf::test::fixed_width_column_wrapper<bool, int32_t>; using lcw = cudf::test::lists_column_wrapper<T, int32_t>; auto lhs_scalar = cudf::list_scalar{ints{33, 33, 33}, false}; auto rhs_scalar = cudf::list_scalar{ints{22, 22}, false}; auto selector_column = bools{1, 1, 0, 1, 1, 0, 1}.release(); auto expected = lcw{{ {-33, -33, -33}, {-33, -33, -33}, {-22, -22}, {-33, -33, -33}, {-33, -33, -33}, {-22, -22}, {-33, -33, -33}, }, all_nulls()} .release(); auto result = cudf::copy_if_else(lhs_scalar, rhs_scalar, selector_column->view()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected->view(), result->view()); } TYPED_TEST(TypedCopyIfElseNestedTest, ScalarListBothValid) { using T = TypeParam; using ints = cudf::test::fixed_width_column_wrapper<T, int32_t>; using bools = cudf::test::fixed_width_column_wrapper<bool, int32_t>; using lcw = cudf::test::lists_column_wrapper<T, int32_t>; auto lhs_scalar = cudf::make_list_scalar(ints{{33, 33, 33}, null_at(1)}); auto rhs_scalar = cudf::make_list_scalar(ints{{22, 22}, null_at(0)}); auto selector_column = bools{1, 1, 0, 1, 1, 0, 1}.release(); auto expected = lcw{ lcw{{33, 33, 33}, null_at(1)}, lcw{{33, 33, 33}, null_at(1)}, lcw{{22, 22}, null_at(0)}, lcw{{33, 33, 33}, null_at(1)}, lcw{{33, 33, 33}, null_at(1)}, lcw{{22, 22}, null_at(0)}, lcw{{33, 33, 33}, null_at(1)}, } .release(); auto result = cudf::copy_if_else(*lhs_scalar, *rhs_scalar, selector_column->view()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected->view(), result->view()); } TYPED_TEST(TypedCopyIfElseNestedTest, ScalarListLeft) { using T = TypeParam; using ints = cudf::test::fixed_width_column_wrapper<T, int32_t>; using bools = cudf::test::fixed_width_column_wrapper<bool, int32_t>; using lcw = cudf::test::lists_column_wrapper<T, int32_t>; auto lhs_scalar = cudf::make_list_scalar(ints{{33, 33, 33}, null_at(1)}); auto rhs_column = lcw{{{-2, -1}, {-2, -1, 0}, {21, 22}, {-20, -10, 0}, {-200, -100, 0, 100}, lcw{{23, 24, 25, 26, 27, 28}, null_at(1)}, {-400}}, null_at(2)} .release(); auto selector_column = bools{1, 1, 0, 1, 1, 0, 1}.release(); auto expected = lcw{{lcw{{33, 33, 33}, null_at(1)}, lcw{{33, -33, 33}, null_at(1)}, {-21, -22}, lcw{{33, -33, 33}, null_at(1)}, lcw{{33, -33, 33}, null_at(1)}, lcw{{23, -24, 25, 26, 27, 28}, null_at(1)}, lcw{{33, -33, 33}, null_at(1)}}, null_at(2)} .release(); auto result = cudf::copy_if_else(*lhs_scalar, rhs_column->view(), selector_column->view()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected->view(), result->view()); } TYPED_TEST(TypedCopyIfElseNestedTest, ScalarListRight) { using T = TypeParam; using ints = cudf::test::fixed_width_column_wrapper<T, int32_t>; using bools = cudf::test::fixed_width_column_wrapper<bool, int32_t>; using lcw = cudf::test::lists_column_wrapper<T, int32_t>; auto lhs_column = lcw{{{-2, -1}, {-2, -1, 0}, {21, 22}, {-20, -10, 0}, {-200, -100, 0, 100}, lcw{{23, 24, 25, 26, 27, 28}, null_at(1)}, {-400}}, null_at(2)} .release(); auto rhs_scalar = cudf::make_list_scalar(ints{{33, 33, 33}, null_at(1)}); auto selector_column = bools{0, 0, 1, 0, 0, 1, 0}.release(); auto expected = lcw{{ lcw{{33, -33, 33}, null_at(1)}, lcw{{33, -33, 33}, null_at(1)}, {-21, -22}, lcw{{33, -33, 33}, null_at(1)}, lcw{{33, -33, 33}, null_at(1)}, lcw{{23, -24, 25, 26, 27, 28}, null_at(1)}, lcw{{33, -33, 33}, null_at(1)}, }, null_at(2)} .release(); auto result = cudf::copy_if_else(lhs_column->view(), *rhs_scalar, selector_column->view()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected->view(), result->view()); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/shift_tests.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/copying.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/utilities/default_stream.hpp> #include <cudf/utilities/traits.hpp> #include <rmm/cuda_stream_view.hpp> #include <limits> #include <memory> using TestTypes = cudf::test::Types<int32_t>; template <typename T, typename ScalarType = cudf::scalar_type_t<T>> std::unique_ptr<cudf::scalar> make_scalar( rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) { auto s = new ScalarType(cudf::test::make_type_param_scalar<T>(0), false, stream, mr); return std::unique_ptr<cudf::scalar>(s); } template <typename T, typename ScalarType = cudf::scalar_type_t<T>> std::unique_ptr<cudf::scalar> make_scalar( T value, rmm::cuda_stream_view stream = cudf::get_default_stream(), rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) { auto s = new ScalarType(value, true, stream, mr); return std::unique_ptr<cudf::scalar>(s); } template <typename T> constexpr auto highest() { // chrono types do not have std::numeric_limits specializations and should use T::max() // https://eel.is/c++draft/numeric.limits.general#6 if constexpr (cudf::is_chrono<T>()) return T::max(); return std::numeric_limits<T>::max(); } template <typename T> constexpr auto lowest() { // chrono types do not have std::numeric_limits specializations and should use T::min() // https://eel.is/c++draft/numeric.limits.general#6 if constexpr (cudf::is_chrono<T>()) return T::min(); return std::numeric_limits<T>::lowest(); } template <typename T> struct ShiftTestsTyped : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(ShiftTestsTyped, cudf::test::FixedWidthTypes); TYPED_TEST(ShiftTestsTyped, ColumnEmpty) { using T = TypeParam; std::vector<T> vals{}; std::vector<bool> mask{}; auto input = cudf::test::fixed_width_column_wrapper<T>(vals.begin(), vals.end(), mask.begin()); auto expected = cudf::test::fixed_width_column_wrapper<T>(vals.begin(), vals.end(), mask.begin()); auto fill = make_scalar<T>(); auto actual = cudf::shift(input, 5, *fill); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *actual); } TYPED_TEST(ShiftTestsTyped, NonNullColumn) { using T = TypeParam; auto input = cudf::test::fixed_width_column_wrapper<T>{lowest<T>(), cudf::test::make_type_param_scalar<T>(1), cudf::test::make_type_param_scalar<T>(2), cudf::test::make_type_param_scalar<T>(3), cudf::test::make_type_param_scalar<T>(4), cudf::test::make_type_param_scalar<T>(5), highest<T>()}; auto expected = cudf::test::fixed_width_column_wrapper<T>{cudf::test::make_type_param_scalar<T>(7), cudf::test::make_type_param_scalar<T>(7), lowest<T>(), cudf::test::make_type_param_scalar<T>(1), cudf::test::make_type_param_scalar<T>(2), cudf::test::make_type_param_scalar<T>(3), cudf::test::make_type_param_scalar<T>(4)}; auto fill = make_scalar<T>(cudf::test::make_type_param_scalar<T>(7)); auto actual = cudf::shift(input, 2, *fill); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *actual); } TYPED_TEST(ShiftTestsTyped, NegativeShift) { using T = TypeParam; auto input = cudf::test::fixed_width_column_wrapper<T>{lowest<T>(), cudf::test::make_type_param_scalar<T>(1), cudf::test::make_type_param_scalar<T>(2), cudf::test::make_type_param_scalar<T>(3), cudf::test::make_type_param_scalar<T>(4), cudf::test::make_type_param_scalar<T>(5), highest<T>()}; auto expected = cudf::test::fixed_width_column_wrapper<T>{cudf::test::make_type_param_scalar<T>(4), cudf::test::make_type_param_scalar<T>(5), highest<T>(), cudf::test::make_type_param_scalar<T>(7), cudf::test::make_type_param_scalar<T>(7), cudf::test::make_type_param_scalar<T>(7), cudf::test::make_type_param_scalar<T>(7)}; auto fill = make_scalar<T>(cudf::test::make_type_param_scalar<T>(7)); auto actual = cudf::shift(input, -4, *fill); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *actual); } TYPED_TEST(ShiftTestsTyped, NullScalar) { using T = TypeParam; auto input = cudf::test::fixed_width_column_wrapper<T>{lowest<T>(), cudf::test::make_type_param_scalar<T>(5), cudf::test::make_type_param_scalar<T>(0), cudf::test::make_type_param_scalar<T>(3), cudf::test::make_type_param_scalar<T>(0), cudf::test::make_type_param_scalar<T>(1), highest<T>()}; auto expected = cudf::test::fixed_width_column_wrapper<T>({cudf::test::make_type_param_scalar<T>(0), cudf::test::make_type_param_scalar<T>(0), lowest<T>(), cudf::test::make_type_param_scalar<T>(5), cudf::test::make_type_param_scalar<T>(0), cudf::test::make_type_param_scalar<T>(3), cudf::test::make_type_param_scalar<T>(0)}, {0, 0, 1, 1, 1, 1, 1}); auto fill = make_scalar<T>(); auto actual = cudf::shift(input, 2, *fill); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *actual); } TYPED_TEST(ShiftTestsTyped, NullableColumn) { using T = TypeParam; auto input = cudf::test::fixed_width_column_wrapper<T, int32_t>({1, 2, 3, 4, 5}, {0, 1, 1, 1, 0}); auto expected = cudf::test::fixed_width_column_wrapper<T, int32_t>({7, 7, 1, 2, 3}, {1, 1, 0, 1, 1}); auto fill = make_scalar<T>(cudf::test::make_type_param_scalar<T>(7)); auto actual = cudf::shift(input, 2, *fill); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *actual); } TYPED_TEST(ShiftTestsTyped, MismatchFillValueDtypes) { using T = TypeParam; auto input = cudf::test::fixed_width_column_wrapper<T>{}; auto fill = cudf::string_scalar(""); EXPECT_THROW(cudf::shift(input, 5, fill), cudf::logic_error); } struct ShiftTests : public cudf::test::BaseFixture {}; TEST_F(ShiftTests, StringsShiftTest) { auto input = cudf::test::strings_column_wrapper({"", "bb", "ccc", "ddddddé", ""}, {0, 1, 1, 1, 0}); auto fill = cudf::string_scalar("xx"); auto results = cudf::shift(input, 2, fill); auto expected_right = cudf::test::strings_column_wrapper({"xx", "xx", "", "bb", "ccc"}, {1, 1, 0, 1, 1}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_right, *results); results = cudf::shift(input, -2, fill); auto expected_left = cudf::test::strings_column_wrapper({"ccc", "ddddddé", "", "xx", "xx"}, {1, 1, 0, 1, 1}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_left, *results); auto sliced = cudf::slice(input, {1, 4}).front(); results = cudf::shift(sliced, 1, fill); auto sliced_right = cudf::test::strings_column_wrapper({"xx", "bb", "ccc"}, {1, 1, 1}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(sliced_right, *results); results = cudf::shift(sliced, -1, fill); auto sliced_left = cudf::test::strings_column_wrapper({"ccc", "ddddddé", "xx"}, {1, 1, 1}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(sliced_left, *results); } TEST_F(ShiftTests, StringsShiftNullFillTest) { auto input = cudf::test::strings_column_wrapper( {"a", "b", "c", "d", "e", "ff", "ggg", "hhhh", "iii", "jjjjj"}); auto phil = cudf::string_scalar("", false); auto results = cudf::shift(input, -1, phil); auto expected = cudf::test::strings_column_wrapper( {"b", "c", "d", "e", "ff", "ggg", "hhhh", "iii", "jjjjj", ""}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); results = cudf::shift(input, 1, phil); expected = cudf::test::strings_column_wrapper( {"", "a", "b", "c", "d", "e", "ff", "ggg", "hhhh", "iii"}, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); auto sliced = cudf::slice(input, {5, 10}).front(); results = cudf::shift(sliced, -2, phil); expected = cudf::test::strings_column_wrapper({"hhhh", "iii", "jjjjj", "", ""}, {1, 1, 1, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); results = cudf::shift(sliced, 2, phil); expected = cudf::test::strings_column_wrapper({"", "", "ff", "ggg", "hhhh"}, {0, 0, 1, 1, 1}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } TEST_F(ShiftTests, OffsetGreaterThanSize) { auto const input_str = cudf::test::strings_column_wrapper({"", "bb", "ccc", "ddé", ""}, {0, 1, 1, 1, 0}); auto results = cudf::shift(input_str, 6, cudf::string_scalar("xx")); auto expected_str = cudf::test::strings_column_wrapper({"xx", "xx", "xx", "xx", "xx"}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_str, *results); results = cudf::shift(input_str, -6, cudf::string_scalar("xx")); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_str, *results); results = cudf::shift(input_str, 6, cudf::string_scalar("", false)); expected_str = cudf::test::strings_column_wrapper({"", "", "", "", ""}, {0, 0, 0, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_str, *results); results = cudf::shift(input_str, -6, cudf::string_scalar("", false)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_str, *results); auto const input = cudf::test::fixed_width_column_wrapper<int32_t>({0, 2, 3, 4, 0}, {0, 1, 1, 1, 0}); results = cudf::shift(input, 6, cudf::numeric_scalar<int32_t>(9)); auto expected = cudf::test::fixed_width_column_wrapper<int32_t>({9, 9, 9, 9, 9}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *results); results = cudf::shift(input, -6, cudf::numeric_scalar<int32_t>(9)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *results); results = cudf::shift(input, 6, cudf::numeric_scalar<int32_t>(0, false)); expected = cudf::test::fixed_width_column_wrapper<int32_t>({0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *results); results = cudf::shift(input, -6, cudf::numeric_scalar<int32_t>(0, false)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *results); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/gather_list_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/column/column_view.hpp> #include <cudf/copying.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/lists/lists_column_view.hpp> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> template <typename T> class GatherTestListTyped : public cudf::test::BaseFixture {}; using FixedWidthTypesNotBool = cudf::test::Concat<cudf::test::IntegralTypesNotBool, cudf::test::FixedPointTypes, cudf::test::FloatingPointTypes, cudf::test::DurationTypes, cudf::test::TimestampTypes>; TYPED_TEST_SUITE(GatherTestListTyped, FixedWidthTypesNotBool); class GatherTestList : public cudf::test::BaseFixture {}; // to disambiguate between {} == 0 and {} == List{0} // Also, see note about compiler issues when declaring nested // empty lists in lists_column_wrapper documentation template <typename T> using LCW = cudf::test::lists_column_wrapper<T, int32_t>; TYPED_TEST(GatherTestListTyped, Gather) { using T = TypeParam; // List<T> LCW<T> list{{1, 2, 3, 4}, {5}, {6, 7}, {8, 9, 10}}; cudf::test::fixed_width_column_wrapper<int> gather_map{0, 2}; cudf::table_view source_table({list}); auto results = cudf::gather(source_table, gather_map); LCW<T> expected{{1, 2, 3, 4}, {6, 7}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view().column(0), expected); } TYPED_TEST(GatherTestListTyped, GatherNothing) { using T = TypeParam; // List<T> { LCW<T> list{{1, 2, 3, 4}, {5}, {6, 7}, {8, 9, 10}}; cudf::test::fixed_width_column_wrapper<int> gather_map{}; cudf::table_view source_table({list}); auto results = cudf::gather(source_table, gather_map); LCW<T> expected; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view().column(0), expected); } // List<T> { cudf::test::lists_column_wrapper<int> list{{{{1, 2, 3, 4}, {5}}}, {{{6, 7}, {8, 9, 10}}}}; cudf::test::fixed_width_column_wrapper<int> gather_map{}; cudf::table_view source_table({list}); auto result = cudf::gather(source_table, gather_map); // the result should preserve the full List<List<List<int>>> hierarchy // even though it is empty past the first level cudf::lists_column_view lcv(result->view().column(0)); EXPECT_EQ(lcv.size(), 0); EXPECT_EQ(lcv.child().type().id(), cudf::type_id::LIST); EXPECT_EQ(lcv.child().size(), 0); EXPECT_EQ(cudf::lists_column_view(lcv.child()).child().type().id(), cudf::type_id::LIST); EXPECT_EQ(cudf::lists_column_view(lcv.child()).child().size(), 0); EXPECT_EQ( cudf::lists_column_view(cudf::lists_column_view(lcv.child()).child()).child().type().id(), cudf::type_id::INT32); EXPECT_EQ(cudf::lists_column_view(cudf::lists_column_view(lcv.child()).child()).child().size(), 0); } } TYPED_TEST(GatherTestListTyped, GatherNulls) { using T = TypeParam; auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); // List<T> LCW<T> list{{{1, 2, 3, 4}, valids}, {5}, {{6, 7}, valids}, {{8, 9, 10}, valids}}; cudf::test::fixed_width_column_wrapper<int> gather_map{0, 2}; cudf::table_view source_table({list}); auto results = cudf::gather(source_table, gather_map); LCW<T> expected{{{1, 2, 3, 4}, valids}, {{6, 7}, valids}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view().column(0), expected); } TYPED_TEST(GatherTestListTyped, GatherNested) { using T = TypeParam; // List<List<T>> { LCW<T> list{{{2, 3}, {4, 5}}, {{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}, {{15, 16}, {17, 18}, {17, 18}, {17, 18}, {17, 18}}}; cudf::test::fixed_width_column_wrapper<int> gather_map{0, 2}; cudf::table_view source_table({list}); auto results = cudf::gather(source_table, gather_map); LCW<T> expected{{{2, 3}, {4, 5}}, {{15, 16}, {17, 18}, {17, 18}, {17, 18}, {17, 18}}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view().column(0), expected); } // List<List<List<T>>> { LCW<T> list{{{{2, 3}, {4, 5}}, {{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}}, {{{15, 16}, {17, 18}, {17, 18}, {17, 18}, {17, 18}}}, {{LCW<T>{0}}}, {{{10}, {20, 30, 40, 50}, {60, 70, 80}}, {{0, 1, 3}, {5}}, {{11, 12, 13, 14, 15}, {16, 17}, {0}}}, {{{10, 20}}, {LCW<T>{30}}, {{40, 50}, {60, 70, 80}}}}; cudf::test::fixed_width_column_wrapper<int> gather_map{1, 2, 4}; cudf::table_view source_table({list}); auto results = cudf::gather(source_table, gather_map); LCW<T> expected{{{{15, 16}, {17, 18}, {17, 18}, {17, 18}, {17, 18}}}, {{LCW<T>{0}}}, {{{10, 20}}, {LCW<T>{30}}, {{40, 50}, {60, 70, 80}}}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view().column(0), expected); } } TYPED_TEST(GatherTestListTyped, GatherOutOfOrder) { using T = TypeParam; // List<List<T>> { LCW<T> list{{{2, 3}, {4, 5}}, {{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}, {{15, 16}, {17, 18}, {17, 18}, {17, 18}, {17, 18}}}; cudf::test::fixed_width_column_wrapper<int> gather_map{1, 2, 0}; cudf::table_view source_table({list}); auto results = cudf::gather(source_table, gather_map); LCW<T> expected{{{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}, {{15, 16}, {17, 18}, {17, 18}, {17, 18}, {17, 18}}, {{2, 3}, {4, 5}}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view().column(0), expected); } } TYPED_TEST(GatherTestListTyped, GatherNestedNulls) { using T = TypeParam; auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); // List<List<T>> { LCW<T> list{{{{2, 3}, valids}, {4, 5}}, {{{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}, valids}, {{15, 16}, {17, 18}, {17, 18}, {17, 18}, {17, 18}}, {{{{25, 26}, valids}, {27, 28}, {{29, 30}, valids}, {31, 32}, {33, 34}}, valids}}; cudf::test::fixed_width_column_wrapper<int> gather_map{0, 1, 3}; cudf::table_view source_table({list}); auto results = cudf::gather(source_table, gather_map); LCW<T> expected{ {{{2, 3}, valids}, {4, 5}}, {{{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}, valids}, {{{{25, 26}, valids}, {27, 28}, {{29, 30}, valids}, {31, 32}, {33, 34}}, valids}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view().column(0), expected); } // List<List<List<T>>> { LCW<T> list{{{{2, 3}, {4, 5}}, {{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}}, {{{15, 16}, {{27, 28}, valids}, {{37, 38}, valids}, {47, 48}, {57, 58}}}, {{LCW<T>{0}}}, {{{10}, {20, 30, 40, 50}, {60, 70, 80}}, {{0, 1, 3}, {5}}, {{11, 12, 13, 14, 15}, {16, 17}, {0}}}, {{{{{10, 20}, valids}}, {LCW<T>{30}}, {{40, 50}, {60, 70, 80}}}, valids}}; cudf::test::fixed_width_column_wrapper<int> gather_map{1, 2, 4}; cudf::table_view source_table({list}); auto results = cudf::gather(source_table, gather_map); LCW<T> expected{{{{15, 16}, {{27, 28}, valids}, {{37, 38}, valids}, {47, 48}, {57, 58}}}, {{LCW<T>{0}}}, {{{{{10, 20}, valids}}, {LCW<T>{30}}, {{40, 50}, {60, 70, 80}}}, valids}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view().column(0), expected); } } TYPED_TEST(GatherTestListTyped, GatherNestedWithEmpties) { using T = TypeParam; LCW<T> list{{{2, 3}, LCW<T>{}}, {{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}, {LCW<T>{}}}; cudf::test::fixed_width_column_wrapper<int> gather_map{0, 2}; cudf::table_view source_table({list}); auto results = cudf::gather(source_table, gather_map); LCW<T> expected{{{2, 3}, LCW<T>{}}, {LCW<T>{}}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view().column(0), expected); } TYPED_TEST(GatherTestListTyped, GatherDetailInvalidIndex) { using T = TypeParam; // List<List<T>> { LCW<T> list{{{2, 3}, {4, 5}}, {{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}, {{15, 16}, {17, 18}, {17, 18}, {17, 18}, {17, 18}}}; cudf::test::fixed_width_column_wrapper<int> gather_map{0, 15, 16, 2}; cudf::table_view source_table({list}); auto results = cudf::gather(source_table, gather_map, cudf::out_of_bounds_policy::NULLIFY); std::vector<int32_t> expected_validity{1, 0, 0, 1}; LCW<T> expected{{{{2, 3}, {4, 5}}, {LCW<T>{}}, {LCW<T>{}}, {{15, 16}, {17, 18}, {17, 18}, {17, 18}, {17, 18}}}, expected_validity.begin()}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view().column(0), expected); } } TEST_F(GatherTestList, GatherIncompleteHierarchies) { using LCW = cudf::test::lists_column_wrapper<int32_t>; { // List<List<List<int>, but rows 1 and 2 are empty at the very top. // We expect to get back a "full" hierarchy of type List<List<List<int>> anyway. cudf::test::lists_column_wrapper<int32_t> list{{{{1, 2}}}, LCW{}, LCW{}}; cudf::table_view source_table({list}); cudf::test::fixed_width_column_wrapper<int32_t> row1_map{1}; auto result = cudf::gather(source_table, row1_map); // the result should preserve the full List<List<List<int>>> hierarchy // even though it is empty past the first level cudf::lists_column_view lcv(result->view().column(0)); EXPECT_EQ(lcv.size(), 1); EXPECT_EQ(lcv.child().type().id(), cudf::type_id::LIST); EXPECT_EQ(lcv.child().size(), 0); EXPECT_EQ(cudf::lists_column_view(lcv.child()).child().type().id(), cudf::type_id::LIST); EXPECT_EQ(cudf::lists_column_view(lcv.child()).child().size(), 0); EXPECT_EQ( cudf::lists_column_view(cudf::lists_column_view(lcv.child()).child()).child().type().id(), cudf::type_id::INT32); EXPECT_EQ(cudf::lists_column_view(cudf::lists_column_view(lcv.child()).child()).child().size(), 0); } { // List<List<List<int>, gathering nothing. // We expect to get back a "full" hierarchy of type List<List<List<int>> anyway. cudf::test::lists_column_wrapper<int32_t> list{{{{1, 2}}}, LCW{}}; cudf::table_view source_table({list}); cudf::test::fixed_width_column_wrapper<int32_t> empty_map{}; auto result = cudf::gather(source_table, empty_map); // the result should preserve the full List<List<List<int>>> hierarchy // even though it is empty past the first level cudf::lists_column_view lcv(result->view().column(0)); EXPECT_EQ(lcv.size(), 0); EXPECT_EQ(lcv.child().type().id(), cudf::type_id::LIST); EXPECT_EQ(lcv.child().size(), 0); EXPECT_EQ(cudf::lists_column_view(lcv.child()).child().type().id(), cudf::type_id::LIST); EXPECT_EQ(cudf::lists_column_view(lcv.child()).child().size(), 0); EXPECT_EQ( cudf::lists_column_view(cudf::lists_column_view(lcv.child()).child()).child().type().id(), cudf::type_id::INT32); EXPECT_EQ(cudf::lists_column_view(cudf::lists_column_view(lcv.child()).child()).child().size(), 0); } } TYPED_TEST(GatherTestListTyped, GatherSliced) { using T = TypeParam; { LCW<T> a{ {{1, 1, 1}, {2, 2}, {3, 3}}, {{4, 4, 4}, {5, 5}, {6, 6}}, {{7, 7, 7}, {8, 8}, {9, 9}}, {{10, 10, 10}, {11, 11}, {12, 12}}, {{20, 20, 20, 20}, {25}}, {{30, 30, 30, 30}, {40}}, {{50, 50, 50, 50}, {6, 13}}, {{70, 70, 70, 70}, {80}}, }; auto split_a = cudf::split(a, {3}); cudf::table_view tbl0({split_a[0]}); cudf::table_view tbl1({split_a[1]}); auto result0 = cudf::gather(tbl0, cudf::test::fixed_width_column_wrapper<int>{1, 2}); LCW<T> expected0{ {{4, 4, 4}, {5, 5}, {6, 6}}, {{7, 7, 7}, {8, 8}, {9, 9}}, }; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected0, result0->get_column(0).view()); auto result1 = cudf::gather(tbl1, cudf::test::fixed_width_column_wrapper<int>{0, 3}); LCW<T> expected1{ {{10, 10, 10}, {11, 11}, {12, 12}}, {{50, 50, 50, 50}, {6, 13}}, }; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected1, result1->get_column(0).view()); } auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); // List<List<List<T>>> { LCW<T> list{ // slice 0 {{{2, 3}, {4, 5}}, {{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}}, {{{15, 16}, {{27, 28}, valids}, {{37, 38}, valids}, {47, 48}, {57, 58}}, {{11, 12}, {{42, 43, 44}, valids}, {{77, 78}, valids}}}, // slice 1 {{LCW<T>{0}}}, {{{10}, {20, 30, 40, 50}, {60, 70, 80}}, {{0, 1, 3}, {5}}, {{11, 12, 13, 14, 15}, {16, 17}, {0}}}, {{{{1, 6}, {60, 70, 80, 100}}, {{10, 11, 13}, {15}}, {{11, 12, 13, 14, 15}}}, valids}, // slice 2 {{{{{10, 20}, valids}}, {LCW<T>{30}}, {{40, 50}, {60, 70, 80}}}, valids}, {{{{10, 20, 30}}, {LCW<T>{30}}, {{{20, 30}, valids}, {62, 72, 82}}}, valids}}; auto sliced = cudf::slice(list, {0, 1, 2, 5, 5, 7}); // gather from slice 0 { cudf::table_view tbl({sliced[0]}); cudf::test::fixed_width_column_wrapper<int> map{0}; auto result = cudf::gather(tbl, map); LCW<T> expected{{{{2, 3}, {4, 5}}, {{6, 7, 8}, {9, 10, 11}, {12, 13, 14}}}}; CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result->get_column(0).view()); } // gather from slice 1 { cudf::table_view tbl({sliced[1]}); cudf::test::fixed_width_column_wrapper<int> map{1, 2, 0, 1}; auto result = cudf::gather(tbl, map); LCW<T> expected{ {{{10}, {20, 30, 40, 50}, {60, 70, 80}}, {{0, 1, 3}, {5}}, {{11, 12, 13, 14, 15}, {16, 17}, {0}}}, {{{{1, 6}, {60, 70, 80, 100}}, {{10, 11, 13}, {15}}, {{11, 12, 13, 14, 15}}}, valids}, {{LCW<T>{0}}}, {{{10}, {20, 30, 40, 50}, {60, 70, 80}}, {{0, 1, 3}, {5}}, {{11, 12, 13, 14, 15}, {16, 17}, {0}}}, }; CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result->get_column(0).view()); } // gather from slice 2 { cudf::table_view tbl({sliced[2]}); cudf::test::fixed_width_column_wrapper<int> map{1, 0, 0, 1, 1, 0}; auto result = cudf::gather(tbl, map); LCW<T> expected{{{{{10, 20, 30}}, {LCW<T>{30}}, {{{20, 30}, valids}, {62, 72, 82}}}, valids}, {{{{{10, 20}, valids}}, {LCW<T>{30}}, {{40, 50}, {60, 70, 80}}}, valids}, {{{{{10, 20}, valids}}, {LCW<T>{30}}, {{40, 50}, {60, 70, 80}}}, valids}, {{{{10, 20, 30}}, {LCW<T>{30}}, {{{20, 30}, valids}, {62, 72, 82}}}, valids}, {{{{10, 20, 30}}, {LCW<T>{30}}, {{{20, 30}, valids}, {62, 72, 82}}}, valids}, {{{{{10, 20}, valids}}, {LCW<T>{30}}, {{40, 50}, {60, 70, 80}}}, valids}}; CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result->get_column(0).view()); } } }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/gather_struct_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/column/column_factories.hpp> #include <cudf/copying.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/lists/lists_column_view.hpp> #include <cudf/null_mask.hpp> #include <cudf/structs/structs_column_view.hpp> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> #include <cudf/types.hpp> #include <cudf/utilities/error.hpp> #include <rmm/device_buffer.hpp> #include <memory> using vector_of_columns = std::vector<std::unique_ptr<cudf::column>>; using gather_map_t = std::vector<cudf::size_type>; using offsets = cudf::test::fixed_width_column_wrapper<int32_t>; using structs = cudf::test::structs_column_wrapper; using strings = cudf::test::strings_column_wrapper; using bools = cudf::test::fixed_width_column_wrapper<bool, int32_t>; // Test validity iterator utilities. using cudf::test::iterators::no_nulls; using cudf::test::iterators::null_at; using cudf::test::iterators::nulls_at; template <typename T> using numerics = cudf::test::fixed_width_column_wrapper<T, int32_t>; template <typename T> using lists = cudf::test::lists_column_wrapper<T, int32_t>; auto constexpr null_index = std::numeric_limits<cudf::size_type>::max(); struct StructGatherTest : public cudf::test::BaseFixture {}; template <typename T> struct TypedStructGatherTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(TypedStructGatherTest, cudf::test::FixedWidthTypes); namespace { template <typename ElementTo, typename SourceElementT = ElementTo> struct column_wrapper_constructor { template <typename ValueIter, typename ValidityIter> auto operator()(ValueIter begin, ValueIter end, ValidityIter validity_begin) const { return cudf::test::fixed_width_column_wrapper<ElementTo, SourceElementT>{ begin, end, validity_begin}; } }; template <> struct column_wrapper_constructor<std::string, std::string> { template <typename ValueIter, typename ValidityIter> cudf::test::strings_column_wrapper operator()(ValueIter begin, ValueIter end, ValidityIter validity_begin) const { return cudf::test::strings_column_wrapper{begin, end, validity_begin}; } }; template <typename ElementTo, typename SourceElementT = ElementTo, typename InputValidityIter = decltype(null_at(0)), typename StructValidityIter = InputValidityIter> auto get_expected_column(std::vector<SourceElementT> const& input_values, InputValidityIter input_validity, StructValidityIter struct_validity, std::vector<int32_t> const& gather_map) { auto is_valid = // Validity predicate. [&input_values, &input_validity, &struct_validity, &gather_map](auto gather_index) { assert( (gather_index >= 0 && gather_index < static_cast<cudf::size_type>(gather_map.size())) && "Gather-index out of range."); auto i = gather_map[gather_index]; // Index into input_values. return (i >= 0 && i < static_cast<int>(input_values.size())) && struct_validity[i] && input_validity[i]; }; auto expected_row_count = gather_map.size(); auto gather_iter = cudf::detail::make_counting_transform_iterator( 0, [is_valid, &input_values, &gather_map](auto i) { return is_valid(i) ? input_values[gather_map[i]] : SourceElementT{}; }); return column_wrapper_constructor<ElementTo, SourceElementT>()( gather_iter, gather_iter + expected_row_count, cudf::detail::make_counting_transform_iterator(0, is_valid)); } auto do_gather(cudf::column_view const& input, gather_map_t const& gather_map) { auto result = cudf::gather(cudf::table_view{{input}}, offsets(gather_map.begin(), gather_map.end()), cudf::out_of_bounds_policy::NULLIFY); return std::move(result->release()[0]); } } // namespace TYPED_TEST(TypedStructGatherTest, TestSimpleStructGather) { // Testing gather() on struct<string, numeric, bool>. // 1. String "names" column. auto const names = std::vector<std::string>{"Vimes", "Carrot", "Angua", "Cheery", "Detritus", "Slant"}; auto const names_validity = no_nulls(); // 2. Numeric "ages" column. auto const ages = std::vector<int32_t>{5, 10, 15, 20, 25, 30}; auto const ages_validity = null_at(4); // 3. Boolean "is_human" column. auto const is_human = {true, true, false, false, false, false}; auto const is_human_validity = null_at(3); // Assemble struct column. auto const struct_validity = null_at(5); auto const struct_column = [&] { auto names_member = ::strings(names.begin(), names.end(), names_validity); auto ages_member = ::numerics<TypeParam>(ages.begin(), ages.end(), ages_validity); auto is_human_member = ::bools(is_human.begin(), is_human.end(), is_human_validity); return structs{{names_member, ages_member, is_human_member}, struct_validity}; }(); // Gather to new struct column. auto const gather_map = gather_map_t{null_index, 4, 3, 2, 1}; auto const output = do_gather(struct_column, gather_map); auto const expected_output = [&] { auto names_member = get_expected_column<std::string>(names, names_validity, struct_validity, gather_map); auto ages_member = get_expected_column<TypeParam, int32_t>(ages, ages_validity, struct_validity, gather_map); auto is_human_member = get_expected_column<bool>(std::vector<bool>(is_human.begin(), is_human.end()), is_human_validity, struct_validity, gather_map); return structs{{names_member, ages_member, is_human_member}, null_at(0)}; }(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(output->view(), expected_output); } TYPED_TEST(TypedStructGatherTest, TestSlicedStructsColumnGatherNoNulls) { auto const structs_original = [] { auto child1 = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; auto child2 = cudf::test::strings_column_wrapper{ "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"}; return cudf::test::structs_column_wrapper{{child1, child2}}; }(); auto const expected = [] { auto child1 = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>{6, 10, 8}; auto child2 = cudf::test::strings_column_wrapper{"Six", "Ten", "Eight"}; return cudf::test::structs_column_wrapper{{child1, child2}}; }(); auto const structs = cudf::slice(structs_original, {4, 10})[0]; auto const gather_map = cudf::test::fixed_width_column_wrapper<int32_t>{1, 5, 3}; auto const result = cudf::gather(cudf::table_view{{structs}}, gather_map)->get_column(0); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.view(), expected); } TYPED_TEST(TypedStructGatherTest, TestSlicedStructsColumnGatherWithNulls) { auto constexpr null = int32_t{0}; // null at child auto constexpr XXX = int32_t{0}; // null at parent auto const structs_original = [] { auto child1 = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>{ {null, XXX, 3, null, null, 6, XXX, null, null, 10}, nulls_at({0, 3, 4, 7, 8})}; auto child2 = cudf::test::strings_column_wrapper{{"One", "" /*NULL at both parent and child*/, "Three", "" /*NULL*/, "Five", "" /*NULL*/, "" /*NULL at parent*/, "" /*NULL*/, "Nine", "" /*NULL*/}, nulls_at({1, 3, 5, 7, 9})}; return cudf::test::structs_column_wrapper{{child1, child2}, nulls_at({1, 6})}; }(); auto const expected = [] { auto child1 = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>{{6, 10, null, XXX}, null_at(2)}; auto child2 = cudf::test::strings_column_wrapper{{ "" /*NULL*/, "" /*NULL*/, "Nine", "" /*NULL at parent*/ }, nulls_at({0, 1})}; return cudf::test::structs_column_wrapper{{child1, child2}, null_at(3)}; }(); auto const structs = cudf::slice(structs_original, {4, 10})[0]; auto const gather_map = cudf::test::fixed_width_column_wrapper<int32_t>{1, 5, 4, 2}; auto const result = cudf::gather(cudf::table_view{{structs}}, gather_map)->get_column(0); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.view(), expected); } TYPED_TEST(TypedStructGatherTest, TestNullifyOnNonNullInput) { // Test that the null masks of the struct output (and its children) are set correctly, // for an input struct column whose members are not nullable. // 1. String "names" column. auto const names = std::vector<std::string>{"Vimes", "Carrot", "Angua", "Cheery", "Detritus", "Slant"}; // 2. Numeric "ages" column. auto const ages = std::vector<int32_t>{5, 10, 15, 20, 25, 30}; // 3. Boolean "is_human" column. auto const is_human = {true, true, false, false, false, false}; // Assemble struct column. auto const struct_column = [&] { auto names_member = ::strings(names.begin(), names.end()); auto ages_member = ::numerics<TypeParam>(ages.begin(), ages.end()); auto is_human_member = ::bools(is_human.begin(), is_human.end()); return structs({names_member, ages_member, is_human_member}); }(); // Gather to new struct column. auto const gather_map = gather_map_t{null_index, 4, 3, 2, 1}; auto const output = do_gather(struct_column, gather_map); auto const expected_output = [&] { auto names_member = get_expected_column<std::string>(names, no_nulls(), no_nulls(), gather_map); auto ages_member = get_expected_column<TypeParam, int32_t>(ages, no_nulls(), no_nulls(), gather_map); auto is_human_member = get_expected_column<bool>( std::vector<bool>(is_human.begin(), is_human.end()), no_nulls(), no_nulls(), gather_map); return cudf::test::structs_column_wrapper{{names_member, ages_member, is_human_member}, null_at(0)}; }(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(output->view(), expected_output); } TYPED_TEST(TypedStructGatherTest, TestGatherStructOfLists) { // Testing gather() on struct<list<numeric>> auto lists_column_exemplar = [] { return lists<TypeParam>{ {{5}, {10, 15}, {20, 25, 30}, {35, 40, 45, 50}, {55, 60, 65}, {70, 75}, {80}, {}, {}}, nulls_at({0, 3, 6, 9})}; }; // Assemble struct column. auto const structs_column = [&] { auto lists_column = lists_column_exemplar(); return cudf::test::structs_column_wrapper{{lists_column}}; }(); // Gather to new struct column. auto const gather_map = gather_map_t{null_index, 4, 3, 2, 1, 7, 3}; auto const gathered_structs = do_gather(structs_column, gather_map); // Verify that the gathered struct column's list member presents as if // it had itself been gathered individually. auto const expected_gathered_list_column = [&] { auto const list_column_before_gathering = lists_column_exemplar(); return do_gather(list_column_before_gathering, gather_map); }(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_gathered_list_column->view(), gathered_structs->view().child(0)); } TYPED_TEST(TypedStructGatherTest, TestGatherStructOfListsOfLists) { // Testing gather() on struct<list<list<numeric>>> auto const lists_column_exemplar = []() { return lists<TypeParam>{{{{5, 5}}, {{10, 15}}, {{20, 25}, {30}}, {{35, 40}, {45, 50}}, {{55}, {60, 65}}, {{70, 75}}, {{80, 80}}, {}, {}}, nulls_at({0, 3, 6, 9})}; }; auto const structs_column = [&] { auto lists_column = lists_column_exemplar(); return cudf::test::structs_column_wrapper{{lists_column}}; }(); // Gather to new struct column. auto const gather_map = gather_map_t{null_index, 4, 3, 2, 1, 7, 3}; auto const gathered_structs = do_gather(structs_column, gather_map); // Verify that the gathered struct column's list member presents as if // it had itself been gathered individually. auto const expected_gathered_list_column = [&] { auto const list_column_before_gathering = lists_column_exemplar(); return do_gather(list_column_before_gathering, gather_map); }(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_gathered_list_column->view(), gathered_structs->view().child(0)); } TYPED_TEST(TypedStructGatherTest, TestGatherStructOfStructs) { // Testing gather() on struct<struct<numeric>> auto const numeric_column_exemplar = []() { return numerics<TypeParam>{{5, 10, 15, 20, 25, 30, 35, 45, 50, 55, 60, 65, 70, 75}, nulls_at({0, 3, 6, 9, 12, 15})}; }; auto const struct_of_structs_column = [&] { auto numeric_column = numeric_column_exemplar(); auto structs_column = cudf::test::structs_column_wrapper{{numeric_column}}; return cudf::test::structs_column_wrapper{{structs_column}}; }(); // Gather to new struct column. auto const gather_map = gather_map_t{null_index, 4, 3, 2, 1, 7, 3}; auto const gathered_structs = do_gather(struct_of_structs_column, gather_map); // Verify that the underlying numeric column presents as if // it had itself been gathered individually. auto const expected_gathered_column = [&] { auto const numeric_column_before_gathering = numeric_column_exemplar(); return do_gather(numeric_column_before_gathering, gather_map); }(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_gathered_column->view(), gathered_structs->view().child(0).child(0)); } TYPED_TEST(TypedStructGatherTest, TestGatherStructOfListOfStructs) { // Testing gather() on struct<list<struct<numeric>>> auto const struct_of_list_of_structs = [&] { auto numeric_column = numerics<TypeParam>{{5, 10, 15, 20, 25, 30, 35, 45, 50, 55, 60, 65, 70, 75}}; auto structs_column = structs{{numeric_column}}.release(); auto list_of_structs_column = cudf::make_lists_column( 7, offsets{0, 2, 4, 6, 8, 10, 12, 14}.release(), std::move(structs_column), 0, {}); std::vector<std::unique_ptr<cudf::column>> vector_of_columns; vector_of_columns.push_back(std::move(list_of_structs_column)); return structs{std::move(vector_of_columns)}; }(); // Gather to new struct column. auto const gather_map = gather_map_t{null_index, 4, 3, 2, 1}; auto const gathered_structs = do_gather(struct_of_list_of_structs, gather_map); // Construct expected gather result. auto expected_gather_result = [&] { auto expected_numeric_col = numerics<TypeParam>{{70, 75, 50, 55, 35, 45, 25, 30, 15, 20}}; auto expected_struct_col = structs{{expected_numeric_col}}.release(); auto expected_list_of_structs_column = cudf::make_lists_column( 5, offsets{0, 2, 4, 6, 8, 10}.release(), std::move(expected_struct_col), 0, {}); std::vector<std::unique_ptr<cudf::column>> expected_vector_of_columns; expected_vector_of_columns.push_back(std::move(expected_list_of_structs_column)); return structs{std::move(expected_vector_of_columns), {0, 1, 1, 1, 1}}; }(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_gather_result, gathered_structs->view()); } TYPED_TEST(TypedStructGatherTest, TestGatherStructOfStructsWithValidity) { // Testing gather() on struct<struct<numeric>> using validity_iter_t = decltype(nulls_at({0})); // Factory to construct numeric column with configurable null-mask. auto const numeric_column_exemplar = [](validity_iter_t validity) { return numerics<TypeParam>{{5, 10, 15, 20, 25, 30, 35, 45, 50, 55, 60, 65, 70, 75}, validity}; }; // Construct struct-of-struct-of-numerics. auto struct_of_structs_column = [&] { // Every 3rd element is null. auto numeric_column = numeric_column_exemplar(nulls_at({0, 3, 6, 9, 12, 15})); // 12th element is null. auto structs_column = cudf::test::structs_column_wrapper{{numeric_column}, nulls_at({11})}; return cudf::test::structs_column_wrapper{{structs_column}}; }(); // Gather to new struct column. auto const gather_map = gather_map_t{null_index, 4, 3, 2, 1, 7, 3}; auto const gathered_structs = do_gather(struct_of_structs_column, gather_map); // Verify that the underlying numeric column presents as if // it had itself been gathered individually. auto const expected_gathered_column = [&] { // Every 3rd element *and* the 12th element are null. auto const final_validity = nulls_at({0, 3, 6, 9, 11, 12, 15}); auto const numeric_column_before_gathering = numeric_column_exemplar(final_validity); return do_gather(numeric_column_before_gathering, gather_map); }(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_gathered_column->view(), gathered_structs->view().child(0).child(0)); } TYPED_TEST(TypedStructGatherTest, TestEmptyGather) { auto const struct_column = [&] { auto ages = numerics<TypeParam>{{5, 10, 15, 20, 25, 30}, null_at(4)}; return cudf::test::structs_column_wrapper{{ages}, null_at(5)}; }(); auto const empty_gather_map = gather_map_t{}; auto const gathered_structs = do_gather(struct_column, empty_gather_map); // Expect empty struct column gathered. auto const expected_empty_column = [&] { auto expected_empty_numerics = numerics<TypeParam>{}; return cudf::test::structs_column_wrapper{{expected_empty_numerics}}; }(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_empty_column, gathered_structs->view()); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/get_value_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_list_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/column/column_factories.hpp> #include <cudf/concatenate.hpp> #include <cudf/copying.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/dictionary/dictionary_factories.hpp> #include <cudf/dictionary/update_keys.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/types.hpp> #include <thrust/iterator/counting_iterator.h> using namespace cudf::test::iterators; template <typename T> struct FixedWidthGetValueTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(FixedWidthGetValueTest, cudf::test::FixedWidthTypesWithoutFixedPoint); TYPED_TEST(FixedWidthGetValueTest, BasicGet) { cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> col({9, 8, 7, 6}); auto s = cudf::get_element(col, 0); using ScalarType = cudf::scalar_type_t<TypeParam>; auto typed_s = static_cast<ScalarType const*>(s.get()); EXPECT_TRUE(s->is_valid()); EXPECT_EQ(cudf::test::make_type_param_scalar<TypeParam>(9), typed_s->value()); } TYPED_TEST(FixedWidthGetValueTest, GetFromNullable) { cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> col({9, 8, 7, 6}, {0, 1, 0, 1}); auto s = cudf::get_element(col, 1); using ScalarType = cudf::scalar_type_t<TypeParam>; auto typed_s = static_cast<ScalarType const*>(s.get()); EXPECT_TRUE(s->is_valid()); EXPECT_EQ(cudf::test::make_type_param_scalar<TypeParam>(8), typed_s->value()); } TYPED_TEST(FixedWidthGetValueTest, GetNull) { cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> col({9, 8, 7, 6}, {0, 1, 0, 1}); auto s = cudf::get_element(col, 2); EXPECT_FALSE(s->is_valid()); } TYPED_TEST(FixedWidthGetValueTest, IndexOutOfBounds) { cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> col({9, 8, 7, 6}, {0, 1, 0, 1}); // Test for out of bounds indexes in both directions. EXPECT_THROW(cudf::get_element(col, -1), cudf::logic_error); EXPECT_THROW(cudf::get_element(col, 4), cudf::logic_error); } struct StringGetValueTest : public cudf::test::BaseFixture {}; TEST_F(StringGetValueTest, BasicGet) { cudf::test::strings_column_wrapper col{"this", "is", "a", "test"}; auto s = cudf::get_element(col, 3); auto typed_s = static_cast<cudf::string_scalar const*>(s.get()); EXPECT_TRUE(s->is_valid()); EXPECT_EQ("test", typed_s->to_string()); } TEST_F(StringGetValueTest, GetEmpty) { cudf::test::strings_column_wrapper col{"this", "is", "", "test"}; auto s = cudf::get_element(col, 2); auto typed_s = static_cast<cudf::string_scalar const*>(s.get()); EXPECT_TRUE(s->is_valid()); EXPECT_EQ("", typed_s->to_string()); } TEST_F(StringGetValueTest, GetFromNullable) { cudf::test::strings_column_wrapper col({"this", "is", "a", "test"}, {0, 1, 0, 1}); auto s = cudf::get_element(col, 1); auto typed_s = static_cast<cudf::string_scalar const*>(s.get()); EXPECT_TRUE(s->is_valid()); EXPECT_EQ("is", typed_s->to_string()); } TEST_F(StringGetValueTest, GetNull) { cudf::test::strings_column_wrapper col({"this", "is", "a", "test"}, {0, 1, 0, 1}); auto s = cudf::get_element(col, 2); EXPECT_FALSE(s->is_valid()); } template <typename T> struct DictionaryGetValueTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(DictionaryGetValueTest, cudf::test::FixedWidthTypesWithoutFixedPoint); TYPED_TEST(DictionaryGetValueTest, BasicGet) { cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> keys({6, 7, 8, 9}); cudf::test::fixed_width_column_wrapper<uint32_t> indices{0, 0, 1, 2, 1, 3, 3, 2}; auto col = cudf::make_dictionary_column(keys, indices); auto s = cudf::get_element(*col, 2); using ScalarType = cudf::scalar_type_t<TypeParam>; auto typed_s = static_cast<ScalarType const*>(s.get()); EXPECT_TRUE(s->is_valid()); EXPECT_EQ(cudf::test::make_type_param_scalar<TypeParam>(7), typed_s->value()); } TYPED_TEST(DictionaryGetValueTest, GetFromNullable) { cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> keys({6, 7, 8, 9}); cudf::test::fixed_width_column_wrapper<uint32_t> indices({0, 0, 1, 2, 1, 3, 3, 2}, {0, 1, 0, 1, 1, 1, 0, 0}); auto col = cudf::make_dictionary_column(keys, indices); auto s = cudf::get_element(*col, 3); using ScalarType = cudf::scalar_type_t<TypeParam>; auto typed_s = static_cast<ScalarType const*>(s.get()); EXPECT_TRUE(s->is_valid()); EXPECT_EQ(cudf::test::make_type_param_scalar<TypeParam>(8), typed_s->value()); } TYPED_TEST(DictionaryGetValueTest, GetNull) { cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> keys({6, 7, 8, 9}); cudf::test::fixed_width_column_wrapper<uint32_t> indices({0, 0, 1, 2, 1, 3, 3, 2}, {0, 1, 0, 1, 1, 1, 0, 0}); auto col = cudf::make_dictionary_column(keys, indices); auto s = cudf::get_element(*col, 2); EXPECT_FALSE(s->is_valid()); } /* * Lists test grid: * Dim1 nestedness: {Nested, Non-nested} * Dim2 validity, emptiness: {Null element, Non-null non-empty list, Non-null empty list} * Dim3 leaf data type: {Fixed-width, string, struct} */ template <typename T> struct ListGetFixedWidthValueTest : public cudf::test::BaseFixture { auto odds_valid() { return cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2; }); } auto nth_valid(cudf::size_type x) { return cudf::detail::make_counting_transform_iterator(0, [=](auto i) { return x == i; }); } }; TYPED_TEST_SUITE(ListGetFixedWidthValueTest, cudf::test::FixedWidthTypes); TYPED_TEST(ListGetFixedWidthValueTest, NonNestedGetNonNullNonEmpty) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; LCW col{LCW({1, 2, 34}, this->odds_valid()), LCW{}, LCW{1}, LCW{}}; cudf::test::fixed_width_column_wrapper<TypeParam> expected_data({1, 2, 34}, this->odds_valid()); cudf::size_type index = 0; auto s = cudf::get_element(col, index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); EXPECT_TRUE(s->is_valid()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_data, typed_s->view()); } TYPED_TEST(ListGetFixedWidthValueTest, NonNestedGetNonNullEmpty) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; LCW col{LCW{1, 2, 34}, LCW{}, LCW{1}, LCW{}}; cudf::test::fixed_width_column_wrapper<TypeParam> expected_data{}; cudf::size_type index = 1; auto s = cudf::get_element(col, index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); EXPECT_TRUE(s->is_valid()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_data, typed_s->view()); } TYPED_TEST(ListGetFixedWidthValueTest, NonNestedGetNull) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; using FCW = cudf::test::fixed_width_column_wrapper<TypeParam>; LCW col({LCW{1, 2, 34}, LCW{}, LCW{1}, LCW{}}, this->odds_valid()); cudf::size_type index = 2; auto s = cudf::get_element(col, index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); EXPECT_FALSE(s->is_valid()); // Test preserve column hierarchy CUDF_TEST_EXPECT_COLUMNS_EQUAL(typed_s->view(), FCW{}); } TYPED_TEST(ListGetFixedWidthValueTest, NestedGetNonNullNonEmpty) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; // clang-format off LCW col{ LCW{LCW{1, 2}, LCW{34}}, LCW{}, LCW{LCW{1}}, LCW{LCW{42}, LCW{10}} }; // clang-format on LCW expected_data{LCW{42}, LCW{10}}; cudf::size_type index = 3; auto s = cudf::get_element(col, index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); EXPECT_TRUE(s->is_valid()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_data, typed_s->view()); } TYPED_TEST(ListGetFixedWidthValueTest, NestedGetNonNullNonEmptyPreserveNull) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; std::vector<cudf::valid_type> valid{0, 1, 1}; // clang-format off LCW col{ LCW{LCW{1, 2}, LCW{34}}, LCW{}, LCW{LCW{1}}, LCW({LCW{42}, LCW{10}, LCW({1, 3, 2}, this->nth_valid(1))}, valid.begin()) }; // clang-format on LCW expected_data({LCW{42}, LCW{10}, LCW({1, 3, 2}, this->nth_valid(1))}, valid.begin()); cudf::size_type index = 3; auto s = cudf::get_element(col, index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); EXPECT_TRUE(s->is_valid()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_data, typed_s->view()); } TYPED_TEST(ListGetFixedWidthValueTest, NestedGetNonNullEmpty) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; // clang-format off LCW col{ LCW{LCW{1, 2}, LCW{34}}, LCW{}, LCW{LCW{1}}, LCW{LCW{42}, LCW{10}} }; // clang-format on LCW expected_data{}; cudf::size_type index = 1; auto s = cudf::get_element(col, index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); EXPECT_TRUE(s->is_valid()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_data, typed_s->view()); } TYPED_TEST(ListGetFixedWidthValueTest, NestedGetNull) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; using FCW = cudf::test::fixed_width_column_wrapper<TypeParam>; using offset_t = cudf::test::fixed_width_column_wrapper<cudf::size_type>; std::vector<cudf::valid_type> valid{1, 0, 1, 0}; // clang-format off LCW col( { LCW{LCW{1, 2}, LCW{34}}, LCW{}, LCW{LCW{1}}, LCW{LCW{42}, LCW{10}} }, valid.begin()); // clang-format on cudf::size_type index = 1; auto s = cudf::get_element(col, index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); auto expected_data = cudf::make_lists_column(0, offset_t{}.release(), FCW{}.release(), 0, rmm::device_buffer{}); EXPECT_FALSE(s->is_valid()); // Test preserve column hierarchy CUDF_TEST_EXPECT_COLUMNS_EQUAL(typed_s->view(), *expected_data); } struct ListGetStringValueTest : public cudf::test::BaseFixture { auto odds_valid() { return cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2; }); } auto nth_valid(cudf::size_type x) { return cudf::detail::make_counting_transform_iterator(0, [=](auto i) { return x == i; }); } }; TEST_F(ListGetStringValueTest, NonNestedGetNonNullNonEmpty) { using LCW = cudf::test::lists_column_wrapper<cudf::string_view>; LCW col{LCW({"aaa", "Héllo"}, this->odds_valid()), LCW{}, LCW{""}, LCW{"42"}}; cudf::test::strings_column_wrapper expected_data({"aaa", "Héllo"}, this->odds_valid()); cudf::size_type index = 0; auto s = cudf::get_element(col, index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); EXPECT_TRUE(s->is_valid()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_data, typed_s->view()); } TEST_F(ListGetStringValueTest, NonNestedGetNonNullEmpty) { using LCW = cudf::test::lists_column_wrapper<cudf::string_view>; LCW col{LCW{"aaa", "Héllo"}, LCW{}, LCW{""}, LCW{"42"}}; cudf::test::strings_column_wrapper expected_data{}; cudf::size_type index = 1; auto s = cudf::get_element(col, index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); EXPECT_TRUE(s->is_valid()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_data, typed_s->view()); } TEST_F(ListGetStringValueTest, NonNestedGetNull) { using LCW = cudf::test::lists_column_wrapper<cudf::string_view>; using StringCW = cudf::test::strings_column_wrapper; std::vector<cudf::valid_type> valid{1, 0, 0, 1}; LCW col({LCW{"aaa", "Héllo"}, LCW{}, LCW{""}, LCW{"42"}}, valid.begin()); cudf::size_type index = 2; auto s = cudf::get_element(col, index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); EXPECT_FALSE(s->is_valid()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(typed_s->view(), StringCW{}); } TEST_F(ListGetStringValueTest, NestedGetNonNullNonEmpty) { using LCW = cudf::test::lists_column_wrapper<cudf::string_view>; // clang-format off LCW col{ LCW{LCW{"aaa", "Héllo"}}, LCW{}, LCW{LCW{""}, LCW({"string", "str2", "xyz"}, this->nth_valid(0))}, LCW{LCW{"42"}, LCW{"21"}} }; // clang-format on LCW expected_data{LCW{""}, LCW({"string", "str2", "xyz"}, this->nth_valid(0))}; cudf::size_type index = 2; auto s = cudf::get_element(col, index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); EXPECT_TRUE(s->is_valid()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_data, typed_s->view()); } TEST_F(ListGetStringValueTest, NestedGetNonNullNonEmptyPreserveNull) { using LCW = cudf::test::lists_column_wrapper<cudf::string_view>; std::vector<cudf::valid_type> valid{0, 1, 1}; // clang-format off LCW col{ LCW{LCW{"aaa", "Héllo"}}, LCW{}, LCW({LCW{""}, LCW{"cc"}, LCW({"string", "str2", "xyz"}, this->nth_valid(0))}, valid.begin()), LCW{LCW{"42"}, LCW{"21"}} }; // clang-format on LCW expected_data({LCW{""}, LCW{"cc"}, LCW({"string", "str2", "xyz"}, this->nth_valid(0))}, valid.begin()); cudf::size_type index = 2; auto s = cudf::get_element(col, index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); EXPECT_TRUE(s->is_valid()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_data, typed_s->view()); } TEST_F(ListGetStringValueTest, NestedGetNonNullEmpty) { using LCW = cudf::test::lists_column_wrapper<cudf::string_view>; // clang-format off LCW col{ LCW{LCW{"aaa", "Héllo"}}, LCW{LCW{""}}, LCW{LCW{"42"}, LCW{"21"}}, LCW{} }; // clang-format on LCW expected_data{}; cudf::size_type index = 3; auto s = cudf::get_element(col, index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); EXPECT_TRUE(s->is_valid()); // Relax to equivalent. `expected_data` leaf string column does not // allocate offset and byte array, but `typed_s` does. CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_data, typed_s->view()); } TEST_F(ListGetStringValueTest, NestedGetNull) { using LCW = cudf::test::lists_column_wrapper<cudf::string_view>; using offset_t = cudf::test::fixed_width_column_wrapper<cudf::size_type>; using StringCW = cudf::test::strings_column_wrapper; std::vector<cudf::valid_type> valid{0, 0, 1, 1}; // clang-format off LCW col( { LCW{LCW{"aaa", "Héllo"}}, LCW{LCW{""}}, LCW{LCW{"42"}, LCW{"21"}}, LCW{} }, valid.begin()); // clang-format on cudf::size_type index = 0; auto s = cudf::get_element(col, index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); auto expected_data = cudf::make_lists_column(0, offset_t{}.release(), StringCW{}.release(), 0, rmm::device_buffer{}); EXPECT_FALSE(s->is_valid()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected_data, typed_s->view()); } /** * @brief Some shared helper functions used by lists of structs test. */ template <typename T> struct ListGetStructValueTest : public cudf::test::BaseFixture { using SCW = cudf::test::structs_column_wrapper; using LCWinner_t = cudf::test::lists_column_wrapper<T, int32_t>; /** * @brief Create a lists column * * @note Different from `cudf::make_lists_column`, this allows setting the `null_mask` * in `initializer_list`. However this is an expensive function because it repeatedly * calls `cudf::set_null_mask` for each row. */ std::unique_ptr<cudf::column> make_test_lists_column( cudf::size_type num_lists, cudf::test::fixed_width_column_wrapper<cudf::size_type> offsets, std::unique_ptr<cudf::column> child, std::initializer_list<cudf::valid_type> null_mask) { cudf::size_type null_count = num_lists - std::accumulate(null_mask.begin(), null_mask.end(), 0); auto d_null_mask = cudf::create_null_mask( num_lists, null_count == 0 ? cudf::mask_state::UNALLOCATED : cudf::mask_state::ALL_NULL); if (null_count > 0) { std::for_each( thrust::make_counting_iterator(0), thrust::make_counting_iterator(num_lists), [&](auto i) { if (*(null_mask.begin() + i)) { cudf::set_null_mask( static_cast<cudf::bitmask_type*>(d_null_mask.data()), i, i + 1, true); } }); } return cudf::make_lists_column( num_lists, offsets.release(), std::move(child), null_count, std::move(d_null_mask)); } /** * @brief Create a structs column that contains 3 fields: int, string, List<int> */ template <typename MaskIterator> SCW make_test_structs_column(cudf::test::fixed_width_column_wrapper<T> field1, cudf::test::strings_column_wrapper field2, cudf::test::lists_column_wrapper<T, int32_t> field3, MaskIterator mask) { return SCW{{field1, field2, field3}, mask}; } /** * @brief Create a 0-length structs column */ SCW zero_length_struct() { return SCW{}; } /** * @brief Concatenate structs columns, allow specifying inputs in `initializer_list` */ std::unique_ptr<cudf::column> concat(std::initializer_list<SCW> rows) { std::vector<cudf::column_view> views; std::transform(rows.begin(), rows.end(), std::back_inserter(views), [](auto& r) { return cudf::column_view(r); }); return cudf::concatenate(views); } /** * @brief Test data setup: row 0 of structs column */ SCW row0() { // {int: 1, string: NULL, list: NULL} return this->make_test_structs_column({{1}, {1}}, cudf::test::strings_column_wrapper({"aa"}, {false}), LCWinner_t({{}}, all_nulls()), no_nulls()); } /** * @brief Test data setup: row 1 of structs column */ SCW row1() { // NULL return this->make_test_structs_column({-1}, {""}, LCWinner_t{-1}, all_nulls()); } /** * @brief Test data setup: row 2 of structs column */ SCW row2() { // {int: 3, string: "xyz", list: [3, 8, 4]} return this->make_test_structs_column({{3}, {1}}, cudf::test::strings_column_wrapper({"xyz"}, {true}), LCWinner_t({{3, 8, 4}}, no_nulls()), no_nulls()); } /** * @brief Test data setup: a 3-row structs column */ std::unique_ptr<cudf::column> leaf_data() { // 3 rows: // {int: 1, string: NULL, list: NULL} // NULL // {int: 3, string: "xyz", list: [3, 8, 4]} return this->concat({row0(), row1(), row2()}); } }; TYPED_TEST_SUITE(ListGetStructValueTest, cudf::test::FixedWidthTypes); TYPED_TEST(ListGetStructValueTest, NonNestedGetNonNullNonEmpty) { // 2-rows // [{1, NULL, NULL}, NULL] // [{3, "xyz", [3, 8, 4]}] <- cudf::get_element(1) auto list_column = this->make_test_lists_column(2, {0, 2, 3}, this->leaf_data(), {1, 1}); cudf::size_type index = 1; auto expected_data = this->row2(); auto s = cudf::get_element(list_column->view(), index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); EXPECT_TRUE(s->is_valid()); // Relax to equivalent. The nested list column in struct allocates `null_mask`. CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_data, typed_s->view()); } TYPED_TEST(ListGetStructValueTest, NonNestedGetNonNullNonEmpty2) { // 2-rows // [{1, NULL, NULL}, NULL] <- cudf::get_element(0) // [{3, "xyz", [3, 8, 4]}] auto list_column = this->make_test_lists_column(2, {0, 2, 3}, this->leaf_data(), {1, 1}); cudf::size_type index = 0; auto expected_data = this->concat({this->row0(), this->row1()}); auto s = cudf::get_element(list_column->view(), index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); EXPECT_TRUE(s->is_valid()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*expected_data, typed_s->view()); } TYPED_TEST(ListGetStructValueTest, NonNestedGetNonNullEmpty) { // 3-rows // [{1, NULL, NULL}, NULL] // [{3, "xyz", [3, 8, 4]}] // [] <- cudf::get_element(2) auto list_column = this->make_test_lists_column(3, {0, 2, 3, 3}, this->leaf_data(), {1, 1, 1}); cudf::size_type index = 2; // For well-formed list column, an empty list still holds the complete structure of // a 0-length structs column auto expected_data = this->zero_length_struct(); auto s = cudf::get_element(list_column->view(), index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); EXPECT_TRUE(s->is_valid()); // Relax to equivalent. The nested list column in struct allocates `null_mask`. CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_data, typed_s->view()); } TYPED_TEST(ListGetStructValueTest, NonNestedGetNull) { // 2-rows // NULL <- cudf::get_element(0) // [{3, "xyz", [3, 8, 4]}] using valid_t = std::vector<cudf::valid_type>; auto list_column = this->make_test_lists_column(2, {0, 2, 3}, this->leaf_data(), {0, 1}); cudf::size_type index = 0; auto s = cudf::get_element(list_column->view(), index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); auto expected_data = this->make_test_structs_column({}, {}, {}, valid_t{}.begin()); EXPECT_FALSE(s->is_valid()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(typed_s->view(), expected_data); } TYPED_TEST(ListGetStructValueTest, NestedGetNonNullNonEmpty) { // 2-rows // [[{1, NULL, NULL}, NULL], [{3, "xyz", [3, 8, 4]}]] <- cudf::get_element(0) // [] auto list_column = this->make_test_lists_column(2, {0, 2, 3}, this->leaf_data(), {1, 1}); auto expected_data = std::make_unique<cudf::column>(*list_column); auto list_column_nested = this->make_test_lists_column(2, {0, 2, 2}, std::move(list_column), {1, 1}); cudf::size_type index = 0; auto s = cudf::get_element(list_column_nested->view(), index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); EXPECT_TRUE(s->is_valid()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*expected_data, typed_s->view()); } TYPED_TEST(ListGetStructValueTest, NestedGetNonNullNonEmpty2) { // 2-rows // [[{1, NULL, NULL}, NULL]] <- cudf::get_element(0) // [[{3, "xyz", [3, 8, 4]}]] auto list_column = this->make_test_lists_column(2, {0, 2, 3}, this->leaf_data(), {1, 1}); auto list_column_nested = this->make_test_lists_column(2, {0, 1, 2}, std::move(list_column), {1, 1}); auto expected_data = this->make_test_lists_column(1, {0, 2}, this->concat({this->row0(), this->row1()}), {1}); cudf::size_type index = 0; auto s = cudf::get_element(list_column_nested->view(), index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); EXPECT_TRUE(s->is_valid()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*expected_data, typed_s->view()); } TYPED_TEST(ListGetStructValueTest, NestedGetNonNullNonEmpty3) { // 2-rows // [[{1, NULL, NULL}, NULL]] // [[{3, "xyz", [3, 8, 4]}]] <- cudf::get_element(1) auto list_column = this->make_test_lists_column(2, {0, 2, 3}, this->leaf_data(), {1, 1}); auto list_column_nested = this->make_test_lists_column(2, {0, 1, 2}, std::move(list_column), {1, 1}); auto expected_data = this->make_test_lists_column(1, {0, 1}, this->row2().release(), {1}); cudf::size_type index = 1; auto s = cudf::get_element(list_column_nested->view(), index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); EXPECT_TRUE(s->is_valid()); // Relax to equivalent. For `get_element`, the nested list column in struct // allocates `null_mask`. CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected_data, typed_s->view()); } TYPED_TEST(ListGetStructValueTest, NestedGetNonNullEmpty) { // 3-rows // [[{1, NULL, NULL}, NULL]] // [] <- cudf::get_element(1) // [[{3, "xyz", [3, 8, 4]}]] auto list_column = this->make_test_lists_column(2, {0, 2, 3}, this->leaf_data(), {1, 1}); auto list_column_nested = this->make_test_lists_column(3, {0, 1, 1, 2}, std::move(list_column), {1, 1, 1}); auto expected_data = this->make_test_lists_column(0, {0}, this->zero_length_struct().release(), {1}); cudf::size_type index = 1; auto s = cudf::get_element(list_column_nested->view(), index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); EXPECT_TRUE(s->is_valid()); // Relax to equivalent. The sliced version still has the array for fields // allocated. CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected_data, typed_s->view()); } TYPED_TEST(ListGetStructValueTest, NestedGetNull) { // 3-rows // [[{1, NULL, NULL}, NULL]] // [] // NULL <- cudf::get_element(2) using valid_t = std::vector<cudf::valid_type>; using offset_t = cudf::test::fixed_width_column_wrapper<cudf::size_type>; auto list_column = this->make_test_lists_column(2, {0, 2, 3}, this->leaf_data(), {1, 1}); auto list_column_nested = this->make_test_lists_column(3, {0, 1, 1, 2}, std::move(list_column), {1, 1, 0}); cudf::size_type index = 2; auto s = cudf::get_element(list_column_nested->view(), index); auto typed_s = static_cast<cudf::list_scalar const*>(s.get()); auto nested = this->make_test_structs_column({}, {}, {}, valid_t{}.begin()); auto expected_data = cudf::make_lists_column(0, offset_t{}.release(), nested.release(), 0, rmm::device_buffer{}); EXPECT_FALSE(s->is_valid()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected_data, typed_s->view()); } struct StructGetValueTest : public cudf::test::BaseFixture {}; template <typename T> struct StructGetValueTestTyped : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(StructGetValueTestTyped, cudf::test::FixedWidthTypes); TYPED_TEST(StructGetValueTestTyped, mixed_types_valid) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; // col fields cudf::test::fixed_width_column_wrapper<TypeParam> f1{1, 2, 3}; cudf::test::strings_column_wrapper f2{"aa", "bbb", "c"}; cudf::test::dictionary_column_wrapper<TypeParam, int32_t> f3{42, 42, 24}; LCW f4{LCW{8, 8, 8}, LCW{9, 9}, LCW{10}}; cudf::test::structs_column_wrapper col{f1, f2, f3, f4}; cudf::size_type index = 2; auto s = cudf::get_element(col, index); auto typed_s = static_cast<cudf::struct_scalar const*>(s.get()); // expect fields cudf::test::fixed_width_column_wrapper<TypeParam> ef1{3}; cudf::test::strings_column_wrapper ef2{"c"}; cudf::test::dictionary_column_wrapper<TypeParam, int32_t> ef3{24}; LCW ef4{LCW{10}}; cudf::table_view expect_data{{ef1, ef2, ef3, ef4}}; EXPECT_TRUE(typed_s->is_valid()); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(expect_data, typed_s->view()); } TYPED_TEST(StructGetValueTestTyped, mixed_types_valid_with_nulls) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; using validity_mask_t = std::vector<cudf::valid_type>; // col fields cudf::test::fixed_width_column_wrapper<TypeParam> f1({1, 2, 3}, {true, false, true}); cudf::test::strings_column_wrapper f2({"aa", "bbb", "c"}, {false, false, true}); cudf::test::dictionary_column_wrapper<TypeParam, uint32_t> f3( {42, 42, 24}, validity_mask_t{true, true, true}.begin()); LCW f4({LCW{8, 8, 8}, LCW{9, 9}, LCW{10}}, validity_mask_t{false, false, false}.begin()); cudf::test::structs_column_wrapper col{f1, f2, f3, f4}; cudf::size_type index = 1; auto s = cudf::get_element(col, index); auto typed_s = static_cast<cudf::struct_scalar const*>(s.get()); // expect fields cudf::test::fixed_width_column_wrapper<TypeParam> ef1({-1}, {false}); cudf::test::strings_column_wrapper ef2({""}, {false}); cudf::test::dictionary_column_wrapper<TypeParam, uint32_t> x({42}, {true}); cudf::dictionary_column_view dict_col(x); cudf::test::fixed_width_column_wrapper<TypeParam> new_key{24}; auto ef3 = cudf::dictionary::add_keys(dict_col, new_key); LCW ef4({LCW{10}}, validity_mask_t{false}.begin()); cudf::table_view expect_data{{ef1, ef2, *ef3, ef4}}; EXPECT_TRUE(typed_s->is_valid()); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(expect_data, typed_s->view()); } TYPED_TEST(StructGetValueTestTyped, mixed_types_invalid) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; using validity_mask_t = std::vector<cudf::valid_type>; // col fields cudf::test::fixed_width_column_wrapper<TypeParam> f1{1, 2, 3}; cudf::test::strings_column_wrapper f2{"aa", "bbb", "c"}; cudf::test::dictionary_column_wrapper<TypeParam, uint32_t> f3{42, 42, 24}; LCW f4{LCW{8, 8, 8}, LCW{9, 9}, LCW{10}}; cudf::test::structs_column_wrapper col({f1, f2, f3, f4}, validity_mask_t{false, true, true}.begin()); cudf::size_type index = 0; auto s = cudf::get_element(col, index); auto typed_s = static_cast<cudf::struct_scalar const*>(s.get()); EXPECT_FALSE(typed_s->is_valid()); // expect to preserve types along column hierarchy. EXPECT_EQ(typed_s->view().column(0).type().id(), cudf::type_to_id<TypeParam>()); EXPECT_EQ(typed_s->view().column(1).type().id(), cudf::type_id::STRING); EXPECT_EQ(typed_s->view().column(2).type().id(), cudf::type_id::DICTIONARY32); EXPECT_EQ(typed_s->view().column(2).child(1).type().id(), cudf::type_to_id<TypeParam>()); EXPECT_EQ(typed_s->view().column(3).type().id(), cudf::type_id::LIST); EXPECT_EQ(typed_s->view().column(3).child(1).type().id(), cudf::type_to_id<TypeParam>()); } TEST_F(StructGetValueTest, multi_level_nested) { using LCW = cudf::test::lists_column_wrapper<int32_t, int32_t>; using validity_mask_t = std::vector<cudf::valid_type>; // col fields LCW l3({LCW{1, 1, 1}, LCW{2, 2}, LCW{3}}, validity_mask_t{false, true, true}.begin()); cudf::test::structs_column_wrapper l2{l3}; auto l1 = cudf::make_lists_column(1, cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 3}.release(), l2.release(), 0, cudf::create_null_mask(1, cudf::mask_state::UNALLOCATED)); std::vector<std::unique_ptr<cudf::column>> l0_fields; l0_fields.emplace_back(std::move(l1)); cudf::test::structs_column_wrapper l0(std::move(l0_fields)); cudf::size_type index = 0; auto s = cudf::get_element(l0, index); auto typed_s = static_cast<cudf::struct_scalar const*>(s.get()); // Expect fields cudf::column_view cv = cudf::column_view(l0); cudf::table_view fields(std::vector<cudf::column_view>(cv.child_begin(), cv.child_end())); EXPECT_TRUE(typed_s->is_valid()); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(fields, typed_s->view()); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/purge_nonempty_nulls_tests.cpp
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/column/column_view.hpp> #include <cudf/copying.hpp> #include <cudf/detail/gather.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/detail/null_mask.hpp> #include <cudf/lists/lists_column_view.hpp> #include <cudf/strings/strings_column_view.hpp> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/iterator_utilities.hpp> using cudf::test::iterators::no_nulls; using cudf::test::iterators::null_at; using cudf::test::iterators::nulls_at; using T = int32_t; // The actual type of the leaf node isn't really important. using values_col_t = cudf::test::fixed_width_column_wrapper<T>; using offsets_col_t = cudf::test::fixed_width_column_wrapper<cudf::size_type>; using gather_map_t = cudf::test::fixed_width_column_wrapper<cudf::size_type>; template <typename T> using LCW = cudf::test::lists_column_wrapper<T, int32_t>; struct HasNonEmptyNullsTest : public cudf::test::BaseFixture {}; TEST_F(HasNonEmptyNullsTest, TrivialTest) { auto const input = LCW<T>{{{{1, 2, 3, 4}, null_at(2)}, {5}, {6, 7}, // <--- Will be set to NULL. Unsanitized row. {8, 9, 10}}, no_nulls()} .release(); EXPECT_FALSE(cudf::may_have_nonempty_nulls(*input)); EXPECT_FALSE(cudf::has_nonempty_nulls(*input)); // Set nullmask, post construction. cudf::detail::set_null_mask( input->mutable_view().null_mask(), 2, 3, false, cudf::get_default_stream()); input->set_null_count(1); EXPECT_TRUE(cudf::may_have_nonempty_nulls(*input)); EXPECT_TRUE(cudf::has_nonempty_nulls(*input)); } TEST_F(HasNonEmptyNullsTest, SlicedInputTest) { auto const input = cudf::test::strings_column_wrapper{ {"" /*NULL*/, "111", "222", "333", "444", "" /*NULL*/, "", "777", "888", "" /*NULL*/, "101010"}, cudf::test::iterators::nulls_at({0, 5, 9})}; // Split into 2 columns from rows [0, 2) and [2, 10). auto const result = cudf::split(input, {2}); for (auto const& col : result) { EXPECT_TRUE(cudf::may_have_nonempty_nulls(col)); EXPECT_FALSE(cudf::has_nonempty_nulls(col)); } } struct PurgeNonEmptyNullsTest : public cudf::test::BaseFixture { /// Helper to run gather() on a single column, and extract the single column from the result. std::unique_ptr<cudf::column> gather(cudf::column_view const& input, gather_map_t const& gather_map) { auto gathered = cudf::gather(cudf::table_view{{input}}, gather_map, cudf::out_of_bounds_policy::NULLIFY); return std::move(gathered->release()[0]); } /// Verify that the result of `sanitize()` is equivalent to the unsanitized input, /// except that the null rows are also empty. void test_purge(cudf::column_view const& unpurged) { auto const purged = cudf::purge_nonempty_nulls(unpurged); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(unpurged, *purged); EXPECT_FALSE(cudf::has_nonempty_nulls(*purged)); } }; // List<T>. TEST_F(PurgeNonEmptyNullsTest, SingleLevelList) { auto const input = LCW<T>{{{{1, 2, 3, 4}, null_at(2)}, {5}, {6, 7}, // <--- Will be set to NULL. Unsanitized row. {8, 9, 10}}, no_nulls()} .release(); // Set nullmask, post construction. cudf::detail::set_null_mask( input->mutable_view().null_mask(), 2, 3, false, cudf::get_default_stream()); input->set_null_count(1); test_purge(*input); { // Selecting all rows from input, in different order. auto const results = gather(input->view(), {1, 2, 0, 3}); auto const results_list_view = cudf::lists_column_view(*results); auto const expected = LCW<T>{{{5}, {}, // NULL. {{1, 2, 3, 4}, null_at(2)}, {8, 9, 10}}, null_at(1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); CUDF_TEST_EXPECT_COLUMNS_EQUAL(results_list_view.offsets(), offsets_col_t{0, 1, 1, 5, 8}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(results_list_view.child(), values_col_t{{5, 1, 2, 3, 4, 8, 9, 10}, null_at(3)}); EXPECT_TRUE(cudf::may_have_nonempty_nulls(*results)); EXPECT_FALSE(cudf::has_nonempty_nulls(*results)); } { // Test when gather selects rows preceded by unsanitized rows. auto const results = gather(input->view(), {3, 100, 0}); auto const expected = LCW<T>{{ {8, 9, 10}, {}, // NULL. {{1, 2, 3, 4}, null_at(2)}, }, null_at(1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected); EXPECT_TRUE(cudf::may_have_nonempty_nulls(*results)); EXPECT_FALSE(cudf::has_nonempty_nulls(*results)); } { // Test when gather selects rows followed by unsanitized rows. auto const results = gather(input->view(), {1, 100, 0}); auto const expected = LCW<T>{{ {5}, {}, // NULL. {{1, 2, 3, 4}, null_at(2)}, }, null_at(1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected); EXPECT_TRUE(cudf::may_have_nonempty_nulls(*results)); EXPECT_FALSE(cudf::has_nonempty_nulls(*results)); } { // Test when gather selects unsanitized row specifically. auto const results = gather(input->view(), {2}); auto const results_lists_view = cudf::lists_column_view(*results); auto const expected = LCW<T>{{ LCW<T>{} // NULL. }, null_at(0)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected); CUDF_TEST_EXPECT_COLUMNS_EQUAL(results_lists_view.offsets(), offsets_col_t{0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(results_lists_view.child(), values_col_t{}); EXPECT_TRUE(cudf::may_have_nonempty_nulls(*results)); EXPECT_FALSE(cudf::has_nonempty_nulls(*results)); } } // List<List<T>>. TEST_F(PurgeNonEmptyNullsTest, TwoLevelList) { auto const input = LCW<T>{ {{{1, 2, 3}, {4, 5, 6, 7}, {8}, {9, 1}, {2}}, {{11, 12}, {13, 14, 15}, {16, 17, 18}, {19}}, {{21}, {22, 23}, {24, 25, 26}}, {{31, 32}, {33, 34, 35, 36}, {}, {37, 38}}, //<--- Will be set to NULL. Unsanitized row. {{41}, {42, 43}}}, no_nulls()} .release(); EXPECT_FALSE(cudf::may_have_nonempty_nulls(*input)); EXPECT_FALSE(cudf::has_nonempty_nulls(*input)); // Set nullmask, post construction. cudf::detail::set_null_mask( input->mutable_view().null_mask(), 3, 4, false, cudf::get_default_stream()); input->set_null_count(1); EXPECT_TRUE(cudf::may_have_nonempty_nulls(*input)); EXPECT_TRUE(cudf::has_nonempty_nulls(*input)); test_purge(*input); { // Verify that gather() output is sanitized. auto const results = gather(input->view(), {100, 3, 0, 1}); auto const results_lists_view = cudf::lists_column_view(*results); auto const expected = LCW<T>{{ LCW<T>{}, // NULL, because of out of bounds. LCW<T>{}, // NULL, because input row was null. {{1, 2, 3}, {4, 5, 6, 7}, {8}, {9, 1}, {2}}, // i.e. input[0] {{11, 12}, {13, 14, 15}, {16, 17, 18}, {19}} // i.e. input[1] }, nulls_at({0, 1})}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); CUDF_TEST_EXPECT_COLUMNS_EQUAL(results_lists_view.offsets(), offsets_col_t{0, 0, 0, 5, 9}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( results_lists_view.child(), LCW<T>{ {1, 2, 3}, {4, 5, 6, 7}, {8}, {9, 1}, {2}, {11, 12}, {13, 14, 15}, {16, 17, 18}, {19}}); auto const child_lists_view = cudf::lists_column_view(results_lists_view.child()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(child_lists_view.offsets(), offsets_col_t{0, 3, 7, 8, 10, 11, 13, 16, 19, 20}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( child_lists_view.child(), values_col_t{1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 11, 12, 13, 14, 15, 16, 17, 18, 19}); EXPECT_TRUE(cudf::may_have_nonempty_nulls(*results)); EXPECT_FALSE(cudf::has_nonempty_nulls(*results)); } } // List<List<List<T>>>. TEST_F(PurgeNonEmptyNullsTest, ThreeLevelList) { auto const input = LCW<T>{{{{{1, 2}, {3}}, {{4, 5}, {6, 7}}, {{8, 8}, {}}, {{9, 1}}, {{2, 3}}}, {{{11, 12}}, {{13}, {14, 15}}, {{16, 17, 18}}, {{19, 19}, {}}}, {{{21, 21}}, {{22, 23}, {}}, {{24, 25}, {26}}}, {{{31, 32}, {}}, {{33, 34, 35}, {36}}, {}, {{37, 38}}}, //<--- Will be set to NULL. Unsanitized row. {{{41, 41, 41}}, {{42, 43}}}}, no_nulls()} .release(); EXPECT_FALSE(cudf::may_have_nonempty_nulls(*input)); EXPECT_FALSE(cudf::has_nonempty_nulls(*input)); // Set nullmask, post construction. cudf::detail::set_null_mask( input->mutable_view().null_mask(), 3, 4, false, cudf::get_default_stream()); input->set_null_count(1); EXPECT_TRUE(cudf::may_have_nonempty_nulls(*input)); EXPECT_TRUE(cudf::has_nonempty_nulls(*input)); test_purge(*input); { auto const results = gather(input->view(), {100, 3, 0, 1}); auto const results_lists_view = cudf::lists_column_view(*results); auto const expected = LCW<T>{ { LCW<T>{}, // NULL, because of out of bounds. LCW<T>{}, // NULL, because input row was null. {{{1, 2}, {3}}, {{4, 5}, {6, 7}}, {{8, 8}, {}}, {{9, 1}}, {{2, 3}}}, // i.e. input[0] {{{11, 12}}, {{13}, {14, 15}}, {{16, 17, 18}}, {{19, 19}, {}}} // i.e. input[1] }, nulls_at({0, 1})}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); CUDF_TEST_EXPECT_COLUMNS_EQUAL(results_lists_view.offsets(), offsets_col_t{0, 0, 0, 5, 9}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(results_lists_view.child(), LCW<T>{{{1, 2}, {3}}, {{4, 5}, {6, 7}}, {{8, 8}, {}}, {{9, 1}}, {{2, 3}}, {{11, 12}}, {{13}, {14, 15}}, {{16, 17, 18}}, {{19, 19}, {}}}); EXPECT_TRUE(cudf::may_have_nonempty_nulls(*results)); EXPECT_FALSE(cudf::has_nonempty_nulls(*results)); } } // List<string>. TEST_F(PurgeNonEmptyNullsTest, ListOfStrings) { using T = cudf::string_view; auto const input = LCW<T>{{{{"1", "22", "", "4444"}, null_at(2)}, {"55555"}, {"666666", "7777777"}, // <--- Will be set to NULL. Unsanitized row. {"88888888", "999999999", "1010101010"}, {"11", "22", "33", "44"}, {"55", "66", "77", "88"}}, no_nulls()} .release(); EXPECT_TRUE(cudf::may_have_nonempty_nulls(*input)); EXPECT_FALSE(cudf::has_nonempty_nulls(*input)); // Set nullmask, post construction. cudf::detail::set_null_mask( input->mutable_view().null_mask(), 2, 3, false, cudf::get_default_stream()); input->set_null_count(1); EXPECT_TRUE(cudf::may_have_nonempty_nulls(*input)); EXPECT_TRUE(cudf::has_nonempty_nulls(*input)); test_purge(*input); { // Selecting all rows from input, in different order. auto const results = gather(input->view(), {1, 2, 0, 3}); auto const results_list_view = cudf::lists_column_view(*results); auto const expected = LCW<T>{{{"55555"}, {}, // NULL. {{"1", "22", "", "4444"}, null_at(2)}, {"88888888", "999999999", "1010101010"}}, null_at(1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); CUDF_TEST_EXPECT_COLUMNS_EQUAL(results_list_view.offsets(), offsets_col_t{0, 1, 1, 5, 8}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( results_list_view.child(), cudf::test::strings_column_wrapper{ {"55555", "1", "22", "", "4444", "88888888", "999999999", "1010101010"}, null_at(3)}); EXPECT_TRUE(cudf::may_have_nonempty_nulls(*results)); EXPECT_FALSE(cudf::has_nonempty_nulls(*results)); } { // Gathering from a sliced column. auto const sliced = cudf::slice({input->view()}, {1, 5})[0]; // Lop off 1 row at each end. EXPECT_TRUE(cudf::may_have_nonempty_nulls(sliced)); EXPECT_TRUE(cudf::has_nonempty_nulls(sliced)); auto const results = gather(sliced, {1, 2, 0, 3}); auto const results_list_view = cudf::lists_column_view(*results); auto const expected = LCW<T>{{ {}, {"88888888", "999999999", "1010101010"}, {"55555"}, {"11", "22", "33", "44"}, }, null_at(0)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); CUDF_TEST_EXPECT_COLUMNS_EQUAL(results_list_view.offsets(), offsets_col_t{0, 0, 3, 4, 8}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( results_list_view.child(), cudf::test::strings_column_wrapper{ "88888888", "999999999", "1010101010", "55555", "11", "22", "33", "44"}); EXPECT_TRUE(cudf::may_have_nonempty_nulls(*results)); EXPECT_FALSE(cudf::has_nonempty_nulls(*results)); } } // List<string>. TEST_F(PurgeNonEmptyNullsTest, UnsanitizedListOfUnsanitizedStrings) { auto strings = cudf::test::strings_column_wrapper{ {"1", "22", "3", "44", "5", "66", "7", "8888", "9", "1010"}, //<--- "8888" will be // unsanitized. no_nulls()} .release(); EXPECT_FALSE(cudf::may_have_nonempty_nulls(*strings)); EXPECT_FALSE(cudf::has_nonempty_nulls(*strings)); // Set strings nullmask, post construction. cudf::set_null_mask(strings->mutable_view().null_mask(), 7, 8, false); strings->set_null_count(1); EXPECT_TRUE(cudf::may_have_nonempty_nulls(*strings)); EXPECT_TRUE(cudf::has_nonempty_nulls(*strings)); test_purge(*strings); CUDF_TEST_EXPECT_COLUMNS_EQUAL(cudf::strings_column_view(*strings).offsets(), offsets_col_t{0, 1, 3, 4, 6, 7, 9, 10, 14, 15, 19} // 10-14 indicates that "8888" is unsanitized. ); // Construct a list column from the strings column. auto [null_mask, null_count] = cudf::test::detail::make_null_mask(no_nulls(), no_nulls() + 4); auto const lists = cudf::make_lists_column(4, offsets_col_t{0, 4, 5, 7, 10}.release(), std::move(strings), null_count, std::move(null_mask)); EXPECT_TRUE(cudf::may_have_nonempty_nulls(*lists)); // The child column has non-empty nulls but it has already been sanitized during lists column // construction. EXPECT_FALSE(cudf::has_nonempty_nulls(*lists)); // Set lists nullmask, post construction. cudf::detail::set_null_mask( lists->mutable_view().null_mask(), 2, 3, false, cudf::get_default_stream()); lists->set_null_count(1); EXPECT_TRUE(cudf::may_have_nonempty_nulls(*lists)); EXPECT_TRUE(cudf::has_nonempty_nulls(*lists)); test_purge(*lists); // At this point, // 1. {"66", "7"} will be unsanitized. // 2. {"8888", "9", "1010"} will be actually be {NULL, "9", "1010"}. CUDF_TEST_EXPECT_COLUMNS_EQUAL( cudf::lists_column_view(*lists).offsets(), offsets_col_t{0, 4, 5, 7, 10}); // 5-7 indicates that list row#2 is unsanitized. auto const result = gather(lists->view(), {1, 2, 0, 3}); auto const expected = LCW<cudf::string_view>{{{"5"}, {}, // NULL. {"1", "22", "3", "44"}, {{"", "9", "1010"}, null_at(0)}}, null_at(1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected); // Ensure row#2 has been sanitized. auto const results_lists_view = cudf::lists_column_view(*result); CUDF_TEST_EXPECT_COLUMNS_EQUAL(results_lists_view.offsets(), offsets_col_t{0, 1, 1, 5, 8} // 1-1 indicates that row#2 is sanitized. ); // Ensure that "8888" has been sanitized, and stored as "". auto const child_strings_view = cudf::strings_column_view(results_lists_view.child()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(child_strings_view.offsets(), offsets_col_t{0, 1, 2, 4, 5, 7, 7, 8, 12}); EXPECT_TRUE(cudf::may_have_nonempty_nulls(*result)); EXPECT_FALSE(cudf::has_nonempty_nulls(*result)); } // Struct<List<T>>. TEST_F(PurgeNonEmptyNullsTest, StructOfList) { auto const structs_input = [] { auto child = LCW<T>{{{{1, 2, 3, 4}, null_at(2)}, {5}, {6, 7}, //<--- Unsanitized row. {8, 9, 10}}, no_nulls()}; EXPECT_FALSE(cudf::has_nonempty_nulls(child)); return cudf::test::structs_column_wrapper{{child}}.release(); }(); auto [null_mask, null_count] = [&] { auto const valid_iter = null_at(2); return cudf::test::detail::make_null_mask(valid_iter, valid_iter + structs_input->size()); }(); // Manually set the null mask for the columns, leaving the null at list index 2 unsanitized. structs_input->child(0).set_null_mask(null_mask, null_count, cudf::get_default_stream()); structs_input->set_null_mask(std::move(null_mask), null_count); EXPECT_TRUE(cudf::may_have_nonempty_nulls(*structs_input)); EXPECT_TRUE(cudf::has_nonempty_nulls(*structs_input)); test_purge(*structs_input); // At this point, even though the structs column has a null at index 2, // the child column has a non-empty list row at index 2: {6, 7}. CUDF_TEST_EXPECT_COLUMNS_EQUAL(cudf::lists_column_view(structs_input->child(0)).child(), values_col_t{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, null_at(2)}); { // Test rearrange. auto const gather_map = gather_map_t{1, 2, 0, 3}; auto const result = gather(structs_input->view(), gather_map); auto const expected_result = [] { auto child = LCW<T>{{{5}, LCW<T>{}, //<--- Now, sanitized. {{1, 2, 3, 4}, null_at(2)}, {8, 9, 10}}, null_at(1)}; return cudf::test::structs_column_wrapper{{child}, null_at(1)}; }(); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->view(), expected_result); auto const results_child = cudf::lists_column_view(result->child(0)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(results_child.offsets(), offsets_col_t{0, 1, 1, 5, 8}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(results_child.child(), values_col_t{{5, 1, 2, 3, 4, 8, 9, 10}, null_at(3)}); EXPECT_TRUE(cudf::may_have_nonempty_nulls(*result)); EXPECT_FALSE(cudf::has_nonempty_nulls(*result)); } }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/copy_tests.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/column/column.hpp> #include <cudf/copying.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/dictionary/encode.hpp> #include <cudf/scalar/scalar.hpp> #include <thrust/iterator/constant_iterator.h> #include <thrust/iterator/counting_iterator.h> template <typename T> struct CopyTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(CopyTest, cudf::test::FixedWidthTypesWithoutFixedPoint); #define wrapper cudf::test::fixed_width_column_wrapper TYPED_TEST(CopyTest, CopyIfElseTestShort) { using T = TypeParam; cudf::test::fixed_width_column_wrapper<bool> mask_w{1, 0, 0, 0}; wrapper<T, int32_t> lhs_w({5, 5, 5, 5}, {1, 1, 1, 1}); wrapper<T, int32_t> rhs_w({6, 6, 6, 6}, {1, 1, 1, 1}); wrapper<T, int32_t> expected_w({5, 6, 6, 6}); auto out = cudf::copy_if_else(lhs_w, rhs_w, mask_w); CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), expected_w); } TYPED_TEST(CopyTest, CopyIfElseTestManyNulls) { using T = TypeParam; cudf::test::fixed_width_column_wrapper<bool> mask_w{{1, 0, 0, 0, 0, 0, 1}, {1, 1, 1, 1, 1, 1, 0}}; wrapper<T, int32_t> lhs_w({5, 5, 5, 5, 5, 5, 5}, {1, 1, 1, 1, 1, 1, 1}); wrapper<T, int32_t> rhs_w({6, 6, 6, 6, 6, 6, 6}, {1, 0, 0, 0, 0, 0, 1}); wrapper<T, int32_t> expected_w({5, 6, 6, 6, 6, 6, 6}, {1, 0, 0, 0, 0, 0, 1}); auto out = cudf::copy_if_else(lhs_w, rhs_w, mask_w); CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), expected_w); } TYPED_TEST(CopyTest, CopyIfElseTestLong) { using T = TypeParam; // make sure we span at least 2 warps int num_els = 64; bool mask[] = {true, false, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, true, true, true, true, true, true, true, true, true, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true}; cudf::test::fixed_width_column_wrapper<bool> mask_w(mask, mask + num_els); bool lhs_v[] = {true, true, true, true, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true}; wrapper<T, int32_t> lhs_w({5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5}, lhs_v); bool rhs_v[] = {true, true, true, true, true, true, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true}; wrapper<T, int32_t> rhs_w({6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6}, rhs_v); bool exp_v[] = {true, true, true, true, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true}; wrapper<T, int32_t> expected_w({5, 6, 5, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5}, exp_v); auto out = cudf::copy_if_else(lhs_w, rhs_w, mask_w); CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), expected_w); } TYPED_TEST(CopyTest, CopyIfElseTestMultipleBlocks) { using T = TypeParam; int num = 1000; // larger than a single block std::vector<int32_t> h_lhs(num, 5); std::vector<int32_t> h_rhs(num, 6); std::vector<bool> h_mask(num, false); std::vector<bool> h_validity(num, true); h_validity[0] = 0; cudf::test::fixed_width_column_wrapper<T, int32_t> lhs_w( h_lhs.begin(), h_lhs.end(), h_validity.begin()); cudf::test::fixed_width_column_wrapper<T, int32_t> rhs_w( h_rhs.begin(), h_rhs.end(), h_validity.begin()); cudf::test::fixed_width_column_wrapper<bool> mask_w(h_mask.begin(), h_mask.end()); auto out = cudf::copy_if_else(lhs_w, rhs_w, mask_w); CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), rhs_w); } TYPED_TEST(CopyTest, CopyIfElseTestEmptyInputs) { using T = TypeParam; cudf::test::fixed_width_column_wrapper<bool> mask_w{}; wrapper<T> lhs_w{}; wrapper<T> rhs_w{}; wrapper<T> expected_w{}; auto out = cudf::copy_if_else(lhs_w, rhs_w, mask_w); CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), expected_w); } TYPED_TEST(CopyTest, CopyIfElseMixedInputValidity) { using T = TypeParam; cudf::test::fixed_width_column_wrapper<bool> mask_w{1, 0, 1, 1}; wrapper<T, int32_t> lhs_w({5, 5, 5, 5}, {1, 1, 1, 0}); wrapper<T, int32_t> rhs_w({6, 6, 6, 6}, {1, 0, 1, 1}); wrapper<T, int32_t> expected_w({5, 6, 5, 5}, {1, 0, 1, 0}); auto out = cudf::copy_if_else(lhs_w, rhs_w, mask_w); CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), expected_w); } TYPED_TEST(CopyTest, CopyIfElseMixedInputValidity2) { using T = TypeParam; cudf::test::fixed_width_column_wrapper<bool> mask_w{1, 0, 1, 1}; wrapper<T, int32_t> lhs_w({5, 5, 5, 5}, {1, 1, 1, 0}); wrapper<T, int32_t> rhs_w({6, 6, 6, 6}); wrapper<T, int32_t> expected_w({5, 6, 5, 5}, {1, 1, 1, 0}); auto out = cudf::copy_if_else(lhs_w, rhs_w, mask_w); CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), expected_w); } TYPED_TEST(CopyTest, CopyIfElseMixedInputValidity3) { using T = TypeParam; cudf::test::fixed_width_column_wrapper<bool> mask_w{1, 0, 1, 1}; wrapper<T, int32_t> lhs_w({5, 5, 5, 5}); wrapper<T, int32_t> rhs_w({6, 6, 6, 6}, {1, 0, 1, 1}); wrapper<T, int32_t> expected_w({5, 6, 5, 5}, {1, 0, 1, 1}); auto out = cudf::copy_if_else(lhs_w, rhs_w, mask_w); CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), expected_w); } TYPED_TEST(CopyTest, CopyIfElseMixedInputValidity4) { using T = TypeParam; cudf::test::fixed_width_column_wrapper<bool> mask_w{1, 0, 1, 1}; wrapper<T, int32_t> lhs_w({5, 5, 5, 5}); wrapper<T, int32_t> rhs_w({6, 6, 6, 6}); wrapper<T, int32_t> expected_w({5, 6, 5, 5}); auto out = cudf::copy_if_else(lhs_w, rhs_w, mask_w); CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), expected_w); } TYPED_TEST(CopyTest, CopyIfElseBadInputLength) { using T = TypeParam; // mask length mismatch { cudf::test::fixed_width_column_wrapper<bool> mask_w{1, 1, 1}; wrapper<T, int32_t> lhs_w({5, 5, 5, 5}); wrapper<T, int32_t> rhs_w({6, 6, 6, 6}); EXPECT_THROW(cudf::copy_if_else(lhs_w, rhs_w, mask_w), cudf::logic_error); } // column length mismatch { cudf::test::fixed_width_column_wrapper<bool> mask_w{1, 1, 1, 1}; wrapper<T, int32_t> lhs_w({5, 5, 5}); wrapper<T, int32_t> rhs_w({6, 6, 6, 6}); EXPECT_THROW(cudf::copy_if_else(lhs_w, rhs_w, mask_w), cudf::logic_error); } } struct CopyEmptyNested : public cudf::test::BaseFixture {}; TEST_F(CopyEmptyNested, CopyIfElseTestEmptyNestedColumns) { // lists { cudf::test::lists_column_wrapper<cudf::string_view> col{{{"abc", "def"}, {"xyz"}}}; auto lhs = cudf::empty_like(col); auto rhs = cudf::empty_like(col); cudf::test::fixed_width_column_wrapper<bool> mask{}; auto expected = empty_like(col); auto out = cudf::copy_if_else(*lhs, *rhs, mask); CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), *expected); } // structs { cudf::test::lists_column_wrapper<cudf::string_view> _col0{{{"abc", "def"}, {"xyz"}}}; auto col0 = cudf::empty_like(_col0); cudf::test::fixed_width_column_wrapper<int> col1; std::vector<std::unique_ptr<cudf::column>> cols; cols.push_back(std::move(col0)); cols.push_back(col1.release()); cudf::test::structs_column_wrapper struct_col(std::move(cols)); auto lhs = cudf::empty_like(struct_col); auto rhs = cudf::empty_like(struct_col); cudf::test::fixed_width_column_wrapper<bool> mask{}; auto expected = cudf::empty_like(struct_col); auto out = cudf::copy_if_else(*lhs, *rhs, mask); CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), *expected); } } TEST_F(CopyEmptyNested, CopyIfElseTestEmptyNestedScalars) { // lists { cudf::test::lists_column_wrapper<cudf::string_view> _col{{{"abc", "def"}, {"xyz"}}}; std::unique_ptr<cudf::scalar> lhs = cudf::get_element(_col, 0); std::unique_ptr<cudf::scalar> rhs = cudf::get_element(_col, 0); cudf::test::fixed_width_column_wrapper<bool> mask{}; auto expected = empty_like(_col); auto out = cudf::copy_if_else(*lhs, *rhs, mask); CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), *expected); } // structs { cudf::test::lists_column_wrapper<cudf::string_view> col0{{{"abc", "def"}, {"xyz"}}}; cudf::test::fixed_width_column_wrapper<int> col1{1}; cudf::table_view tbl({col0, col1}); cudf::struct_scalar lhs(tbl); cudf::struct_scalar rhs(tbl); std::vector<std::unique_ptr<cudf::column>> cols; cols.push_back(col0.release()); cols.push_back(col1.release()); cudf::test::structs_column_wrapper struct_col(std::move(cols)); cudf::test::fixed_width_column_wrapper<bool> mask{}; auto expected = cudf::empty_like(struct_col); auto out = cudf::copy_if_else(lhs, rhs, mask); CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), *expected); } } template <typename T> struct CopyTestNumeric : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(CopyTestNumeric, cudf::test::NumericTypes); TYPED_TEST(CopyTestNumeric, CopyIfElseTestScalarColumn) { using T = TypeParam; int num_els = 4; bool mask[] = {true, false, false, true}; cudf::test::fixed_width_column_wrapper<bool> mask_w(mask, mask + num_els); cudf::numeric_scalar<T> lhs_w(5); auto const rhs = cudf::test::make_type_param_vector<T>({6, 6, 6, 6}); bool rhs_v[] = {true, false, true, true}; wrapper<T> rhs_w(rhs.begin(), rhs.end(), rhs_v); auto const expected = cudf::test::make_type_param_vector<T>({5, 6, 6, 5}); wrapper<T> expected_w(expected.begin(), expected.end(), rhs_v); auto out = cudf::copy_if_else(lhs_w, rhs_w, mask_w); CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), expected_w); } TYPED_TEST(CopyTestNumeric, CopyIfElseTestColumnScalar) { using T = TypeParam; int num_els = 4; bool mask[] = {true, false, false, true}; bool mask_v[] = {true, true, true, false}; cudf::test::fixed_width_column_wrapper<bool> mask_w(mask, mask + num_els, mask_v); auto const lhs = cudf::test::make_type_param_vector<T>({5, 5, 5, 5}); bool lhs_v[] = {false, true, true, true}; wrapper<T> lhs_w(lhs.begin(), lhs.end(), lhs_v); cudf::numeric_scalar<T> rhs_w(6); auto const expected = cudf::test::make_type_param_vector<T>({5, 6, 6, 6}); wrapper<T> expected_w(expected.begin(), expected.end(), lhs_v); auto out = cudf::copy_if_else(lhs_w, rhs_w, mask_w); CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), expected_w); } TYPED_TEST(CopyTestNumeric, CopyIfElseTestScalarScalar) { using T = TypeParam; int num_els = 4; bool mask[] = {true, false, false, true}; cudf::test::fixed_width_column_wrapper<bool> mask_w(mask, mask + num_els); cudf::numeric_scalar<T> lhs_w(5); cudf::numeric_scalar<T> rhs_w(6, false); auto const expected = cudf::test::make_type_param_vector<T>({5, 6, 6, 5}); wrapper<T> expected_w(expected.begin(), expected.end(), mask); auto out = cudf::copy_if_else(lhs_w, rhs_w, mask_w); CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), expected_w); } template <typename T> struct create_chrono_scalar { template <typename ChronoT = T, typename... Args> std::enable_if_t<std::is_same_v<typename cudf::is_timestamp_t<ChronoT>::type, std::true_type>, cudf::timestamp_scalar<ChronoT>> operator()(Args&&... args) const { return cudf::timestamp_scalar<T>(std::forward<Args>(args)...); } template <typename ChronoT = T, typename... Args> std::enable_if_t<std::is_same_v<typename cudf::is_duration_t<ChronoT>::type, std::true_type>, cudf::duration_scalar<ChronoT>> operator()(Args&&... args) const { return cudf::duration_scalar<T>(std::forward<Args>(args)...); } }; template <typename T> struct CopyTestChrono : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(CopyTestChrono, cudf::test::ChronoTypes); TYPED_TEST(CopyTestChrono, CopyIfElseTestScalarColumn) { using T = TypeParam; int num_els = 4; bool mask[] = {true, false, false, true}; cudf::test::fixed_width_column_wrapper<bool> mask_w(mask, mask + num_els); auto lhs_w = create_chrono_scalar<T>{}(cudf::test::make_type_param_scalar<T>(5), true); bool rhs_v[] = {true, false, true, true}; wrapper<T, int32_t> rhs_w({6, 6, 6, 6}, rhs_v); wrapper<T, int32_t> expected_w({5, 6, 6, 5}, rhs_v); auto out = cudf::copy_if_else(lhs_w, rhs_w, mask_w); CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), expected_w); } TYPED_TEST(CopyTestChrono, CopyIfElseTestColumnScalar) { using T = TypeParam; int num_els = 4; bool mask[] = {true, false, false, true}; cudf::test::fixed_width_column_wrapper<bool> mask_w(mask, mask + num_els); bool lhs_v[] = {false, true, true, true}; wrapper<T, int32_t> lhs_w({5, 5, 5, 5}, lhs_v); auto rhs_w = create_chrono_scalar<T>{}(cudf::test::make_type_param_scalar<T>(6), true); wrapper<T, int32_t> expected_w({5, 6, 6, 5}, lhs_v); auto out = cudf::copy_if_else(lhs_w, rhs_w, mask_w); CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), expected_w); } TYPED_TEST(CopyTestChrono, CopyIfElseTestScalarScalar) { using T = TypeParam; int num_els = 4; bool mask[] = {true, false, false, true}; cudf::test::fixed_width_column_wrapper<bool> mask_w(mask, mask + num_els); auto lhs_w = create_chrono_scalar<T>{}(cudf::test::make_type_param_scalar<T>(5), true); auto rhs_w = create_chrono_scalar<T>{}(cudf::test::make_type_param_scalar<T>(6), false); wrapper<T, int32_t> expected_w({5, 6, 6, 5}, mask); auto out = cudf::copy_if_else(lhs_w, rhs_w, mask_w); CUDF_TEST_EXPECT_COLUMNS_EQUAL(out->view(), expected_w); } struct CopyTestUntyped : public cudf::test::BaseFixture {}; TEST_F(CopyTestUntyped, CopyIfElseTypeMismatch) { cudf::test::fixed_width_column_wrapper<bool> mask_w{1, 1, 1, 1}; wrapper<float> lhs_w{5, 5, 5, 5}; wrapper<int32_t> rhs_w{6, 6, 6, 6}; EXPECT_THROW(cudf::copy_if_else(lhs_w, rhs_w, mask_w), cudf::logic_error); } struct StringsCopyIfElseTest : public cudf::test::BaseFixture {}; TEST_F(StringsCopyIfElseTest, CopyIfElse) { auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); std::vector<char const*> h_strings1{"eee", "bb", "", "aa", "bbb", "ééé"}; cudf::test::strings_column_wrapper strings1(h_strings1.begin(), h_strings1.end(), valids); std::vector<char const*> h_strings2{"zz", "", "yyy", "w", "ééé", "ooo"}; cudf::test::strings_column_wrapper strings2(h_strings2.begin(), h_strings2.end(), valids); bool mask[] = {true, true, false, true, false, true}; bool mask_v[] = {true, true, true, true, true, false}; cudf::test::fixed_width_column_wrapper<bool> mask_w(mask, mask + 6, mask_v); auto results = cudf::copy_if_else(strings1, strings2, mask_w); std::vector<char const*> h_expected; for (cudf::size_type idx = 0; idx < static_cast<cudf::size_type>(h_strings1.size()); ++idx) { if (mask[idx] and mask_v[idx]) h_expected.push_back(h_strings1[idx]); else h_expected.push_back(h_strings2[idx]); } cudf::test::strings_column_wrapper expected(h_expected.begin(), h_expected.end(), valids); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } TEST_F(StringsCopyIfElseTest, CopyIfElseScalarColumn) { auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); std::vector<char const*> h_string1{"eee"}; cudf::string_scalar strings1{h_string1[0]}; std::vector<char const*> h_strings2{"zz", "", "yyy", "w", "ééé", "ooo"}; cudf::test::strings_column_wrapper strings2(h_strings2.begin(), h_strings2.end(), valids); bool mask[] = {true, false, true, false, true, false}; bool mask_v[] = {true, true, true, true, true, false}; cudf::test::fixed_width_column_wrapper<bool> mask_w(mask, mask + 6, mask_v); auto results = cudf::copy_if_else(strings1, strings2, mask_w); std::vector<char const*> h_expected; for (cudf::size_type idx = 0; idx < static_cast<cudf::size_type>(h_strings2.size()); ++idx) { if (mask[idx] and mask_v[idx]) { h_expected.push_back(h_string1[0]); } else { h_expected.push_back(h_strings2[idx]); } } cudf::test::strings_column_wrapper expected(h_expected.begin(), h_expected.end(), valids); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } TEST_F(StringsCopyIfElseTest, CopyIfElseColumnScalar) { auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); std::vector<char const*> h_string1{"eee"}; cudf::string_scalar strings1{h_string1[0]}; std::vector<char const*> h_strings2{"zz", "", "yyy", "w", "ééé", "ooo"}; cudf::test::strings_column_wrapper strings2(h_strings2.begin(), h_strings2.end(), valids); bool mask[] = {false, true, true, true, false, true}; cudf::test::fixed_width_column_wrapper<bool> mask_w(mask, mask + 6); auto results = cudf::copy_if_else(strings2, strings1, mask_w); std::vector<char const*> h_expected; for (cudf::size_type idx = 0; idx < static_cast<cudf::size_type>(h_strings2.size()); ++idx) { if (mask[idx]) { h_expected.push_back(h_strings2[idx]); } else { h_expected.push_back(h_string1[0]); } } cudf::test::strings_column_wrapper expected(h_expected.begin(), h_expected.end(), valids); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } TEST_F(StringsCopyIfElseTest, CopyIfElseScalarScalar) { auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); std::vector<char const*> h_string1{"eee"}; cudf::string_scalar string1{h_string1[0]}; std::vector<char const*> h_string2{"aaa"}; cudf::string_scalar string2{h_string2[0], false}; constexpr cudf::size_type mask_size = 6; bool mask[] = {true, false, true, false, true, false}; cudf::test::fixed_width_column_wrapper<bool> mask_w(mask, mask + mask_size); auto results = cudf::copy_if_else(string1, string2, mask_w); std::vector<char const*> h_expected; for (bool idx : mask) { if (idx) { h_expected.push_back(h_string1[0]); } else { h_expected.push_back(h_string2[0]); } } cudf::test::strings_column_wrapper expected(h_expected.begin(), h_expected.end(), valids); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } template <typename T> struct FixedPointTypes : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(FixedPointTypes, cudf::test::FixedPointTypes); TYPED_TEST(FixedPointTypes, FixedPointSimple) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const mask = cudf::test::fixed_width_column_wrapper<bool>{0, 1, 1, 1, 0, 0}; auto const a = fp_wrapper{{110, 220, 330, 440, 550, 660}, scale_type{-2}}; auto const b = fp_wrapper{{0, 0, 0, 0, 0, 0}, scale_type{-2}}; auto const expected = fp_wrapper{{0, 220, 330, 440, 0, 0}, scale_type{-2}}; auto const result = cudf::copy_if_else(a, b, mask); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointTypes, FixedPointLarge) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto a = thrust::make_counting_iterator(-1000); auto b = thrust::make_constant_iterator(0); auto m = cudf::detail::make_counting_transform_iterator(-1000, [](int i) { return i > 0; }); auto e = cudf::detail::make_counting_transform_iterator(-1000, [](int i) { return std::max(0, i); }); auto const mask = cudf::test::fixed_width_column_wrapper<bool>(m, m + 2000); auto const A = fp_wrapper{a, a + 2000, scale_type{-3}}; auto const B = fp_wrapper{b, b + 2000, scale_type{-3}}; auto const expected = fp_wrapper{e, e + 2000, scale_type{-3}}; auto const result = cudf::copy_if_else(A, B, mask); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointTypes, FixedPointScaleMismatch) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const mask = cudf::test::fixed_width_column_wrapper<bool>{0, 1, 1, 1, 0, 0}; auto const a = fp_wrapper{{110, 220, 330, 440, 550, 660}, scale_type{-2}}; auto const b = fp_wrapper{{0, 0, 0, 0, 0, 0}, scale_type{-1}}; EXPECT_THROW(cudf::copy_if_else(a, b, mask), cudf::logic_error); } struct DictionaryCopyIfElseTest : public cudf::test::BaseFixture {}; TEST_F(DictionaryCopyIfElseTest, ColumnColumn) { auto valids = cudf::test::iterators::null_at(2); std::vector<char const*> h_strings1{"eee", "bb", "", "aa", "bb", "ééé"}; cudf::test::dictionary_column_wrapper<std::string> input1( h_strings1.begin(), h_strings1.end(), valids); std::vector<char const*> h_strings2{"zz", "bb", "", "aa", "ééé", "ooo"}; cudf::test::dictionary_column_wrapper<std::string> input2( h_strings2.begin(), h_strings2.end(), valids); bool mask[] = {true, true, false, true, false, true}; bool mask_v[] = {true, true, true, true, true, false}; cudf::test::fixed_width_column_wrapper<bool> mask_w(mask, mask + 6, mask_v); auto results = cudf::copy_if_else(input1, input2, mask_w); auto decoded = cudf::dictionary::decode(cudf::dictionary_column_view(results->view())); std::vector<char const*> h_expected; for (cudf::size_type idx = 0; idx < static_cast<cudf::size_type>(h_strings1.size()); ++idx) { if (mask[idx] and mask_v[idx]) h_expected.push_back(h_strings1[idx]); else h_expected.push_back(h_strings2[idx]); } cudf::test::strings_column_wrapper expected(h_expected.begin(), h_expected.end(), valids); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(decoded->view(), expected); } TEST_F(DictionaryCopyIfElseTest, ColumnScalar) { std::string h_string{"eee"}; cudf::string_scalar input1{h_string}; std::vector<char const*> h_strings{"zz", "", "yyy", "w", "ééé", "ooo"}; auto valids = cudf::test::iterators::null_at(1); cudf::test::dictionary_column_wrapper<std::string> input2( h_strings.begin(), h_strings.end(), valids); bool mask[] = {false, true, true, true, false, true}; cudf::test::fixed_width_column_wrapper<bool> mask_w(mask, mask + 6); auto results = cudf::copy_if_else(input2, input1, mask_w); auto decoded = cudf::dictionary::decode(cudf::dictionary_column_view(results->view())); std::vector<char const*> h_expected1; std::vector<char const*> h_expected2; for (cudf::size_type idx = 0; idx < static_cast<cudf::size_type>(h_strings.size()); ++idx) { if (mask[idx]) { h_expected1.push_back(h_strings[idx]); h_expected2.push_back(h_string.c_str()); } else { h_expected1.push_back(h_string.c_str()); h_expected2.push_back(h_strings[idx]); } } cudf::test::strings_column_wrapper expected1(h_expected1.begin(), h_expected1.end(), valids); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(decoded->view(), expected1); results = cudf::copy_if_else(input1, input2, mask_w); decoded = cudf::dictionary::decode(cudf::dictionary_column_view(results->view())); cudf::test::strings_column_wrapper expected2(h_expected2.begin(), h_expected2.end()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(decoded->view(), expected2); } TEST_F(DictionaryCopyIfElseTest, TypeMismatch) { cudf::test::dictionary_column_wrapper<int32_t> input1({1, 1, 1, 1}); cudf::test::dictionary_column_wrapper<double> input2({1.0, 1.0, 1.0, 1.0}); cudf::test::fixed_width_column_wrapper<bool> mask({1, 0, 0, 1}); EXPECT_THROW(cudf::copy_if_else(input1, input2, mask), cudf::logic_error); cudf::string_scalar input3{"1"}; EXPECT_THROW(cudf::copy_if_else(input1, input3, mask), cudf::logic_error); EXPECT_THROW(cudf::copy_if_else(input3, input2, mask), cudf::logic_error); EXPECT_THROW(cudf::copy_if_else(input2, input3, mask), cudf::logic_error); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/scatter_list_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/column/column_view.hpp> #include <cudf/copying.hpp> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> template <typename T> class TypedScatterListsTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(TypedScatterListsTest, cudf::test::FixedWidthTypes); class ScatterListsTest : public cudf::test::BaseFixture {}; TYPED_TEST(TypedScatterListsTest, ListsOfFixedWidth) { using T = TypeParam; auto src_list_column = cudf::test::lists_column_wrapper<T, int32_t>{{9, 9, 9, 9}, {8, 8, 8}}; auto target_list_column = cudf::test::lists_column_wrapper<T, int32_t>{ {0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}}; auto scatter_map = cudf::test::fixed_width_column_wrapper<cudf::size_type>{2, 0}; auto ret = cudf::scatter( cudf::table_view({src_list_column}), scatter_map, cudf::table_view({target_list_column})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( ret->get_column(0), cudf::test::lists_column_wrapper<T, int32_t>{ {8, 8, 8}, {1, 1}, {9, 9, 9, 9}, {3, 3}, {4, 4}, {5, 5}, {6, 6}}); } TYPED_TEST(TypedScatterListsTest, SlicedInputLists) { using T = TypeParam; auto src_list_column = cudf::test::lists_column_wrapper<T, int32_t>{ {0, 0, 0, 0}, {9, 9, 9, 9}, {8, 8, 8}, {7, 7, 7}}.release(); auto src_sliced = cudf::slice(src_list_column->view(), {1, 3}).front(); auto target_list_column = cudf::test::lists_column_wrapper<T, int32_t>{ {0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}} .release(); auto scatter_map = cudf::test::fixed_width_column_wrapper<cudf::size_type>{2, 0}; auto ret_1 = cudf::scatter( cudf::table_view({src_sliced}), scatter_map, cudf::table_view({target_list_column->view()})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( ret_1->get_column(0), cudf::test::lists_column_wrapper<T, int32_t>{ {8, 8, 8}, {1, 1}, {9, 9, 9, 9}, {3, 3}, {4, 4}, {5, 5}, {6, 6}}); auto target_sliced = cudf::slice(target_list_column->view(), {1, 6}); auto ret_2 = cudf::scatter(cudf::table_view({src_sliced}), scatter_map, cudf::table_view({target_sliced})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( ret_2->get_column(0), cudf::test::lists_column_wrapper<T, int32_t>{{8, 8, 8}, {2, 2}, {9, 9, 9, 9}, {4, 4}, {5, 5}}); } TYPED_TEST(TypedScatterListsTest, EmptyListsOfFixedWidth) { using T = TypeParam; auto src_child = cudf::test::fixed_width_column_wrapper<T, int32_t>{ {9, 9, 9, 9, 8, 8, 8}, }; // One null list row, and one row with nulls. auto src_list_column = cudf::make_lists_column( 3, cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 4, 7, 7}.release(), src_child.release(), 0, {}); auto target_list_column = cudf::test::lists_column_wrapper<T, int32_t>{ {0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}}; auto scatter_map = cudf::test::fixed_width_column_wrapper<cudf::size_type>{2, 0, 5}; auto ret = cudf::scatter(cudf::table_view({src_list_column->view()}), scatter_map, cudf::table_view({target_list_column})); auto expected_child_ints = cudf::test::fixed_width_column_wrapper<T, int32_t>{ {8, 8, 8, 1, 1, 9, 9, 9, 9, 3, 3, 4, 4, 6, 6}}; auto expected_lists_column = cudf::make_lists_column( 7, cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 3, 5, 9, 11, 13, 13, 15}.release(), expected_child_ints.release(), 0, {}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_lists_column->view(), ret->get_column(0)); } TYPED_TEST(TypedScatterListsTest, EmptyListsOfNullableFixedWidth) { using T = TypeParam; auto src_child = cudf::test::fixed_width_column_wrapper<T, int32_t>{{9, 9, 9, 9, 8, 8, 8}, {1, 1, 1, 0, 1, 1, 1}}; // One null list row, and one row with nulls. auto src_list_column = cudf::make_lists_column( 3, cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 4, 7, 7}.release(), src_child.release(), 0, {}); auto target_list_column = cudf::test::lists_column_wrapper<T, int32_t>{ {0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}}; auto scatter_map = cudf::test::fixed_width_column_wrapper<cudf::size_type>{2, 0, 5}; auto ret = cudf::scatter(cudf::table_view({src_list_column->view()}), scatter_map, cudf::table_view({target_list_column})); auto expected_child_ints = cudf::test::fixed_width_column_wrapper<T, int32_t>{ {8, 8, 8, 1, 1, 9, 9, 9, 9, 3, 3, 4, 4, 6, 6}, {1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1}}; auto expected_lists_column = cudf::make_lists_column( 7, cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 3, 5, 9, 11, 13, 13, 15}.release(), expected_child_ints.release(), 0, {}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_lists_column->view(), ret->get_column(0)); } TYPED_TEST(TypedScatterListsTest, NullableListsOfNullableFixedWidth) { using T = TypeParam; auto src_child = cudf::test::fixed_width_column_wrapper<T, int32_t>{{9, 9, 9, 9, 8, 8, 8}, {1, 1, 1, 0, 1, 1, 1}}; auto src_list_validity = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 2; }); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(src_list_validity, src_list_validity + 3); // One null list row, and one row with nulls. auto src_list_column = cudf::make_lists_column( 3, cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 4, 7, 7}.release(), src_child.release(), null_count, std::move(null_mask)); auto target_list_column = cudf::test::lists_column_wrapper<T, int32_t>{ {0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}}; auto scatter_map = cudf::test::fixed_width_column_wrapper<cudf::size_type>{2, 0, 5}; auto ret = cudf::scatter(cudf::table_view({src_list_column->view()}), scatter_map, cudf::table_view({target_list_column})); auto expected_child_ints = cudf::test::fixed_width_column_wrapper<T, int32_t>{ {8, 8, 8, 1, 1, 9, 9, 9, 9, 3, 3, 4, 4, 6, 6}, {1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1}}; auto expected_validity = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 5; }); std::tie(null_mask, null_count) = cudf::test::detail::make_null_mask(expected_validity, expected_validity + 7); auto expected_lists_column = cudf::make_lists_column( 7, cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 3, 5, 9, 11, 13, 13, 15}.release(), expected_child_ints.release(), null_count, std::move(null_mask)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_lists_column->view(), ret->get_column(0)); } TEST_F(ScatterListsTest, ListsOfStrings) { auto src_list_column = cudf::test::lists_column_wrapper<cudf::string_view>{ {"all", "the", "leaves", "are", "brown"}, {"california", "dreaming"}}; auto target_list_column = cudf::test::lists_column_wrapper<cudf::string_view>{{"zero"}, {"one", "one"}, {"two", "two"}, {"three", "three", "three"}, {"four", "four", "four", "four"}}; auto scatter_map = cudf::test::fixed_width_column_wrapper<int32_t>{2, 0}; auto ret = cudf::scatter( cudf::table_view({src_list_column}), scatter_map, cudf::table_view({target_list_column})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( cudf::test::lists_column_wrapper<cudf::string_view>{{"california", "dreaming"}, {"one", "one"}, {"all", "the", "leaves", "are", "brown"}, {"three", "three", "three"}, {"four", "four", "four", "four"}}, ret->get_column(0)); } TEST_F(ScatterListsTest, ListsOfNullableStrings) { auto src_strings_column = cudf::test::strings_column_wrapper{ {"all", "the", "leaves", "are", "brown", "california", "dreaming"}, {1, 1, 1, 0, 1, 0, 1}}; auto src_list_column = cudf::make_lists_column( 2, cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 5, 7}.release(), src_strings_column.release(), 0, {}); auto target_list_column = cudf::test::lists_column_wrapper<cudf::string_view>{{"zero"}, {"one", "one"}, {"two", "two"}, {"three", "three"}, {"four", "four"}, {"five", "five"}}; auto scatter_map = cudf::test::fixed_width_column_wrapper<int32_t>{2, 0}; auto ret = cudf::scatter(cudf::table_view({src_list_column->view()}), scatter_map, cudf::table_view({target_list_column})); auto expected_strings = cudf::test::strings_column_wrapper{ {"california", "dreaming", "one", "one", "all", "the", "leaves", "are", "brown", "three", "three", "four", "four", "five", "five"}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 0 && i != 7; })}; auto expected_lists = cudf::make_lists_column( 6, cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 2, 4, 9, 11, 13, 15}.release(), expected_strings.release(), 0, {}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_lists->view(), ret->get_column(0)); } TEST_F(ScatterListsTest, EmptyListsOfNullableStrings) { auto src_strings_column = cudf::test::strings_column_wrapper{ {"all", "the", "leaves", "are", "brown", "california", "dreaming"}, {1, 1, 1, 0, 1, 0, 1}}; auto src_list_column = cudf::make_lists_column( 3, cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 5, 5, 7}.release(), src_strings_column.release(), 0, {}); auto target_list_column = cudf::test::lists_column_wrapper<cudf::string_view>{{"zero"}, {"one", "one"}, {"two", "two"}, {"three", "three"}, {"four", "four"}, {"five", "five"}}; auto scatter_map = cudf::test::fixed_width_column_wrapper<int32_t>{2, 4, 0}; auto ret = cudf::scatter(cudf::table_view({src_list_column->view()}), scatter_map, cudf::table_view({target_list_column})); auto expected_strings = cudf::test::strings_column_wrapper{ {"california", "dreaming", "one", "one", "all", "the", "leaves", "are", "brown", "three", "three", "five", "five"}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 0 && i != 7; })}; auto expected_lists = cudf::make_lists_column( 6, cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 2, 4, 9, 11, 11, 13}.release(), expected_strings.release(), 0, {}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_lists->view(), ret->get_column(0)); } TEST_F(ScatterListsTest, NullableListsOfNullableStrings) { auto src_strings_column = cudf::test::strings_column_wrapper{ {"all", "the", "leaves", "are", "brown", "california", "dreaming"}, {1, 1, 1, 0, 1, 0, 1}}; auto src_validity = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 1; }); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(src_validity, src_validity + 3); auto src_list_column = cudf::make_lists_column( 3, cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 5, 5, 7}.release(), src_strings_column.release(), null_count, std::move(null_mask)); auto target_list_column = cudf::test::lists_column_wrapper<cudf::string_view>{{"zero"}, {"one", "one"}, {"two", "two"}, {"three", "three"}, {"four", "four"}, {"five", "five"}}; auto scatter_map = cudf::test::fixed_width_column_wrapper<int32_t>{2, 4, 0}; auto ret = cudf::scatter(cudf::table_view({src_list_column->view()}), scatter_map, cudf::table_view({target_list_column})); auto expected_strings = cudf::test::strings_column_wrapper{ {"california", "dreaming", "one", "one", "all", "the", "leaves", "are", "brown", "three", "three", "five", "five"}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 0 && i != 7; })}; auto expected_validity = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 4; }); std::tie(null_mask, null_count) = cudf::test::detail::make_null_mask(expected_validity, expected_validity + 6); auto expected_lists = cudf::make_lists_column( 6, cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 2, 4, 9, 11, 11, 13}.release(), expected_strings.release(), null_count, std::move(null_mask)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_lists->view(), ret->get_column(0)); } TYPED_TEST(TypedScatterListsTest, ListsOfLists) { using T = TypeParam; auto src_list_column = cudf::test::lists_column_wrapper<T, int32_t>{{{1, 1, 1, 1}, {2, 2, 2, 2}}, {{3, 3, 3, 3}, {4, 4, 4, 4}}}; auto target_list_column = cudf::test::lists_column_wrapper<T, int32_t>{{{9, 9, 9}, {8, 8, 8}, {7, 7, 7}}, {{6, 6, 6}, {5, 5, 5}, {4, 4, 4}}, {{3, 3, 3}, {2, 2, 2}, {1, 1, 1}}, {{9, 9}, {8, 8}, {7, 7}}, {{6, 6}, {5, 5}, {4, 4}}, {{3, 3}, {2, 2}, {1, 1}}}; auto scatter_map = cudf::test::fixed_width_column_wrapper<cudf::size_type>{2, 0}; auto ret = cudf::scatter( cudf::table_view({src_list_column}), scatter_map, cudf::table_view({target_list_column})); auto expected = cudf::test::lists_column_wrapper<T, int32_t>{{{3, 3, 3, 3}, {4, 4, 4, 4}}, {{6, 6, 6}, {5, 5, 5}, {4, 4, 4}}, {{1, 1, 1, 1}, {2, 2, 2, 2}}, {{9, 9}, {8, 8}, {7, 7}}, {{6, 6}, {5, 5}, {4, 4}}, {{3, 3}, {2, 2}, {1, 1}}}; CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, ret->get_column(0)); } TYPED_TEST(TypedScatterListsTest, EmptyListsOfLists) { using T = TypeParam; auto src_list_column = cudf::test::lists_column_wrapper<T, int32_t>{ {{1, 1, 1, 1}, {2, 2, 2, 2}}, {{3, 3, 3, 3}, {}}, {}}; auto target_list_column = cudf::test::lists_column_wrapper<T, int32_t>{{{9, 9, 9}, {8, 8, 8}, {7, 7, 7}}, {{6, 6, 6}, {5, 5, 5}, {4, 4, 4}}, {{3, 3, 3}, {2, 2, 2}, {1, 1, 1}}, {{9, 9}, {8, 8}, {7, 7}}, {{6, 6}, {5, 5}, {4, 4}}, {{3, 3}, {2, 2}, {1, 1}}}; auto scatter_map = cudf::test::fixed_width_column_wrapper<cudf::size_type>{2, 0, 4}; auto ret = cudf::scatter( cudf::table_view({src_list_column}), scatter_map, cudf::table_view({target_list_column})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( cudf::test::lists_column_wrapper<T, int32_t>{{{3, 3, 3, 3}, {}}, {{6, 6, 6}, {5, 5, 5}, {4, 4, 4}}, {{1, 1, 1, 1}, {2, 2, 2, 2}}, {{9, 9}, {8, 8}, {7, 7}}, {}, {{3, 3}, {2, 2}, {1, 1}}}, ret->get_column(0)); } TYPED_TEST(TypedScatterListsTest, NullListsOfLists) { using T = TypeParam; auto src_list_column = cudf::test::lists_column_wrapper<T, int32_t>{ {{{1, 1, 1, 1}, {2, 2, 2, 2}}, {{3, 3, 3, 3}, {}}, {}}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 2; })}; auto target_list_column = cudf::test::lists_column_wrapper<T, int32_t>{{{9, 9, 9}, {8, 8, 8}, {7, 7, 7}}, {{6, 6, 6}, {5, 5, 5}, {4, 4, 4}}, {{3, 3, 3}, {2, 2, 2}, {1, 1, 1}}, {{9, 9}, {8, 8}, {7, 7}}, {{6, 6}, {5, 5}, {4, 4}}, {{3, 3}, {2, 2}, {1, 1}}}; auto scatter_map = cudf::test::fixed_width_column_wrapper<cudf::size_type>{2, 0, 4}; auto ret = cudf::scatter( cudf::table_view({src_list_column}), scatter_map, cudf::table_view({target_list_column})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( cudf::test::lists_column_wrapper<T, int32_t>{ {{{3, 3, 3, 3}, {}}, {{6, 6, 6}, {5, 5, 5}, {4, 4, 4}}, {{1, 1, 1, 1}, {2, 2, 2, 2}}, {{9, 9}, {8, 8}, {7, 7}}, {}, {{3, 3}, {2, 2}, {1, 1}}}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 4; })}, ret->get_column(0)); } TYPED_TEST(TypedScatterListsTest, ListsOfStructs) { using T = TypeParam; using offsets_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>; using numerics_column = cudf::test::fixed_width_column_wrapper<T>; // clang-format off auto source_numerics = numerics_column{ 9, 9, 9, 9, 8, 8, 8 }; auto source_strings = cudf::test::strings_column_wrapper{ "nine", "nine", "nine", "nine", "eight", "eight", "eight" }; // clang-format on auto source_structs = cudf::test::structs_column_wrapper{{source_numerics, source_strings}}; auto source_lists = cudf::make_lists_column(2, offsets_column{0, 4, 7}.release(), source_structs.release(), 0, {}); // clang-format off auto target_ints = numerics_column{ 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5 }; auto target_strings = cudf::test::strings_column_wrapper{ "zero", "zero", "one", "one", "two", "two", "three", "three", "four", "four", "five", "five" }; // clang-format on auto target_structs = cudf::test::structs_column_wrapper{{target_ints, target_strings}}; auto target_lists = cudf::make_lists_column( 6, offsets_column{0, 2, 4, 6, 8, 10, 12}.release(), target_structs.release(), 0, {}); auto scatter_map = offsets_column{2, 0}; auto scatter_result = cudf::scatter(cudf::table_view({source_lists->view()}), scatter_map, cudf::table_view({target_lists->view()})); // clang-format off auto expected_numerics = numerics_column{ 8, 8, 8, 1, 1, 9, 9, 9, 9, 3, 3, 4, 4, 5, 5 }; auto expected_strings = cudf::test::strings_column_wrapper{ "eight", "eight", "eight", "one", "one", "nine", "nine", "nine", "nine", "three", "three", "four", "four", "five", "five" }; // clang-format on auto expected_structs = cudf::test::structs_column_wrapper{{expected_numerics, expected_strings}}; auto expected_lists = cudf::make_lists_column( 6, offsets_column{0, 3, 5, 9, 11, 13, 15}.release(), expected_structs.release(), 0, {}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_lists->view(), scatter_result->get_column(0)); } TYPED_TEST(TypedScatterListsTest, ListsOfStructsWithNullMembers) { using T = TypeParam; using offsets_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>; using numerics_column = cudf::test::fixed_width_column_wrapper<T>; // clang-format off auto source_numerics = numerics_column{ { 9, 9, 9, 9, 8, 8, 8 }, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 3; }) }; auto source_strings = cudf::test::strings_column_wrapper{ { "nine", "nine", "nine", "nine", "eight", "eight", "eight" }, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 5; }) }; // clang-format on auto source_structs = cudf::test::structs_column_wrapper{{source_numerics, source_strings}}; auto source_lists = cudf::make_lists_column(2, offsets_column{0, 4, 7}.release(), source_structs.release(), 0, {}); // clang-format off auto target_ints = numerics_column{ 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5 }; auto target_strings = cudf::test::strings_column_wrapper{ "zero", "zero", "one", "one", "two", "two", "three","three", "four", "four", "five", "five" }; // clang-format on auto target_structs = cudf::test::structs_column_wrapper{{target_ints, target_strings}}; auto target_lists = cudf::make_lists_column( 6, offsets_column{0, 2, 4, 6, 8, 10, 12}.release(), target_structs.release(), 0, {}); // clang-format on auto scatter_map = offsets_column{2, 0}; auto scatter_result = cudf::scatter(cudf::table_view({source_lists->view()}), scatter_map, cudf::table_view({target_lists->view()})); // clang-format off auto expected_numerics = numerics_column{ { 8, 8, 8, 1, 1, 9, 9, 9, 9, 3, 3, 4, 4, 5, 5 }, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 8; }) }; auto expected_strings = cudf::test::strings_column_wrapper{ { "eight", "eight", "eight", "one", "one", "nine", "nine", "nine", "nine", "three", "three", "four", "four", "five", "five" }, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 1; }) }; // clang-format on auto expected_structs = cudf::test::structs_column_wrapper{{expected_numerics, expected_strings}}; auto expected_lists = cudf::make_lists_column( 6, offsets_column{0, 3, 5, 9, 11, 13, 15}.release(), expected_structs.release(), 0, {}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_lists->view(), scatter_result->get_column(0)); } TYPED_TEST(TypedScatterListsTest, ListsOfNullStructs) { using T = TypeParam; using offsets_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>; using numerics_column = cudf::test::fixed_width_column_wrapper<T>; // clang-format off auto source_numerics = numerics_column{ { 9, 9, 9, 9, 8, 8, 8 }, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 3; }) }; auto source_strings = cudf::test::strings_column_wrapper{ { "nine", "nine", "nine", "nine", "eight", "eight", "eight" }, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 5; }) }; // clang-format on auto source_structs = cudf::test::structs_column_wrapper{ {source_numerics, source_strings}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 1; })}; auto source_lists = cudf::make_lists_column(2, offsets_column{0, 4, 7}.release(), source_structs.release(), 0, {}); // clang-format off auto target_ints = numerics_column{ 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5 }; auto target_strings = cudf::test::strings_column_wrapper{ "zero", "zero", "one", "one", "two", "two", "three", "three", "four", "four", "five", "five" }; // clang-format on auto target_structs = cudf::test::structs_column_wrapper{{target_ints, target_strings}}; auto target_lists = cudf::make_lists_column( 6, offsets_column{0, 2, 4, 6, 8, 10, 12}.release(), target_structs.release(), 0, {}); auto scatter_map = offsets_column{2, 0}; auto scatter_result = cudf::scatter(cudf::table_view({source_lists->view()}), scatter_map, cudf::table_view({target_lists->view()})); // clang-format off auto expected_numerics = numerics_column{ { 8, 8, 8, 1, 1, 9, 9, 9, 9, 3, 3, 4, 4, 5, 5 }, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return (i != 6) && (i != 8); }) }; auto expected_strings = cudf::test::strings_column_wrapper{ { "eight", "eight", "eight", "one", "one", "nine", "nine", "nine", "nine", "three", "three", "four", "four", "five", "five" }, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return (i != 1) && (i != 6); }) }; // clang-format on auto expected_structs = cudf::test::structs_column_wrapper{ {expected_numerics, expected_strings}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 6; })}; auto expected_lists = cudf::make_lists_column( 6, offsets_column{0, 3, 5, 9, 11, 13, 15}.release(), expected_structs.release(), 0, {}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_lists->view(), scatter_result->get_column(0)); } TYPED_TEST(TypedScatterListsTest, EmptyListsOfStructs) { using T = TypeParam; using offsets_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>; using numerics_column = cudf::test::fixed_width_column_wrapper<T>; // clang-format off auto source_numerics = numerics_column{ { 9, 9, 9, 9, 8, 8, 8 }, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 3; }) }; auto source_strings = cudf::test::strings_column_wrapper{ { "nine", "nine", "nine", "nine", "eight", "eight", "eight" }, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 5; }) }; // clang-format on auto source_structs = cudf::test::structs_column_wrapper{ {source_numerics, source_strings}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 1; })}; auto source_lists = cudf::make_lists_column( 3, offsets_column{0, 4, 7, 7}.release(), source_structs.release(), 0, {}); // clang-format off auto target_ints = numerics_column{ 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5 }; auto target_strings = cudf::test::strings_column_wrapper{ "zero", "zero", "one", "one", "two", "two", "three", "three", "four", "four", "five", "five" }; // clang-format on auto target_structs = cudf::test::structs_column_wrapper{{target_ints, target_strings}}; auto target_lists = cudf::make_lists_column( 6, offsets_column{0, 2, 4, 6, 8, 10, 12}.release(), target_structs.release(), 0, {}); auto scatter_map = offsets_column{2, 0, 4}; auto scatter_result = cudf::scatter(cudf::table_view({source_lists->view()}), scatter_map, cudf::table_view({target_lists->view()})); // clang-format off auto expected_numerics = numerics_column{ { 8, 8, 8, 1, 1, 9, 9, 9, 9, 3, 3, 5, 5 }, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return (i != 6) && (i != 8); }) }; auto expected_strings = cudf::test::strings_column_wrapper{ { "eight", "eight", "eight", "one", "one", "nine", "nine", "nine", "nine", "three", "three", "five", "five" }, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return (i != 1) && (i != 6); }) }; // clang-format on auto expected_structs = cudf::test::structs_column_wrapper{ {expected_numerics, expected_strings}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 6; })}; auto expected_lists = cudf::make_lists_column( 6, offsets_column{0, 3, 5, 9, 11, 11, 13}.release(), expected_structs.release(), 0, {}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_lists->view(), scatter_result->get_column(0)); } TYPED_TEST(TypedScatterListsTest, NullListsOfStructs) { using T = TypeParam; using offsets_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>; using numerics_column = cudf::test::fixed_width_column_wrapper<T>; // clang-format off auto source_numerics = numerics_column{ { 9, 9, 9, 9, 8, 8, 8 }, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 3; }) }; auto source_strings = cudf::test::strings_column_wrapper{ { "nine", "nine", "nine", "nine", "eight", "eight", "eight" }, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 5; }) }; // clang-format on auto source_structs = cudf::test::structs_column_wrapper{ {source_numerics, source_strings}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 1; })}; auto source_list_null_mask_begin = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 2; }); auto [null_mask, null_count] = cudf::test::detail::make_null_mask( source_list_null_mask_begin, source_list_null_mask_begin + 3); auto source_lists = cudf::make_lists_column(3, offsets_column{0, 4, 7, 7}.release(), source_structs.release(), null_count, std::move(null_mask)); // clang-format off auto target_ints = numerics_column{ 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5 }; auto target_strings = cudf::test::strings_column_wrapper{ "zero", "zero", "one", "one", "two", "two", "three", "three", "four", "four", "five", "five" }; // clang-format on auto target_structs = cudf::test::structs_column_wrapper{{target_ints, target_strings}}; auto target_lists = cudf::make_lists_column( 6, offsets_column{0, 2, 4, 6, 8, 10, 12}.release(), target_structs.release(), 0, {}); auto scatter_map = offsets_column{2, 0, 4}; auto scatter_result = cudf::scatter(cudf::table_view({source_lists->view()}), scatter_map, cudf::table_view({target_lists->view()})); // clang-format off auto expected_numerics = numerics_column{ { 8, 8, 8, 1, 1, 9, 9, 9, 9, 3, 3, 5, 5 }, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return (i != 6) && (i != 8); }) }; auto expected_strings = cudf::test::strings_column_wrapper{ { "eight", "eight", "eight", "one", "one", "nine", "nine", "nine", "nine", "three", "three", "five", "five" }, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 1 && i != 6; }) }; // clang-format on auto expected_structs = cudf::test::structs_column_wrapper{ {expected_numerics, expected_strings}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 6; })}; auto expected_lists_null_mask_begin = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 4; }); std::tie(null_mask, null_count) = cudf::test::detail::make_null_mask( expected_lists_null_mask_begin, expected_lists_null_mask_begin + 6); auto expected_lists = cudf::make_lists_column(6, offsets_column{0, 3, 5, 9, 11, 11, 13}.release(), expected_structs.release(), null_count, std::move(null_mask)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_lists->view(), scatter_result->get_column(0)); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/concatenate_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/column/column.hpp> #include <cudf/concatenate.hpp> #include <cudf/copying.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/detail/null_mask.hpp> #include <cudf/dictionary/encode.hpp> #include <cudf/filling.hpp> #include <cudf/table/table.hpp> #include <cudf/utilities/default_stream.hpp> #include <numeric> #include <stdexcept> #include <string> template <typename T> using column_wrapper = cudf::test::fixed_width_column_wrapper<T>; using s_col_wrapper = cudf::test::strings_column_wrapper; using CVector = std::vector<std::unique_ptr<cudf::column>>; using column = cudf::column; using column_view = cudf::column_view; using TView = cudf::table_view; using Table = cudf::table; template <typename T> struct TypedColumnTest : public cudf::test::BaseFixture { cudf::data_type type() { return cudf::data_type{cudf::type_to_id<T>()}; } TypedColumnTest(rmm::cuda_stream_view stream = cudf::get_default_stream()) : data{_num_elements * cudf::size_of(type()), stream}, mask{cudf::bitmask_allocation_size_bytes(_num_elements), stream} { auto typed_data = static_cast<char*>(data.data()); auto typed_mask = static_cast<char*>(mask.data()); std::vector<char> h_data(data.size()); std::iota(h_data.begin(), h_data.end(), char{0}); std::vector<char> h_mask(mask.size()); std::iota(h_mask.begin(), h_mask.end(), char{0}); CUDF_CUDA_TRY( cudaMemcpyAsync(typed_data, h_data.data(), data.size(), cudaMemcpyDefault, stream.value())); CUDF_CUDA_TRY( cudaMemcpyAsync(typed_mask, h_mask.data(), mask.size(), cudaMemcpyDefault, stream.value())); _null_count = cudf::detail::null_count( static_cast<cudf::bitmask_type*>(mask.data()), 0, _num_elements, stream); stream.synchronize(); } cudf::size_type num_elements() const { return _num_elements; } cudf::size_type null_count() const { return _null_count; } std::random_device r; std::default_random_engine generator{r()}; std::uniform_int_distribution<cudf::size_type> distribution{200, 1000}; cudf::size_type _num_elements{distribution(generator)}; rmm::device_buffer data{}; rmm::device_buffer mask{}; cudf::size_type _null_count{}; rmm::device_buffer all_valid_mask{create_null_mask(num_elements(), cudf::mask_state::ALL_VALID)}; rmm::device_buffer all_null_mask{create_null_mask(num_elements(), cudf::mask_state::ALL_NULL)}; }; TYPED_TEST_SUITE(TypedColumnTest, cudf::test::Types<int32_t>); TYPED_TEST(TypedColumnTest, ConcatenateEmptyColumns) { cudf::test::fixed_width_column_wrapper<TypeParam> empty_first{}; cudf::test::fixed_width_column_wrapper<TypeParam> empty_second{}; cudf::test::fixed_width_column_wrapper<TypeParam> empty_third{}; std::vector<column_view> columns_to_concat({empty_first, empty_second, empty_third}); auto concat = cudf::concatenate(columns_to_concat); auto expected_type = cudf::column_view(empty_first).type(); EXPECT_EQ(concat->size(), 0); EXPECT_EQ(concat->type(), expected_type); } TYPED_TEST(TypedColumnTest, ConcatenateNoColumns) { std::vector<column_view> columns_to_concat{}; EXPECT_THROW(cudf::concatenate(columns_to_concat), cudf::logic_error); } TYPED_TEST(TypedColumnTest, ConcatenateColumnView) { column original{this->type(), this->num_elements(), std::move(this->data), std::move(this->mask), this->null_count()}; std::vector<cudf::size_type> indices{0, this->num_elements() / 3, this->num_elements() / 3, this->num_elements() / 2, this->num_elements() / 2, this->num_elements()}; std::vector<cudf::column_view> views = cudf::slice(original, indices); auto concatenated_col = cudf::concatenate(views); CUDF_TEST_EXPECT_COLUMNS_EQUAL(original, *concatenated_col); } struct StringColumnTest : public cudf::test::BaseFixture {}; TEST_F(StringColumnTest, ConcatenateColumnView) { std::vector<char const*> h_strings{"aaa", "bb", "", "cccc", "d", "ééé", "ff", "gggg", "", "h", "iiii", "jjj", "k", "lllllll", "mmmmm", "n", "oo", "ppp"}; cudf::test::strings_column_wrapper strings1(h_strings.data(), h_strings.data() + 6); cudf::test::strings_column_wrapper strings2(h_strings.data() + 6, h_strings.data() + 10); cudf::test::strings_column_wrapper strings3(h_strings.data() + 10, h_strings.data() + h_strings.size()); std::vector<cudf::column_view> strings_columns; strings_columns.push_back(strings1); strings_columns.push_back(strings2); strings_columns.push_back(strings3); auto results = cudf::concatenate(strings_columns); cudf::test::strings_column_wrapper expected(h_strings.begin(), h_strings.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } TEST_F(StringColumnTest, ConcatenateColumnViewLarge) { // Test large concatenate, causes out of bound device memory errors if kernel // indexing is not int64_t. // 1.5GB bytes, 5k columns constexpr size_t num_strings = 10000; constexpr size_t string_length = 150000; constexpr size_t strings_per_column = 2; constexpr size_t num_columns = num_strings / strings_per_column; std::vector<std::string> strings; std::vector<char const*> h_strings; std::vector<cudf::test::strings_column_wrapper> strings_column_wrappers; std::vector<cudf::column_view> strings_columns; std::string s(string_length, 'a'); for (size_t i = 0; i < num_strings; ++i) h_strings.push_back(s.data()); for (size_t i = 0; i < num_columns; ++i) strings_column_wrappers.push_back(cudf::test::strings_column_wrapper( h_strings.data() + i * strings_per_column, h_strings.data() + (i + 1) * strings_per_column)); for (auto& wrapper : strings_column_wrappers) strings_columns.push_back(wrapper); auto results = cudf::concatenate(strings_columns); cudf::test::strings_column_wrapper expected(h_strings.begin(), h_strings.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } TEST_F(StringColumnTest, ConcatenateTooManyColumns) { std::vector<char const*> h_strings{"aaa", "bb", "", "cccc", "d", "ééé", "ff", "gggg", "", "h", "iiii", "jjj", "k", "lllllll", "mmmmm", "n", "oo", "ppp"}; std::vector<char const*> expected_strings; std::vector<cudf::test::strings_column_wrapper> wrappers; std::vector<cudf::column_view> strings_columns; for (int i = 0; i < 200; ++i) { wrappers.emplace_back(h_strings.data(), h_strings.data() + h_strings.size()); strings_columns.push_back(wrappers[i]); expected_strings.insert(expected_strings.end(), h_strings.begin(), h_strings.end()); } cudf::test::strings_column_wrapper expected(expected_strings.data(), expected_strings.data() + expected_strings.size()); auto results = cudf::concatenate(strings_columns); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } struct TableTest : public cudf::test::BaseFixture {}; TEST_F(TableTest, ConcatenateTables) { std::vector<char const*> h_strings{ "Lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit"}; CVector cols_gold; column_wrapper<int8_t> col1_gold{{1, 2, 3, 4, 5, 6, 7, 8}}; column_wrapper<int16_t> col2_gold{{1, 2, 3, 4, 5, 6, 7, 8}}; s_col_wrapper col3_gold(h_strings.data(), h_strings.data() + h_strings.size()); cols_gold.push_back(col1_gold.release()); cols_gold.push_back(col2_gold.release()); cols_gold.push_back(col3_gold.release()); Table gold_table(std::move(cols_gold)); CVector cols_table1; column_wrapper<int8_t> col1_table1{{1, 2, 3, 4}}; column_wrapper<int16_t> col2_table1{{1, 2, 3, 4}}; s_col_wrapper col3_table1(h_strings.data(), h_strings.data() + 4); cols_table1.push_back(col1_table1.release()); cols_table1.push_back(col2_table1.release()); cols_table1.push_back(col3_table1.release()); Table t1(std::move(cols_table1)); CVector cols_table2; column_wrapper<int8_t> col1_table2{{5, 6, 7, 8}}; column_wrapper<int16_t> col2_table2{{5, 6, 7, 8}}; s_col_wrapper col3_table2(h_strings.data() + 4, h_strings.data() + h_strings.size()); cols_table2.push_back(col1_table2.release()); cols_table2.push_back(col2_table2.release()); cols_table2.push_back(col3_table2.release()); Table t2(std::move(cols_table2)); auto concat_table = cudf::concatenate(std::vector<TView>({t1, t2})); CUDF_TEST_EXPECT_TABLES_EQUAL(*concat_table, gold_table); } TEST_F(TableTest, ConcatenateTablesWithOffsets) { column_wrapper<int32_t> col1_1{{5, 4, 3, 5, 8, 5, 6}}; cudf::test::strings_column_wrapper col2_1( {"dada", "egg", "avocado", "dada", "kite", "dog", "ln"}); cudf::table_view table_view_in1{{col1_1, col2_1}}; column_wrapper<int32_t> col1_2{{5, 8, 5, 6, 15, 14, 13}}; cudf::test::strings_column_wrapper col2_2( {"dada", "kite", "dog", "ln", "dado", "greg", "spinach"}); cudf::table_view table_view_in2{{col1_2, col2_2}}; std::vector<cudf::size_type> split_indexes1{3}; std::vector<cudf::table_view> partitioned1 = cudf::split(table_view_in1, split_indexes1); std::vector<cudf::size_type> split_indexes2{3}; std::vector<cudf::table_view> partitioned2 = cudf::split(table_view_in2, split_indexes2); { std::vector<cudf::table_view> table_views_to_concat; table_views_to_concat.push_back(partitioned1[1]); table_views_to_concat.push_back(partitioned2[1]); std::unique_ptr<cudf::table> concatenated_tables = cudf::concatenate(table_views_to_concat); column_wrapper<int32_t> exp1_1{{5, 8, 5, 6, 6, 15, 14, 13}}; cudf::test::strings_column_wrapper exp2_1( {"dada", "kite", "dog", "ln", "ln", "dado", "greg", "spinach"}); cudf::table_view table_view_exp1{{exp1_1, exp2_1}}; CUDF_TEST_EXPECT_TABLES_EQUAL(concatenated_tables->view(), table_view_exp1); } { std::vector<cudf::table_view> table_views_to_concat; table_views_to_concat.push_back(partitioned1[0]); table_views_to_concat.push_back(partitioned2[1]); std::unique_ptr<cudf::table> concatenated_tables = cudf::concatenate(table_views_to_concat); column_wrapper<int32_t> exp1_1{{5, 4, 3, 6, 15, 14, 13}}; cudf::test::strings_column_wrapper exp2_1( {"dada", "egg", "avocado", "ln", "dado", "greg", "spinach"}); cudf::table_view table_view_exp1{{exp1_1, exp2_1}}; CUDF_TEST_EXPECT_TABLES_EQUAL(concatenated_tables->view(), table_view_exp1); } { std::vector<cudf::table_view> table_views_to_concat; table_views_to_concat.push_back(partitioned1[1]); table_views_to_concat.push_back(partitioned2[0]); std::unique_ptr<cudf::table> concatenated_tables = cudf::concatenate(table_views_to_concat); column_wrapper<int32_t> exp1_1{{5, 8, 5, 6, 5, 8, 5}}; cudf::test::strings_column_wrapper exp2_1({"dada", "kite", "dog", "ln", "dada", "kite", "dog"}); cudf::table_view table_view_exp{{exp1_1, exp2_1}}; CUDF_TEST_EXPECT_TABLES_EQUAL(concatenated_tables->view(), table_view_exp); } } TEST_F(TableTest, ConcatenateTablesWithOffsetsAndNulls) { cudf::test::fixed_width_column_wrapper<int32_t> col1_1{{5, 4, 3, 5, 8, 5, 6}, {0, 1, 1, 1, 1, 1, 1}}; cudf::test::strings_column_wrapper col2_1({"dada", "egg", "avocado", "dada", "kite", "dog", "ln"}, {1, 1, 1, 0, 1, 1, 1}); cudf::table_view table_view_in1{{col1_1, col2_1}}; cudf::test::fixed_width_column_wrapper<int32_t> col1_2{{5, 8, 5, 6, 15, 14, 13}, {1, 1, 1, 1, 1, 1, 0}}; cudf::test::strings_column_wrapper col2_2( {"dada", "kite", "dog", "ln", "dado", "greg", "spinach"}, {1, 0, 1, 1, 1, 1, 1}); cudf::table_view table_view_in2{{col1_2, col2_2}}; std::vector<cudf::size_type> split_indexes1{3}; std::vector<cudf::table_view> partitioned1 = cudf::split(table_view_in1, split_indexes1); std::vector<cudf::size_type> split_indexes2{3}; std::vector<cudf::table_view> partitioned2 = cudf::split(table_view_in2, split_indexes2); { std::vector<cudf::table_view> table_views_to_concat; table_views_to_concat.push_back(partitioned1[1]); table_views_to_concat.push_back(partitioned2[1]); std::unique_ptr<cudf::table> concatenated_tables = cudf::concatenate(table_views_to_concat); cudf::test::fixed_width_column_wrapper<int32_t> exp1_1{{5, 8, 5, 6, 6, 15, 14, 13}, {1, 1, 1, 1, 1, 1, 1, 0}}; cudf::test::strings_column_wrapper exp2_1( {"dada", "kite", "dog", "ln", "ln", "dado", "greg", "spinach"}, {0, 1, 1, 1, 1, 1, 1, 1}); cudf::table_view table_view_exp1{{exp1_1, exp2_1}}; CUDF_TEST_EXPECT_TABLES_EQUAL(concatenated_tables->view(), table_view_exp1); } { std::vector<cudf::table_view> table_views_to_concat; table_views_to_concat.push_back(partitioned1[1]); table_views_to_concat.push_back(partitioned2[0]); std::unique_ptr<cudf::table> concatenated_tables = cudf::concatenate(table_views_to_concat); cudf::test::fixed_width_column_wrapper<int32_t> exp1_1{5, 8, 5, 6, 5, 8, 5}; cudf::test::strings_column_wrapper exp2_1({"dada", "kite", "dog", "ln", "dada", "kite", "dog"}, {0, 1, 1, 1, 1, 0, 1}); cudf::table_view table_view_exp1{{exp1_1, exp2_1}}; CUDF_TEST_EXPECT_TABLES_EQUAL(concatenated_tables->view(), table_view_exp1); } } struct OverflowTest : public cudf::test::BaseFixture {}; TEST_F(OverflowTest, OverflowTest) { // should concatenate up to size_type::max rows. { // 5 x size + size_last adds to size_type::max constexpr auto size = static_cast<cudf::size_type>(static_cast<uint32_t>(250) * 1024 * 1024); constexpr auto size_last = static_cast<cudf::size_type>(836763647); auto many_chars = cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT8}, size); auto many_chars_last = cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT8}, size_last); cudf::table_view tbl({*many_chars}); cudf::table_view tbl_last({*many_chars_last}); std::vector<cudf::table_view> table_views_to_concat({tbl, tbl, tbl, tbl, tbl, tbl_last}); std::unique_ptr<cudf::table> concatenated_tables = cudf::concatenate(table_views_to_concat); EXPECT_NO_THROW(cudf::get_default_stream().synchronize()); ASSERT_EQ(concatenated_tables->num_rows(), std::numeric_limits<cudf::size_type>::max()); } // primitive column { constexpr auto size = static_cast<cudf::size_type>(static_cast<uint32_t>(1024) * 1024 * 1024); // try and concatenate 6 char columns of size 1 billion each auto many_chars = cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT8}, size); cudf::table_view tbl({*many_chars}); EXPECT_THROW(cudf::concatenate(std::vector<cudf::table_view>({tbl, tbl, tbl, tbl, tbl, tbl})), std::overflow_error); } // string column, overflow on chars { constexpr auto size = static_cast<cudf::size_type>(static_cast<uint32_t>(1024) * 1024 * 1024); // try and concatenate 6 string columns of with 1 billion chars in each auto offsets = cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, size}; auto many_chars = cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT8}, size); auto col = cudf::make_strings_column( 1, offsets.release(), std::move(many_chars), 0, rmm::device_buffer{}); cudf::table_view tbl({*col}); EXPECT_THROW(cudf::concatenate(std::vector<cudf::table_view>({tbl, tbl, tbl, tbl, tbl, tbl})), std::overflow_error); } // string column, overflow on offsets (rows) { constexpr auto size = static_cast<cudf::size_type>(static_cast<uint32_t>(1024) * 1024 * 1024); // try and concatenate 6 string columns 1 billion rows each auto many_offsets = cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT32}, size + 1); auto chars = cudf::test::fixed_width_column_wrapper<int8_t>{0, 1, 2}; auto col = cudf::make_strings_column( size, std::move(many_offsets), chars.release(), 0, rmm::device_buffer{}); cudf::table_view tbl({*col}); EXPECT_THROW(cudf::concatenate(std::vector<cudf::table_view>({tbl, tbl, tbl, tbl, tbl, tbl})), std::overflow_error); } // list<struct>, structs too long { constexpr auto inner_size = static_cast<cudf::size_type>(static_cast<uint32_t>(512) * 1024 * 1024); // struct std::vector<std::unique_ptr<column>> children; children.push_back( cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT8}, inner_size)); children.push_back( cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT8}, inner_size)); auto struct_col = cudf::make_structs_column(inner_size, std::move(children), 0, rmm::device_buffer{}); // list auto offsets = cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, inner_size}; auto col = cudf::make_lists_column(1, offsets.release(), std::move(struct_col), 0, rmm::device_buffer{}); cudf::table_view tbl({*col}); auto tables = std::vector<cudf::table_view>({tbl, tbl, tbl, tbl, tbl, tbl, tbl, tbl, tbl, tbl, tbl, tbl}); EXPECT_THROW(cudf::concatenate(tables), std::overflow_error); } // struct<int, list>, list child too long { constexpr auto inner_size = static_cast<cudf::size_type>(static_cast<uint32_t>(512) * 1024 * 1024); constexpr cudf::size_type size = 3; // list auto offsets = cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 0, 0, inner_size}; auto many_chars = cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT8}, inner_size); auto list_col = cudf::make_lists_column(3, offsets.release(), std::move(many_chars), 0, rmm::device_buffer{}); // struct std::vector<std::unique_ptr<column>> children; children.push_back(cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT32}, size)); children.push_back(std::move(list_col)); auto col = cudf::make_structs_column(size, std::move(children), 0, rmm::device_buffer{}); cudf::table_view tbl({*col}); auto tables = std::vector<cudf::table_view>({tbl, tbl, tbl, tbl, tbl, tbl, tbl, tbl, tbl, tbl, tbl, tbl}); EXPECT_THROW(cudf::concatenate(tables), std::overflow_error); } } TEST_F(OverflowTest, Presliced) { // primitive column { constexpr auto size = static_cast<cudf::size_type>(static_cast<uint32_t>(1024) * 1024 * 1024); // try and concatenate 4 char columns of size ~1/2 billion each auto many_chars = cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT8}, size); auto sliced = cudf::split(*many_chars, {511 * 1024 * 1024}); // 511 * 1024 * 1024, should succeed cudf::table_view a({sliced[0]}); cudf::concatenate(std::vector<cudf::table_view>({a, a, a, a})); // 513 * 1024 * 1024, should fail cudf::table_view b({sliced[1]}); EXPECT_THROW(cudf::concatenate(std::vector<cudf::table_view>({b, b, b, b})), std::overflow_error); } // struct<int8> column { constexpr auto size = static_cast<cudf::size_type>(static_cast<uint32_t>(1024) * 1024 * 1024); // try and concatenate 4 char columns of size ~1/2 billion each std::vector<std::unique_ptr<column>> children; children.push_back(cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT8}, size)); auto struct_col = cudf::make_structs_column(size, std::move(children), 0, rmm::device_buffer{}); auto sliced = cudf::split(*struct_col, {511 * 1024 * 1024}); // 511 * 1024 * 1024, should succeed cudf::table_view a({sliced[0]}); cudf::concatenate(std::vector<cudf::table_view>({a, a, a, a})); // 513 * 1024 * 1024, should fail cudf::table_view b({sliced[1]}); EXPECT_THROW(cudf::concatenate(std::vector<cudf::table_view>({b, b, b, b})), std::overflow_error); } // strings, overflow on chars { constexpr cudf::size_type total_chars_size = 1024 * 1024 * 1024; constexpr cudf::size_type string_size = 64; constexpr cudf::size_type num_rows = total_chars_size / string_size; // try and concatenate 4 string columns of with ~1/2 billion chars in each auto offset_gen = cudf::detail::make_counting_transform_iterator( 0, [string_size](cudf::size_type index) { return index * string_size; }); cudf::test::fixed_width_column_wrapper<int> offsets(offset_gen, offset_gen + num_rows + 1); auto many_chars = cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT8}, total_chars_size); auto col = cudf::make_strings_column( num_rows, offsets.release(), std::move(many_chars), 0, rmm::device_buffer{}); auto sliced = cudf::split(*col, {(num_rows / 2) - 1}); // (num_rows / 2) - 1 should succeed cudf::table_view a({sliced[0]}); cudf::concatenate(std::vector<cudf::table_view>({a, a, a, a})); // (num_rows / 2) + 1 should fail cudf::table_view b({sliced[1]}); EXPECT_THROW(cudf::concatenate(std::vector<cudf::table_view>({b, b, b, b})), std::overflow_error); } // strings, overflow on offsets { constexpr cudf::size_type total_chars_size = 1024 * 1024 * 1024; constexpr cudf::size_type string_size = 1; constexpr cudf::size_type num_rows = total_chars_size / string_size; // try and concatenate 4 string columns of with ~1/2 billion chars in each auto offsets = cudf::sequence(num_rows + 1, cudf::numeric_scalar<cudf::size_type>(0), cudf::numeric_scalar<cudf::size_type>(string_size)); auto many_chars = cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT8}, total_chars_size); auto col = cudf::make_strings_column( num_rows, std::move(offsets), std::move(many_chars), 0, rmm::device_buffer{}); // should pass (with 2 rows to spare) // leaving this disabled as it typically runs out of memory on a T4 /* { auto sliced = cudf::split(*col, {(num_rows / 2) + 1}); cudf::table_view b({sliced[1]}); cudf::concatenate(std::vector<cudf::table_view>({b, b, b, b})); } */ // should fail by 1 row (2,147,483,647 rows which is fine, but that requires 2,147,483,648 // offsets, which is not) { auto a = cudf::split(*col, {(num_rows / 2)}); cudf::table_view ta({a[1]}); auto b = cudf::split(*col, {(num_rows / 2) + 1}); cudf::table_view tb({b[1]}); EXPECT_THROW(cudf::concatenate(std::vector<cudf::table_view>({ta, ta, ta, tb})), std::overflow_error); } } // list<struct>, structs too long { constexpr auto inner_size = static_cast<cudf::size_type>(static_cast<uint32_t>(1024) * 1024 * 1024); // struct std::vector<std::unique_ptr<column>> children; children.push_back( cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT8}, inner_size)); children.push_back( cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT8}, inner_size)); auto struct_col = cudf::make_structs_column(inner_size, std::move(children), 0, rmm::device_buffer{}); // list constexpr cudf::size_type list_size = inner_size / 4; auto offsets = cudf::test::fixed_width_column_wrapper<int>{ 0, list_size, list_size * 2, list_size * 3, inner_size}; auto col = cudf::make_lists_column(4, offsets.release(), std::move(struct_col), 0, rmm::device_buffer{}); auto sliced = cudf::split(*col, {2}); cudf::table_view tbl({sliced[1]}); auto tables = std::vector<cudf::table_view>({tbl, tbl, tbl, tbl}); EXPECT_THROW(cudf::concatenate(tables), std::overflow_error); } // list<struct>, overflow on offsets { constexpr cudf::size_type inner_size = 1024 * 1024 * 1024; constexpr cudf::size_type list_size = 1; constexpr cudf::size_type num_rows = inner_size / list_size; // struct std::vector<std::unique_ptr<column>> children; children.push_back( cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT8}, inner_size)); children.push_back( cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT8}, inner_size)); auto struct_col = cudf::make_structs_column(inner_size, std::move(children), 0, rmm::device_buffer{}); // try and concatenate 4 struct columns of with ~1/2 billion elements in each auto offsets = cudf::sequence(num_rows + 1, cudf::numeric_scalar<cudf::size_type>(0), cudf::numeric_scalar<cudf::size_type>(list_size)); auto col = cudf::make_strings_column( num_rows, std::move(offsets), std::move(struct_col), 0, rmm::device_buffer{}); // should pass (with 2 rows to spare) // leaving this disabled as it typically runs out of memory on a T4 /* { auto sliced = cudf::split(*col, {(num_rows / 2) + 1}); cudf::table_view b({sliced[1]}); cudf::concatenate(std::vector<cudf::table_view>({b, b, b, b})); } */ // should fail by 1 row (2,147,483,647 rows which is fine, but that requires 2,147,483,648 // offsets, which is not) { auto a = cudf::split(*col, {(num_rows / 2)}); cudf::table_view ta({a[1]}); auto b = cudf::split(*col, {(num_rows / 2) + 1}); cudf::table_view tb({b[1]}); EXPECT_THROW(cudf::concatenate(std::vector<cudf::table_view>({ta, ta, ta, tb})), std::overflow_error); } } // struct<int8, list>, list child elements too long { constexpr auto inner_size = static_cast<cudf::size_type>(static_cast<uint32_t>(1024) * 1024 * 1024); constexpr cudf::size_type num_rows = 4; constexpr cudf::size_type list_size = inner_size / num_rows; // list auto offsets = cudf::test::fixed_width_column_wrapper<cudf::size_type>{ 0, list_size, (list_size * 2) - 1, list_size * 3, inner_size}; auto many_chars = cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT8}, inner_size); auto list_col = cudf::make_lists_column( num_rows, offsets.release(), std::move(many_chars), 0, rmm::device_buffer{}); // struct std::vector<std::unique_ptr<column>> children; children.push_back( cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT8}, num_rows)); children.push_back(std::move(list_col)); auto struct_col = cudf::make_structs_column(num_rows, std::move(children), 0, rmm::device_buffer{}); auto sliced = cudf::split(*struct_col, {2}); cudf::table_view a({sliced[0]}); cudf::concatenate(std::vector<cudf::table_view>({a, a, a, a})); cudf::table_view b({sliced[1]}); EXPECT_THROW(cudf::concatenate(std::vector<cudf::table_view>({b, b, b, b})), std::overflow_error); } } TEST_F(OverflowTest, BigColumnsSmallSlices) { // test : many small slices of large columns. the idea is to make sure // that we are respecting the offset/sizes of the slices and not attempting to // concatenate the entire large initial columns // primitive column { constexpr auto size = static_cast<cudf::size_type>(static_cast<uint32_t>(1024) * 1024 * 1024); auto many_chars = cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT8}, size); auto sliced = cudf::slice(*many_chars, {16, 32}); // 192 total rows cudf::table_view a({sliced[0]}); cudf::concatenate(std::vector<cudf::table_view>({a, a, a, a, a, a, a, a, a, a, a, a})); } // strings column { constexpr auto inner_size = static_cast<cudf::size_type>(static_cast<uint32_t>(1024) * 1024 * 1024); constexpr cudf::size_type num_rows = 1024; constexpr cudf::size_type string_size = inner_size / num_rows; auto offsets = cudf::sequence(num_rows + 1, cudf::numeric_scalar<cudf::size_type>(0), cudf::numeric_scalar<cudf::size_type>(string_size)); auto many_chars = cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT8}, inner_size); auto col = cudf::make_strings_column( num_rows, std::move(offsets), std::move(many_chars), 0, rmm::device_buffer{}); auto sliced = cudf::slice(*col, {16, 32}); // 192 outer rows // 201,326,592 inner rows cudf::table_view a({sliced[0]}); cudf::concatenate(std::vector<cudf::table_view>({a, a, a, a, a, a, a, a, a, a, a, a})); } // list<int8> column { constexpr auto inner_size = static_cast<cudf::size_type>(static_cast<uint32_t>(1024) * 1024 * 1024); constexpr cudf::size_type num_rows = 1024; constexpr cudf::size_type list_size = inner_size / num_rows; auto offsets = cudf::sequence(num_rows + 1, cudf::numeric_scalar<cudf::size_type>(0), cudf::numeric_scalar<cudf::size_type>(list_size)); auto many_chars = cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT8}, inner_size); auto col = cudf::make_lists_column( num_rows, std::move(offsets), std::move(many_chars), 0, rmm::device_buffer{}); auto sliced = cudf::slice(*col, {16, 32}); // 192 outer rows // 201,326,592 inner rows cudf::table_view a({sliced[0]}); cudf::concatenate(std::vector<cudf::table_view>({a, a, a, a, a, a, a, a, a, a, a, a})); } // struct<int8, list> { constexpr auto inner_size = static_cast<cudf::size_type>(static_cast<uint32_t>(1024) * 1024 * 1024); constexpr cudf::size_type num_rows = 1024; constexpr cudf::size_type list_size = inner_size / num_rows; auto offsets = cudf::sequence(num_rows + 1, cudf::numeric_scalar<cudf::size_type>(0), cudf::numeric_scalar<cudf::size_type>(list_size)); auto many_chars = cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT8}, inner_size); auto list_col = cudf::make_lists_column( num_rows, std::move(offsets), std::move(many_chars), 0, rmm::device_buffer{}); // struct std::vector<std::unique_ptr<column>> children; children.push_back( cudf::make_fixed_width_column(cudf::data_type{cudf::type_id::INT8}, num_rows)); children.push_back(std::move(list_col)); auto struct_col = cudf::make_structs_column(num_rows, std::move(children), 0, rmm::device_buffer{}); auto sliced = cudf::slice(*struct_col, {16, 32}); // 192 outer rows // 201,326,592 inner rows cudf::table_view a({sliced[0]}); cudf::concatenate(std::vector<cudf::table_view>({a, a, a, a, a, a, a, a, a, a, a, a})); } } struct StructsColumnTest : public cudf::test::BaseFixture {}; TEST_F(StructsColumnTest, ConcatenateStructs) { auto count_iter = thrust::make_counting_iterator(0); // 1. String "names" column. std::vector<std::vector<std::string>> names( {{"Vimes", "Carrot"}, {"Angua", "Cheery"}, {}, {"Detritus", "Slant"}}); std::vector<std::vector<bool>> names_validity({{1, 1}, {1, 1}, {}, {1, 1}}); std::vector<cudf::test::strings_column_wrapper> name_cols; std::transform(count_iter, count_iter + names.size(), std::back_inserter(name_cols), [&](int i) { return cudf::test::strings_column_wrapper( names[i].begin(), names[i].end(), names_validity[i].begin()); }); // 2. Numeric "ages" column. std::vector<std::vector<int>> ages({{5, 10}, {15, 20}, {}, {25, 30}}); std::vector<std::vector<bool>> ages_validity({{1, 1}, {1, 1}, {}, {0, 1}}); std::vector<cudf::test::fixed_width_column_wrapper<int>> age_cols; std::transform(count_iter, count_iter + ages.size(), std::back_inserter(age_cols), [&](int i) { return cudf::test::fixed_width_column_wrapper<int>( ages[i].begin(), ages[i].end(), ages_validity[i].begin()); }); // 3. Boolean "is_human" column. std::vector<std::vector<bool>> is_human({{true, true}, {false, false}, {}, {false, false}}); std::vector<std::vector<bool>> is_human_validity({{1, 1}, {1, 0}, {}, {1, 1}}); std::vector<cudf::test::fixed_width_column_wrapper<bool>> is_human_cols; std::transform( count_iter, count_iter + is_human.size(), std::back_inserter(is_human_cols), [&](int i) { return cudf::test::fixed_width_column_wrapper<bool>( is_human[i].begin(), is_human[i].end(), is_human_validity[i].begin()); }); // build expected output std::vector<std::unique_ptr<column>> expected_children; auto name_col_vec = std::vector<column_view>({name_cols[0], name_cols[1], name_cols[2], name_cols[3]}); auto age_col_vec = std::vector<column_view>({age_cols[0], age_cols[1], age_cols[2], age_cols[3]}); auto is_human_col_vec = std::vector<column_view>( {is_human_cols[0], is_human_cols[1], is_human_cols[2], is_human_cols[3]}); expected_children.push_back(cudf::concatenate(name_col_vec)); expected_children.push_back(cudf::concatenate(age_col_vec)); expected_children.push_back(cudf::concatenate(is_human_col_vec)); std::vector<bool> struct_validity({1, 0, 1, 1, 1, 0}); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(struct_validity.begin(), struct_validity.end()); auto expected = make_structs_column(6, std::move(expected_children), null_count, std::move(null_mask)); // concatenate as structs std::vector<cudf::test::structs_column_wrapper> src; src.push_back( cudf::test::structs_column_wrapper({name_cols[0], age_cols[0], is_human_cols[0]}, {1, 0})); src.push_back( cudf::test::structs_column_wrapper({name_cols[1], age_cols[1], is_human_cols[1]}, {1, 1})); src.push_back( cudf::test::structs_column_wrapper({name_cols[2], age_cols[2], is_human_cols[2]}, {})); src.push_back( cudf::test::structs_column_wrapper({name_cols[3], age_cols[3], is_human_cols[3]}, {1, 0})); // concatenate auto result = cudf::concatenate(std::vector<column_view>({src[0], src[1], src[2], src[3]})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected); } TEST_F(StructsColumnTest, ConcatenateEmptyStructs) { auto expected = cudf::make_structs_column(10, {}, 0, rmm::device_buffer()); auto first = cudf::make_structs_column(5, {}, 0, rmm::device_buffer()); auto second = cudf::make_structs_column(2, {}, 0, rmm::device_buffer()); auto third = cudf::make_structs_column(0, {}, 0, rmm::device_buffer()); auto fourth = cudf::make_structs_column(3, {}, 0, rmm::device_buffer()); // concatenate auto result = cudf::concatenate(std::vector<column_view>({*first, *second, *third, *fourth})); ASSERT_EQ(result->size(), expected->size()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected); } TEST_F(StructsColumnTest, ConcatenateSplitStructs) { auto count_iter = thrust::make_counting_iterator(0); std::vector<int> splits({2}); // 1. String "names" column. std::vector<std::vector<std::string>> names( {{"Vimes", "Carrot", "Angua", "Cheery", "Detritus", "Slant"}, {"Bill", "Bob", "Sam", "Fred", "Tom"}}); std::vector<std::vector<bool>> names_validity({{1, 1, 1, 1, 1, 1}, {0, 1, 0, 1, 0}}); std::vector<cudf::test::strings_column_wrapper> name_cols; std::transform(count_iter, count_iter + names.size(), std::back_inserter(name_cols), [&](int i) { return cudf::test::strings_column_wrapper( names[i].begin(), names[i].end(), names_validity[i].begin()); }); // 2. Numeric "ages" column. std::vector<std::vector<int>> ages({{5, 10, 15, 20, 25, 30}, {11, 16, 17, 41, 42}}); std::vector<std::vector<bool>> ages_validity({{1, 1, 1, 1, 0, 1}, {1, 1, 1, 0, 0}}); std::vector<cudf::test::fixed_width_column_wrapper<int>> age_cols; std::transform(count_iter, count_iter + ages.size(), std::back_inserter(age_cols), [&](int i) { return cudf::test::fixed_width_column_wrapper<int>( ages[i].begin(), ages[i].end(), ages_validity[i].begin()); }); // 3. Boolean "is_human" column. std::vector<std::vector<bool>> is_human( {{true, true, false, false, false, false}, {true, true, true, false, true}}); std::vector<std::vector<bool>> is_human_validity({{1, 1, 1, 0, 1, 1}, {0, 0, 0, 1, 1}}); std::vector<cudf::test::fixed_width_column_wrapper<bool>> is_human_cols; std::transform( count_iter, count_iter + is_human.size(), std::back_inserter(is_human_cols), [&](int i) { return cudf::test::fixed_width_column_wrapper<bool>( is_human[i].begin(), is_human[i].end(), is_human_validity[i].begin()); }); // split the columns, keep the one on the end std::vector<column_view> split_names_cols( {cudf::split(name_cols[0], splits)[1], cudf::split(name_cols[1], splits)[1]}); std::vector<column_view> split_ages_cols( {cudf::split(age_cols[0], splits)[1], cudf::split(age_cols[1], splits)[1]}); std::vector<column_view> split_is_human_cols( {cudf::split(is_human_cols[0], splits)[1], cudf::split(is_human_cols[1], splits)[1]}); // build expected output std::vector<std::unique_ptr<column>> expected_children; auto expected_names = std::vector<column_view>({split_names_cols[0], split_names_cols[1]}); auto expected_ages = std::vector<column_view>({split_ages_cols[0], split_ages_cols[1]}); auto expected_is_human = std::vector<column_view>({split_is_human_cols[0], split_is_human_cols[1]}); expected_children.push_back(cudf::concatenate(expected_names)); expected_children.push_back(cudf::concatenate(expected_ages)); expected_children.push_back(cudf::concatenate(expected_is_human)); auto expected = make_structs_column(7, std::move(expected_children), 0, rmm::device_buffer{}); // concatenate as structs std::vector<cudf::test::structs_column_wrapper> src; for (size_t idx = 0; idx < split_names_cols.size(); idx++) { std::vector<std::unique_ptr<column>> inputs; inputs.push_back(std::make_unique<column>(split_names_cols[idx])); inputs.push_back(std::make_unique<column>(split_ages_cols[idx])); inputs.push_back(std::make_unique<column>(split_is_human_cols[idx])); src.push_back(cudf::test::structs_column_wrapper(std::move(inputs))); } // concatenate auto result = cudf::concatenate(std::vector<column_view>({src[0], src[1]})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected); } TEST_F(StructsColumnTest, ConcatenateStructsNested) { // includes Struct<Struct> and Struct<List> auto count_iter = thrust::make_counting_iterator(0); // inner structs std::vector<cudf::test::structs_column_wrapper> inner_structs; { // 1. String "names" column. std::vector<std::vector<std::string>> names( {{"Vimes", "Carrot", "Angua", "Cheery", "Detritus", "Slant"}, {"Bill", "Bob", "Sam", "Fred", "Tom"}}); std::vector<std::vector<bool>> names_validity({{1, 1, 1, 1, 1, 1}, {0, 1, 0, 1, 0}}); std::vector<cudf::test::strings_column_wrapper> name_cols; std::transform( count_iter, count_iter + names.size(), std::back_inserter(name_cols), [&](int i) { return cudf::test::strings_column_wrapper( names[i].begin(), names[i].end(), names_validity[i].begin()); }); // 2. Numeric "ages" column. std::vector<std::vector<int>> ages({{5, 10, 15, 20, 25, 30}, {11, 16, 17, 41, 42}}); std::vector<std::vector<bool>> ages_validity({{1, 1, 1, 1, 0, 1}, {1, 1, 1, 0, 0}}); std::vector<cudf::test::fixed_width_column_wrapper<int>> age_cols; std::transform(count_iter, count_iter + ages.size(), std::back_inserter(age_cols), [&](int i) { return cudf::test::fixed_width_column_wrapper<int>( ages[i].begin(), ages[i].end(), ages_validity[i].begin()); }); for (size_t idx = 0; idx < names.size(); idx++) { std::vector<std::unique_ptr<column>> children; children.push_back(name_cols[idx].release()); children.push_back(age_cols[idx].release()); inner_structs.push_back(cudf::test::structs_column_wrapper(std::move(children))); } } // inner lists using LCW = cudf::test::lists_column_wrapper<cudf::string_view>; std::vector<cudf::test::lists_column_wrapper<cudf::string_view>> inner_lists; { inner_lists.push_back(cudf::test::lists_column_wrapper<cudf::string_view>{ {"abc", "d"}, {"ef", "ghi", "j"}, {"klm", "no"}, LCW{}, LCW{"whee"}, {"xyz", "ab", "g"}}); inner_lists.push_back(cudf::test::lists_column_wrapper<cudf::string_view>{ {"er", "hyj"}, {"", "", "uvw"}, LCW{}, LCW{"oipq", "te"}, LCW{"yay", "bonk"}}); } // build expected output std::vector<std::unique_ptr<column>> expected_children; expected_children.push_back( cudf::concatenate(std::vector<column_view>({inner_structs[0], inner_structs[1]}))); expected_children.push_back( cudf::concatenate(std::vector<column_view>({inner_lists[0], inner_lists[1]}))); auto expected = make_structs_column(11, std::move(expected_children), 0, rmm::device_buffer{}); // concatenate as structs std::vector<cudf::test::structs_column_wrapper> src; for (size_t idx = 0; idx < inner_structs.size(); idx++) { std::vector<std::unique_ptr<column>> inputs; inputs.push_back(std::make_unique<column>(inner_structs[idx])); inputs.push_back(std::make_unique<column>(inner_lists[idx])); src.push_back(cudf::test::structs_column_wrapper(std::move(inputs))); } // concatenate auto result = cudf::concatenate(std::vector<column_view>({src[0], src[1]})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected); } struct ListsColumnTest : public cudf::test::BaseFixture {}; TEST_F(ListsColumnTest, ConcatenateLists) { { cudf::test::lists_column_wrapper<int> a{0, 1, 2, 3}; cudf::test::lists_column_wrapper<int> b{4, 5, 6, 7, 8, 9, 10}; cudf::test::lists_column_wrapper<int> expected{{0, 1, 2, 3}, {4, 5, 6, 7, 8, 9, 10}}; auto result = cudf::concatenate(std::vector<column_view>({a, b})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected); } { cudf::test::lists_column_wrapper<int> a{{0, 1, 1}, {2, 3}, {4, 5}}; cudf::test::lists_column_wrapper<int> b{{6}, {8, 9, 9, 9}, {10, 11}}; cudf::test::lists_column_wrapper<int> expected{ {0, 1, 1}, {2, 3}, {4, 5}, {6}, {8, 9, 9, 9}, {10, 11}}; auto result = cudf::concatenate(std::vector<column_view>({a, b})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected); } { cudf::test::lists_column_wrapper<int> a{{0, 1}, {2, 3, 4, 5}, {6, 7, 8}}; cudf::test::lists_column_wrapper<int> b{{9}, {10, 11}, {12, 13, 14, 15}}; cudf::test::lists_column_wrapper<int> expected{ {0, 1}, {2, 3, 4, 5}, {6, 7, 8}, {9}, {10, 11}, {12, 13, 14, 15}}; auto result = cudf::concatenate(std::vector<column_view>({a, b})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected); } } TEST_F(ListsColumnTest, ConcatenateEmptyLists) { // to disambiguate between {} == 0 and {} == List{0} // Also, see note about compiler issues when declaring nested // empty lists in lists_column_wrapper documentation using LCW = cudf::test::lists_column_wrapper<int>; { cudf::test::lists_column_wrapper<int> a; cudf::test::lists_column_wrapper<int> b{4, 5, 6, 7}; cudf::test::lists_column_wrapper<int> expected{4, 5, 6, 7}; auto result = cudf::concatenate(std::vector<column_view>({a, b})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected); } { cudf::test::lists_column_wrapper<int> a, b, c; cudf::test::lists_column_wrapper<int> d{4, 5, 6, 7}; cudf::test::lists_column_wrapper<int> expected{4, 5, 6, 7}; auto result = cudf::concatenate(std::vector<column_view>({a, b, c, d})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected); } { cudf::test::lists_column_wrapper<int> a{LCW{}}; cudf::test::lists_column_wrapper<int> b{4, 5, 6, 7}; cudf::test::lists_column_wrapper<int> expected{LCW{}, {4, 5, 6, 7}}; auto result = cudf::concatenate(std::vector<column_view>({a, b})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected); } { cudf::test::lists_column_wrapper<int> a{LCW{}}, b{LCW{}}, c{LCW{}}; cudf::test::lists_column_wrapper<int> d{4, 5, 6, 7}; cudf::test::lists_column_wrapper<int> expected{LCW{}, LCW{}, LCW{}, {4, 5, 6, 7}}; auto result = cudf::concatenate(std::vector<column_view>({a, b, c, d})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected); } { cudf::test::lists_column_wrapper<int> a{1, 2}; cudf::test::lists_column_wrapper<int> b{LCW{}}, c{LCW{}}; cudf::test::lists_column_wrapper<int> d{4, 5, 6, 7}; cudf::test::lists_column_wrapper<int> expected{{1, 2}, LCW{}, LCW{}, {4, 5, 6, 7}}; auto result = cudf::concatenate(std::vector<column_view>({a, b, c, d})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected); } } TEST_F(ListsColumnTest, ConcatenateListsWithNulls) { auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); // nulls in the leaves { cudf::test::lists_column_wrapper<int> a{{{0, 1, 2, 3}, valids}}; cudf::test::lists_column_wrapper<int> b{{{4, 6, 7}, valids}}; cudf::test::lists_column_wrapper<int> expected{{{0, 1, 2, 3}, valids}, {{4, 6, 7}, valids}}; auto result = cudf::concatenate(std::vector<column_view>({a, b})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected); } } TEST_F(ListsColumnTest, ConcatenateNestedLists) { { cudf::test::lists_column_wrapper<int> a{{{0, 1}, {2}}, {{4, 5, 6, 7, 8, 9, 10}}}; cudf::test::lists_column_wrapper<int> b{{{6, 7}}, {{8, 9, 10}, {11, 12}}}; cudf::test::lists_column_wrapper<int> expected{ {{0, 1}, {2}}, {{4, 5, 6, 7, 8, 9, 10}}, {{6, 7}}, {{8, 9, 10}, {11, 12}}}; auto result = cudf::concatenate(std::vector<column_view>({a, b})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected); } { cudf::test::lists_column_wrapper<int> a{ {{{0, 1, 2}, {3, 4}}, {{5}, {6, 7}}, {{8, 9}}}, {{{10}, {11, 12}}, {{13, 14, 15, 16}, {15, 16}}, {{17, 18}, {19, 20}}}, {{{50}, {51, 52}}, {{54}, {55, 16}}, {{57, 18}, {59, 60}}}}; cudf::test::lists_column_wrapper<int> b{ {{{21, 22}, {23, 24}}, {{25}, {26, 27}}, {{28, 29, 30}}}, {{{31, 32}, {33, 34}}, {{35, 36}, {37, 38}}, {{39, 40}}}, {{{71, 72}, {74}}, {{75, 76, 77, 78}, {77, 78}}, {{79, 80, 81}}}}; cudf::test::lists_column_wrapper<int> expected{ {{{0, 1, 2}, {3, 4}}, {{5}, {6, 7}}, {{8, 9}}}, {{{10}, {11, 12}}, {{13, 14, 15, 16}, {15, 16}}, {{17, 18}, {19, 20}}}, {{{50}, {51, 52}}, {{54}, {55, 16}}, {{57, 18}, {59, 60}}}, {{{21, 22}, {23, 24}}, {{25}, {26, 27}}, {{28, 29, 30}}}, {{{31, 32}, {33, 34}}, {{35, 36}, {37, 38}}, {{39, 40}}}, {{{71, 72}, {74}}, {{75, 76, 77, 78}, {77, 78}}, {{79, 80, 81}}}}; auto result = cudf::concatenate(std::vector<column_view>({a, b})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected); } } TEST_F(ListsColumnTest, ConcatenateNestedEmptyLists) { using T = int; // to disambiguate between {} == 0 and {} == List{0} // Also, see note about compiler issues when declaring nested // empty lists in lists_column_wrapper documentation using LCW = cudf::test::lists_column_wrapper<T>; { cudf::test::lists_column_wrapper<T> a{{LCW{}}, {{0, 1}, {2, 3}}}; cudf::test::lists_column_wrapper<int> b{{{6, 7}}, {LCW{}, {11, 12}}}; cudf::test::lists_column_wrapper<int> expected{ {LCW{}}, {{0, 1}, {2, 3}}, {{6, 7}}, {LCW{}, {11, 12}}}; auto result = cudf::concatenate(std::vector<column_view>({a, b})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected); } { cudf::test::lists_column_wrapper<int> a{ {{{0, 1, 2}, LCW{}}, {{5}, {6, 7}}, {{8, 9}}}, {{LCW{}}, {{17, 18}, {19, 20}}}, {{LCW{}}}, {{{50}, {51, 52}}, {{53, 54}, {55, 16, 17}}, {{59, 60}}}}; cudf::test::lists_column_wrapper<int> b{ {{{21, 22}, {23, 24}}, {LCW{}, {26, 27}}, {{28, 29, 30}}}, {{{31, 32}, {33, 34}}, {{35, 36}, {37, 38}, {1, 2}}, {{39, 40}}}, {{LCW{}}}}; cudf::test::lists_column_wrapper<int> expected{ {{{0, 1, 2}, LCW{}}, {{5}, {6, 7}}, {{8, 9}}}, {{LCW{}}, {{17, 18}, {19, 20}}}, {{LCW{}}}, {{{50}, {51, 52}}, {{53, 54}, {55, 16, 17}}, {{59, 60}}}, {{{21, 22}, {23, 24}}, {LCW{}, {26, 27}}, {{28, 29, 30}}}, {{{31, 32}, {33, 34}}, {{35, 36}, {37, 38}, {1, 2}}, {{39, 40}}}, {{LCW{}}}}; auto result = cudf::concatenate(std::vector<column_view>({a, b})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected); } } TEST_F(ListsColumnTest, ConcatenateNestedListsWithNulls) { auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); // nulls in the lists { cudf::test::lists_column_wrapper<int> a{{{{0, 1}, {2, 3}}, valids}}; cudf::test::lists_column_wrapper<int> b{{{{4}, {6, 7}}, valids}}; cudf::test::lists_column_wrapper<int> expected{{{{0, 1}, {2, 3}}, valids}, {{{4}, {6, 7}}, valids}}; auto result = cudf::concatenate(std::vector<column_view>({a, b})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected); } // nulls in the lists -and- the values { cudf::test::lists_column_wrapper<int> a{{{{{0}, valids}, {2, 3}}, valids}, {{4, 5}}}; cudf::test::lists_column_wrapper<int> b{{{6, 7}}, {{{{8, 9, 10}, valids}, {11, 12}}, valids}}; cudf::test::lists_column_wrapper<int> expected{{{{{0}, valids}, {2, 3}}, valids}, {{4, 5}}, {{6, 7}}, {{{{8, 9, 10}, valids}, {11, 12}}, valids}}; auto result = cudf::concatenate(std::vector<column_view>({a, b})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expected); } } TEST_F(ListsColumnTest, ConcatenateMismatchedHierarchies) { // to disambiguate between {} == 0 and {} == List{0} // Also, see note about compiler issues when declaring nested // empty lists in lists_column_wrapper documentation using LCW = cudf::test::lists_column_wrapper<int>; { cudf::test::lists_column_wrapper<int> a{{{{LCW{}}}}}; cudf::test::lists_column_wrapper<int> b{{{LCW{}}}}; cudf::test::lists_column_wrapper<int> c{{LCW{}}}; EXPECT_THROW(cudf::concatenate(std::vector<column_view>({a, b, c})), cudf::logic_error); } { std::vector<bool> valids{false}; cudf::test::lists_column_wrapper<int> a{{{{{LCW{}}}}, valids.begin()}}; cudf::test::lists_column_wrapper<int> b{{{LCW{}}}}; cudf::test::lists_column_wrapper<int> c{{LCW{}}}; EXPECT_THROW(cudf::concatenate(std::vector<column_view>({a, b, c})), cudf::logic_error); } { cudf::test::lists_column_wrapper<int> a{{{{LCW{}}}}}; cudf::test::lists_column_wrapper<int> b{1, 2, 3}; cudf::test::lists_column_wrapper<int> c{{3, 4, 5}}; EXPECT_THROW(cudf::concatenate(std::vector<column_view>({a, b, c})), cudf::logic_error); } { cudf::test::lists_column_wrapper<int> a{{{1, 2, 3}}}; cudf::test::lists_column_wrapper<int> b{{4, 5}}; EXPECT_THROW(cudf::concatenate(std::vector<column_view>({a, b})), cudf::logic_error); } } TEST_F(ListsColumnTest, SlicedColumns) { using LCW = cudf::test::lists_column_wrapper<int>; { cudf::test::lists_column_wrapper<int> a{{{1, 1, 1}, {2, 2}, {3, 3}}, {{4, 4, 4}, {5, 5}, {6, 6}}, {{7, 7, 7}, {8, 8}, {9, 9}}, {{10, 10, 10}, {11, 11}, {12, 12}}}; auto split_a = cudf::split(a, {2}); cudf::test::lists_column_wrapper<int> b{{{-1, -1, -1, -1}, {-2}}, {{-3, -3, -3, -3}, {-4}}, {{-5, -5, -5, -5}, {-6}}, {{-7, -7, -7, -7}, {-8}}}; auto split_b = cudf::split(b, {2}); cudf::test::lists_column_wrapper<int> expected0{{{1, 1, 1}, {2, 2}, {3, 3}}, {{4, 4, 4}, {5, 5}, {6, 6}}, {{-1, -1, -1, -1}, {-2}}, {{-3, -3, -3, -3}, {-4}}}; auto result0 = cudf::concatenate(std::vector<column_view>({split_a[0], split_b[0]})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result0, expected0); cudf::test::lists_column_wrapper<int> expected1{{{1, 1, 1}, {2, 2}, {3, 3}}, {{4, 4, 4}, {5, 5}, {6, 6}}, {{-5, -5, -5, -5}, {-6}}, {{-7, -7, -7, -7}, {-8}}}; auto result1 = cudf::concatenate(std::vector<column_view>({split_a[0], split_b[1]})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result1, expected1); cudf::test::lists_column_wrapper<int> expected2{ {{7, 7, 7}, {8, 8}, {9, 9}}, {{10, 10, 10}, {11, 11}, {12, 12}}, {{-1, -1, -1, -1}, {-2}}, {{-3, -3, -3, -3}, {-4}}, }; auto result2 = cudf::concatenate(std::vector<column_view>({split_a[1], split_b[0]})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result2, expected2); cudf::test::lists_column_wrapper<int> expected3{{{7, 7, 7}, {8, 8}, {9, 9}}, {{10, 10, 10}, {11, 11}, {12, 12}}, {{-5, -5, -5, -5}, {-6}}, {{-7, -7, -7, -7}, {-8}}}; auto result3 = cudf::concatenate(std::vector<column_view>({split_a[1], split_b[1]})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result3, expected3); } { cudf::test::lists_column_wrapper<int> a{ {{{1, 1, 1}, {2, 2}}, {{3, 3}}, {{10, 9, 16}, {8, 7, 1}, {6, 8, 2}}}, {LCW{}, {LCW{}}, {{6, 6}, {2}}}, {LCW{}, LCW{}}, {LCW{}, LCW{}, {{10, 10, 10}, {11, 11}, {12, 12}}, LCW{}}}; auto split_a = cudf::split(a, {2}); cudf::test::lists_column_wrapper<int> b{ {{LCW{}}}, {LCW{}, {LCW{}}}, {{{1, 2, 9}, LCW{}}, {{5, 6, 7, 8, 9}, {0}, {15, 17}}}, {{LCW{}}}, }; auto split_b = cudf::split(b, {2}); cudf::test::lists_column_wrapper<int> expected0{ {{{1, 1, 1}, {2, 2}}, {{3, 3}}, {{10, 9, 16}, {8, 7, 1}, {6, 8, 2}}}, {LCW{}, {LCW{}}, {{6, 6}, {2}}}, {{LCW{}}}, {LCW{}, {LCW{}}}}; auto result0 = cudf::concatenate(std::vector<column_view>({split_a[0], split_b[0]})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result0, expected0); cudf::test::lists_column_wrapper<int> expected1{ {{{1, 1, 1}, {2, 2}}, {{3, 3}}, {{10, 9, 16}, {8, 7, 1}, {6, 8, 2}}}, {LCW{}, {LCW{}}, {{6, 6}, {2}}}, {{{1, 2, 9}, LCW{}}, {{5, 6, 7, 8, 9}, {0}, {15, 17}}}, {{LCW{}}}, }; auto result1 = cudf::concatenate(std::vector<column_view>({split_a[0], split_b[1]})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result1, expected1); cudf::test::lists_column_wrapper<int> expected2{ {LCW{}, LCW{}}, {LCW{}, LCW{}, {{10, 10, 10}, {11, 11}, {12, 12}}, LCW{}}, {{LCW{}}}, {LCW{}, {LCW{}}}}; auto result2 = cudf::concatenate(std::vector<column_view>({split_a[1], split_b[0]})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result2, expected2); cudf::test::lists_column_wrapper<int> expected3{ {LCW{}, LCW{}}, {LCW{}, LCW{}, {{10, 10, 10}, {11, 11}, {12, 12}}, LCW{}}, {{{1, 2, 9}, LCW{}}, {{5, 6, 7, 8, 9}, {0}, {15, 17}}}, {{LCW{}}}, }; auto result3 = cudf::concatenate(std::vector<column_view>({split_a[1], split_b[1]})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result3, expected3); } } TEST_F(ListsColumnTest, SlicedColumnsWithNulls) { using LCW = cudf::test::lists_column_wrapper<int>; auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); { cudf::test::lists_column_wrapper<int> a{{{{1, 1, 1}, valids}, {2, 2}, {{3, 3}, valids}}, {{{4, 4, 4}, {{5, 5}, valids}, {6, 6}}, valids}, {{7, 7, 7}, {8, 8}, {9, 9}}, {{{10, 10, 10}, {11, 11}, {{12, 12}, valids}}, valids}}; auto split_a = cudf::split(a, {3}); cudf::test::lists_column_wrapper<int> b{{{{{-1, -1, -1, -1}, valids}, {-2}}, valids}, {{{{-3, -3, -3, -3}, valids}, {-4}}, valids}, {{{{-5, -5, -5, -5}, valids}, {-6}}, valids}, {{{{-7, -7, -7, -7}, valids}, {-8}}, valids}}; auto split_b = cudf::split(b, {3}); cudf::test::lists_column_wrapper<int> expected0{{{{1, 1, 1}, valids}, {2, 2}, {{3, 3}, valids}}, {{{4, 4, 4}, {{5, 5}, valids}, {6, 6}}, valids}, {{7, 7, 7}, {8, 8}, {9, 9}}, {{{{-1, -1, -1, -1}, valids}, {-2}}, valids}, {{{{-3, -3, -3, -3}, valids}, {-4}}, valids}, {{{{-5, -5, -5, -5}, valids}, {-6}}, valids}}; auto result0 = cudf::concatenate(std::vector<column_view>({split_a[0], split_b[0]})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result0, expected0); cudf::test::lists_column_wrapper<int> expected1{{{{1, 1, 1}, valids}, {2, 2}, {{3, 3}, valids}}, {{{4, 4, 4}, {{5, 5}, valids}, {6, 6}}, valids}, {{7, 7, 7}, {8, 8}, {9, 9}}, {{{{-7, -7, -7, -7}, valids}, {-8}}, valids}}; auto result1 = cudf::concatenate(std::vector<column_view>({split_a[0], split_b[1]})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result1, expected1); cudf::test::lists_column_wrapper<int> expected2{ {{{10, 10, 10}, {11, 11}, {{12, 12}, valids}}, valids}, {{{{-1, -1, -1, -1}, valids}, {-2}}, valids}, {{{{-3, -3, -3, -3}, valids}, {-4}}, valids}, {{{{-5, -5, -5, -5}, valids}, {-6}}, valids}}; auto result2 = cudf::concatenate(std::vector<column_view>({split_a[1], split_b[0]})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result2, expected2); cudf::test::lists_column_wrapper<int> expected3{ {{{10, 10, 10}, {11, 11}, {{12, 12}, valids}}, valids}, {{{{-7, -7, -7, -7}, valids}, {-8}}, valids}}; auto result3 = cudf::concatenate(std::vector<column_view>({split_a[1], split_b[1]})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result3, expected3); } { cudf::test::lists_column_wrapper<int> a{ {{{{1, 1, 1}, valids}, {2, 2}}, {{{3, 3}}, valids}, {{{10, 9, 16}, valids}, {8, 7, 1}, {{6, 8, 2}, valids}}}, {{LCW{}, {{LCW{}}, valids}, {{6, 6}, {2}}}, valids}, {{{LCW{}, LCW{}}, valids}}, {LCW{}, LCW{}, {{{10, 10, 10}, {{11, 11}, valids}, {12, 12}}, valids}, LCW{}}}; auto split_a = cudf::split(a, {3}); cudf::test::lists_column_wrapper<int> b{ {{{LCW{}}, valids}}, {{LCW{}, {{LCW{}}, valids}}, valids}, {{{{1, 2, 9}, LCW{}}, {{5, 6, 7, 8, 9}, {0}, {15, 17}}}, valids}, {{LCW{}}}, }; auto split_b = cudf::split(b, {3}); cudf::test::lists_column_wrapper<int> expected0{ {{{{1, 1, 1}, valids}, {2, 2}}, {{{3, 3}}, valids}, {{{10, 9, 16}, valids}, {8, 7, 1}, {{6, 8, 2}, valids}}}, {{LCW{}, {{LCW{}}, valids}, {{6, 6}, {2}}}, valids}, {{{LCW{}, LCW{}}, valids}}, {{{LCW{}}, valids}}, {{LCW{}, {{LCW{}}, valids}}, valids}, {{{{1, 2, 9}, LCW{}}, {{5, 6, 7, 8, 9}, {0}, {15, 17}}}, valids}, }; auto result0 = cudf::concatenate(std::vector<column_view>({split_a[0], split_b[0]})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result0, expected0); cudf::test::lists_column_wrapper<int> expected1{ {{{{1, 1, 1}, valids}, {2, 2}}, {{{3, 3}}, valids}, {{{10, 9, 16}, valids}, {8, 7, 1}, {{6, 8, 2}, valids}}}, {{LCW{}, {{LCW{}}, valids}, {{6, 6}, {2}}}, valids}, {{{LCW{}, LCW{}}, valids}}, {{LCW{}}}, }; auto result1 = cudf::concatenate(std::vector<column_view>({split_a[0], split_b[1]})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result1, expected1); cudf::test::lists_column_wrapper<int> expected2{ {LCW{}, LCW{}, {{{10, 10, 10}, {{11, 11}, valids}, {12, 12}}, valids}, LCW{}}, {{{LCW{}}, valids}}, {{LCW{}, {{LCW{}}, valids}}, valids}, {{{{1, 2, 9}, LCW{}}, {{5, 6, 7, 8, 9}, {0}, {15, 17}}}, valids}, }; auto result2 = cudf::concatenate(std::vector<column_view>({split_a[1], split_b[0]})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result2, expected2); cudf::test::lists_column_wrapper<int> expected3{ {LCW{}, LCW{}, {{{10, 10, 10}, {{11, 11}, valids}, {12, 12}}, valids}, LCW{}}, {{LCW{}}}, }; auto result3 = cudf::concatenate(std::vector<column_view>({split_a[1], split_b[1]})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result3, expected3); } } TEST_F(ListsColumnTest, ListOfStructs) { auto count_iter = thrust::make_counting_iterator(0); // inner structs std::vector<cudf::test::structs_column_wrapper> inner_structs; { // 1. String "names" column. std::vector<std::vector<std::string>> names( {{"Vimes", "Carrot", "Angua", "Cheery", "Detritus", "Slant"}, {}, {}, {"Bill", "Bob", "Sam", "Fred", "Tom"}}); std::vector<std::vector<bool>> names_validity({{1, 1, 1, 1, 1, 1}, {}, {}, {0, 1, 0, 1, 0}}); std::vector<cudf::test::strings_column_wrapper> name_cols; std::transform( count_iter, count_iter + names.size(), std::back_inserter(name_cols), [&](int i) { return cudf::test::strings_column_wrapper( names[i].begin(), names[i].end(), names_validity[i].begin()); }); // 2. Numeric "ages" column. std::vector<std::vector<int>> ages({{5, 10, 15, 20, 25, 30}, {}, {}, {11, 16, 17, 41, 42}}); std::vector<std::vector<bool>> ages_validity({{1, 1, 1, 1, 0, 1}, {}, {}, {1, 1, 1, 0, 0}}); std::vector<cudf::test::fixed_width_column_wrapper<int>> age_cols; std::transform(count_iter, count_iter + ages.size(), std::back_inserter(age_cols), [&](int i) { return cudf::test::fixed_width_column_wrapper<int>( ages[i].begin(), ages[i].end(), ages_validity[i].begin()); }); for (size_t idx = 0; idx < names.size(); idx++) { std::vector<std::unique_ptr<column>> children; children.push_back(name_cols[idx].release()); children.push_back(age_cols[idx].release()); inner_structs.push_back(cudf::test::structs_column_wrapper(std::move(children))); } } // build expected output auto struct_views = std::vector<column_view>( {inner_structs[0], inner_structs[1], inner_structs[2], inner_structs[3]}); auto expected_child = cudf::concatenate(struct_views); cudf::test::fixed_width_column_wrapper<int> offsets_w{0, 1, 1, 1, 1, 4, 6, 6, 6, 10, 11}; auto expected = make_lists_column(10, offsets_w.release(), std::move(expected_child), 0, rmm::device_buffer{}); // lists std::vector<cudf::test::fixed_width_column_wrapper<int>> offsets; offsets.push_back({0, 1, 1, 1, 1, 4, 6, 6}); offsets.push_back({0}); offsets.push_back({0}); offsets.push_back({0, 0, 4, 5}); // concatenate as lists std::vector<std::unique_ptr<column>> src; for (size_t idx = 0; idx < inner_structs.size(); idx++) { int size = static_cast<column_view>(offsets[idx]).size() - 1; src.push_back(make_lists_column( size, offsets[idx].release(), inner_structs[idx].release(), 0, rmm::device_buffer{})); } // concatenate auto result = cudf::concatenate(std::vector<column_view>({*src[0], *src[1], *src[2], *src[3]})); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected); } template <typename T> struct FixedPointTestAllReps : public cudf::test::BaseFixture {}; struct FixedPointTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(FixedPointTestAllReps, cudf::test::FixedPointTypes); TYPED_TEST(FixedPointTestAllReps, FixedPointConcatentate) { using namespace numeric; using decimalXX = TypeParam; using fw_wrapper = cudf::test::fixed_width_column_wrapper<decimalXX>; auto begin = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return decimalXX{i}; }); auto const vec = std::vector<decimalXX>(begin, begin + 1000); auto const a = fw_wrapper(vec.begin(), /***/ vec.begin() + 300); auto const b = fw_wrapper(vec.begin() + 300, vec.begin() + 700); auto const c = fw_wrapper(vec.begin() + 700, vec.end()); auto const results = cudf::concatenate(std::vector<cudf::column_view>{a, b, c}); auto const expected = fw_wrapper(vec.begin(), vec.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } TEST_F(FixedPointTest, FixedPointConcatentate) { using namespace numeric; using fp_wrapper = cudf::test::fixed_point_column_wrapper<int32_t>; auto begin = thrust::make_counting_iterator(0); auto const vec = std::vector<int32_t>(begin, begin + 1000); auto const a = fp_wrapper(vec.begin(), /***/ vec.begin() + 300, scale_type{-2}); auto const b = fp_wrapper(vec.begin() + 300, vec.begin() + 700, scale_type{-2}); auto const c = fp_wrapper(vec.begin() + 700, vec.end(), /*****/ scale_type{-2}); auto const results = cudf::concatenate(std::vector<cudf::column_view>{a, b, c}); auto const expected = fp_wrapper(vec.begin(), vec.end(), scale_type{-2}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } TEST_F(FixedPointTest, FixedPointScaleMismatch) { using namespace numeric; using fp_wrapper = cudf::test::fixed_point_column_wrapper<int32_t>; auto begin = thrust::make_counting_iterator(0); auto const vec = std::vector<int32_t>(begin, begin + 1000); auto const a = fp_wrapper(vec.begin(), /***/ vec.begin() + 300, scale_type{-1}); auto const b = fp_wrapper(vec.begin() + 300, vec.begin() + 700, scale_type{-2}); auto const c = fp_wrapper(vec.begin() + 700, vec.end(), /*****/ scale_type{-3}); EXPECT_THROW(cudf::concatenate(std::vector<cudf::column_view>{a, b, c}), cudf::logic_error); } struct DictionaryConcatTest : public cudf::test::BaseFixture {}; TEST_F(DictionaryConcatTest, StringsKeys) { cudf::test::strings_column_wrapper strings( {"eee", "aaa", "ddd", "bbb", "", "", "ccc", "ccc", "ccc", "eee", "aaa"}, {1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1}); auto dictionary = cudf::dictionary::encode(strings); std::vector<cudf::size_type> splits{0, 2, 2, 5, 5, 7, 7, 7, 7, 11}; std::vector<cudf::column_view> views = cudf::slice(dictionary->view(), splits); // concatenate should recreate the original column auto result = cudf::concatenate(views); auto decoded = cudf::dictionary::decode(result->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*decoded, strings); } template <typename T> struct DictionaryConcatTestFW : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(DictionaryConcatTestFW, cudf::test::FixedWidthTypes); TYPED_TEST(DictionaryConcatTestFW, FixedWidthKeys) { cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> original( {20, 10, 0, 5, 15, 15, 10, 5, 20}, {1, 1, 0, 1, 1, 1, 1, 1, 1}); auto dictionary = cudf::dictionary::encode(original); std::vector<cudf::size_type> splits{0, 3, 3, 5, 5, 9}; std::vector<cudf::column_view> views = cudf::slice(dictionary->view(), splits); // concatenated result should equal the original column auto result = cudf::concatenate(views); auto decoded = cudf::dictionary::decode(result->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*decoded, original); } TEST_F(DictionaryConcatTest, ErrorsTest) { cudf::test::strings_column_wrapper strings({"aaa", "ddd", "bbb"}); auto dictionary1 = cudf::dictionary::encode(strings); cudf::test::fixed_width_column_wrapper<int32_t> integers({10, 30, 20}); auto dictionary2 = cudf::dictionary::encode(integers); std::vector<cudf::column_view> views({dictionary1->view(), dictionary2->view()}); EXPECT_THROW(cudf::concatenate(views), cudf::logic_error); std::vector<cudf::column_view> empty; EXPECT_THROW(cudf::concatenate(empty), cudf::logic_error); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/gather_str_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf/column/column_view.hpp> #include <cudf/copying.hpp> #include <cudf/detail/gather.hpp> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> #include <rmm/mr/device/per_device_resource.hpp> class GatherTestStr : public cudf::test::BaseFixture {}; TEST_F(GatherTestStr, StringColumn) { cudf::test::fixed_width_column_wrapper<int16_t> col1{{1, 2, 3, 4, 5, 6}, {1, 1, 0, 1, 0, 1}}; cudf::test::strings_column_wrapper col2{{"This", "is", "not", "a", "string", "type"}, {1, 1, 1, 1, 1, 0}}; cudf::table_view source_table{{col1, col2}}; cudf::test::fixed_width_column_wrapper<int16_t> gather_map{{0, 1, 3, 4}}; cudf::test::fixed_width_column_wrapper<int16_t> exp_col1{{1, 2, 4, 5}, {1, 1, 1, 0}}; cudf::test::strings_column_wrapper exp_col2{{"This", "is", "a", "string"}, {1, 1, 1, 1}}; cudf::table_view expected{{exp_col1, exp_col2}}; auto got = cudf::gather(source_table, gather_map); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); } TEST_F(GatherTestStr, GatherSlicedStringsColumn) { cudf::test::strings_column_wrapper strings{{"This", "is", "not", "a", "string", "type"}, {1, 1, 1, 1, 1, 0}}; std::vector<cudf::size_type> slice_indices{0, 2, 2, 3, 3, 6}; auto sliced_strings = cudf::slice(strings, slice_indices); { cudf::test::fixed_width_column_wrapper<int16_t> gather_map{{1, 0, 1}}; cudf::test::strings_column_wrapper expected_strings{{"is", "This", "is"}, {1, 1, 1}}; cudf::table_view expected{{expected_strings}}; auto result = cudf::gather(cudf::table_view{{sliced_strings[0]}}, gather_map); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, result->view()); } { cudf::test::fixed_width_column_wrapper<int16_t> gather_map{{0, 0, 0}}; cudf::test::strings_column_wrapper expected_strings{{"not", "not", "not"}, {1, 1, 1}}; cudf::table_view expected{{expected_strings}}; auto result = cudf::gather(cudf::table_view{{sliced_strings[1]}}, gather_map); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, result->view()); } { cudf::test::fixed_width_column_wrapper<int16_t> gather_map{{2, 1, 0}}; cudf::test::strings_column_wrapper expected_strings{{"", "string", "a"}, {0, 1, 1}}; cudf::table_view expected{{expected_strings}}; auto result = cudf::gather(cudf::table_view{{sliced_strings[2]}}, gather_map); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, result->view()); } } TEST_F(GatherTestStr, Gather) { std::vector<char const*> h_strings{"eee", "bb", "", "aa", "bbb", "ééé"}; cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end()); cudf::table_view source_table({strings}); std::vector<int32_t> h_map{4, 1, 5, 2, 7}; cudf::test::fixed_width_column_wrapper<int32_t> gather_map(h_map.begin(), h_map.end()); auto results = cudf::detail::gather(source_table, gather_map, cudf::out_of_bounds_policy::NULLIFY, cudf::detail::negative_index_policy::NOT_ALLOWED, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); std::vector<char const*> h_expected; std::vector<int32_t> expected_validity; for (auto itr = h_map.begin(); itr != h_map.end(); ++itr) { auto index = *itr; if ((0 <= index) && (index < static_cast<decltype(index)>(h_strings.size()))) { h_expected.push_back(h_strings[index]); expected_validity.push_back(1); } else { h_expected.push_back(""); expected_validity.push_back(0); } } cudf::test::strings_column_wrapper expected( h_expected.begin(), h_expected.end(), expected_validity.begin()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view().column(0), expected); } TEST_F(GatherTestStr, GatherDontCheckOutOfBounds) { std::vector<char const*> h_strings{"eee", "bb", "", "aa", "bbb", "ééé"}; cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end()); cudf::table_view source_table({strings}); std::vector<int32_t> h_map{3, 4, 0, 0}; cudf::test::fixed_width_column_wrapper<int32_t> gather_map(h_map.begin(), h_map.end()); auto results = cudf::detail::gather(source_table, gather_map, cudf::out_of_bounds_policy::DONT_CHECK, cudf::detail::negative_index_policy::NOT_ALLOWED, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); std::vector<char const*> h_expected; for (auto itr = h_map.begin(); itr != h_map.end(); ++itr) { h_expected.push_back(h_strings[*itr]); } cudf::test::strings_column_wrapper expected(h_expected.begin(), h_expected.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view().column(0), expected); } TEST_F(GatherTestStr, GatherEmptyMapStringsColumn) { auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING); cudf::test::fixed_width_column_wrapper<cudf::size_type> gather_map; auto results = cudf::detail::gather(cudf::table_view({zero_size_strings_column->view()}), gather_map, cudf::out_of_bounds_policy::NULLIFY, cudf::detail::negative_index_policy::NOT_ALLOWED, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); cudf::test::expect_column_empty(results->get_column(0).view()); } TEST_F(GatherTestStr, GatherZeroSizeStringsColumn) { auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING); cudf::test::fixed_width_column_wrapper<int32_t> gather_map({0}); cudf::test::strings_column_wrapper expected{std::pair<std::string, bool>{"", false}}; auto results = cudf::detail::gather(cudf::table_view({zero_size_strings_column->view()}), gather_map, cudf::out_of_bounds_policy::NULLIFY, cudf::detail::negative_index_policy::NOT_ALLOWED, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, results->get_column(0).view()); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/copy_range_tests.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/column/column.hpp> #include <cudf/column/column_view.hpp> #include <cudf/copying.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/dictionary/encode.hpp> #include <thrust/iterator/constant_iterator.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/iterator/transform_iterator.h> auto all_valid = [](cudf::size_type row) { return true; }; auto even_valid = [](cudf::size_type row) { return (row % 2 == 0); }; template <typename T> class CopyRangeTypedTestFixture : public cudf::test::BaseFixture { public: static constexpr cudf::size_type column_size{1000}; void test(cudf::column_view const& source, cudf::column_view const& expected, cudf::mutable_column_view& target, cudf::size_type source_begin, cudf::size_type source_end, cudf::size_type target_begin) { static_assert(cudf::is_fixed_width<T>(), "this code assumes fixed-width types."); // test the out-of-place version first const cudf::column_view immutable_view{target}; auto p_ret = cudf::copy_range(source, immutable_view, source_begin, source_end, target_begin); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*p_ret, expected); // test the in-place version second EXPECT_NO_THROW( cudf::copy_range_in_place(source, target, source_begin, source_end, target_begin)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(target, expected); } }; TYPED_TEST_SUITE(CopyRangeTypedTestFixture, cudf::test::FixedWidthTypesWithoutFixedPoint); TYPED_TEST(CopyRangeTypedTestFixture, CopyWithNulls) { using T = TypeParam; cudf::size_type size{CopyRangeTypedTestFixture<T>::column_size}; cudf::size_type source_begin{9}; cudf::size_type source_end{size - 50}; cudf::size_type target_begin{30}; auto target_end = target_begin + (source_end - source_begin); auto row_diff = source_begin - target_begin; cudf::test::fixed_width_column_wrapper<T, int32_t> target( thrust::make_counting_iterator(0), thrust::make_counting_iterator(0) + size, cudf::detail::make_counting_transform_iterator(0, all_valid)); auto source_elements = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i * 2; }); cudf::test::fixed_width_column_wrapper<T, typename decltype(source_elements)::value_type> source( source_elements, source_elements + size, cudf::detail::make_counting_transform_iterator(0, even_valid)); auto expected_elements = cudf::detail::make_counting_transform_iterator(0, [target_begin, target_end, row_diff](auto i) { return ((i >= target_begin) && (i < target_end)) ? (i + row_diff) * 2 : i; }); cudf::test::fixed_width_column_wrapper<T, typename decltype(expected_elements)::value_type> expected(expected_elements, expected_elements + size, cudf::detail::make_counting_transform_iterator( 0, [target_begin, target_end, row_diff](auto i) { return ((i >= target_begin) && (i < target_end)) ? even_valid(i + row_diff) : all_valid(i); })); cudf::mutable_column_view target_view{target}; this->test(source, expected, target_view, source_begin, source_end, target_begin); } TYPED_TEST(CopyRangeTypedTestFixture, CopyNoNulls) { using T = TypeParam; cudf::size_type size{CopyRangeTypedTestFixture<T>::column_size}; cudf::size_type source_begin{9}; cudf::size_type source_end{size - 50}; cudf::size_type target_begin{30}; auto target_end = target_begin + (source_end - source_begin); auto row_diff = source_begin - target_begin; cudf::test::fixed_width_column_wrapper<T, int32_t> target( thrust::make_counting_iterator(0), thrust::make_counting_iterator(0) + size); auto source_elements = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i * 2; }); cudf::test::fixed_width_column_wrapper<T, typename decltype(source_elements)::value_type> source( source_elements, source_elements + size); auto expected_elements = cudf::detail::make_counting_transform_iterator(0, [target_begin, target_end, row_diff](auto i) { return ((i >= target_begin) && (i < target_end)) ? (i + row_diff) * 2 : i; }); cudf::test::fixed_width_column_wrapper<T, typename decltype(expected_elements)::value_type> expected(expected_elements, expected_elements + size); cudf::mutable_column_view target_view{target}; this->test(source, expected, target_view, source_begin, source_end, target_begin); } TYPED_TEST(CopyRangeTypedTestFixture, CopyWithNullsNonzeroOffset) { using T = TypeParam; cudf::size_type size{CopyRangeTypedTestFixture<T>::column_size}; cudf::size_type source_offset{27}; cudf::size_type source_begin{9}; cudf::size_type source_end{50}; cudf::size_type target_offset{58}; cudf::size_type target_begin{30}; auto target_end = target_begin + (source_end - source_begin); auto row_diff = (source_offset + source_begin) - (target_offset + target_begin); cudf::test::fixed_width_column_wrapper<T, int32_t> target( thrust::make_counting_iterator(0), thrust::make_counting_iterator(0) + size, cudf::detail::make_counting_transform_iterator(0, all_valid)); cudf::mutable_column_view tmp = target; cudf::mutable_column_view target_slice(tmp.type(), tmp.size() - target_offset, tmp.head<T>(), tmp.null_mask(), tmp.null_count(), target_offset); auto source_elements = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i * 2; }); cudf::test::fixed_width_column_wrapper<T, typename decltype(source_elements)::value_type> source( source_elements, source_elements + size, cudf::detail::make_counting_transform_iterator(0, even_valid)); auto source_slice = cudf::slice(source, std::vector<cudf::size_type>{source_offset, size})[0]; auto expected_elements = cudf::detail::make_counting_transform_iterator( 0, [target_offset, target_begin, target_end, row_diff](auto i) { return ((i >= target_offset + target_begin) && (i < target_offset + target_end)) ? (i + row_diff) * 2 : i; }); cudf::test::fixed_width_column_wrapper<T, typename decltype(expected_elements)::value_type> expected(expected_elements, expected_elements + size, cudf::detail::make_counting_transform_iterator( 0, [target_offset, target_begin, target_end, row_diff](auto i) { return ((i >= target_offset + target_begin) && (i < target_offset + target_end)) ? even_valid(i + row_diff) : all_valid(i); })); auto expected_slice = cudf::slice(expected, std::vector<cudf::size_type>{target_offset, size})[0]; this->test(source_slice, expected_slice, target_slice, source_begin, source_end, target_begin); } class CopyRangeTestFixture : public cudf::test::BaseFixture {}; TEST_F(CopyRangeTestFixture, CopyWithNullsString) { cudf::size_type size{100}; cudf::size_type source_begin{9}; cudf::size_type source_end{50}; cudf::size_type target_begin{30}; auto target_end = target_begin + (source_end - source_begin); auto row_diff = source_begin - target_begin; auto target_elements = cudf::detail::make_counting_transform_iterator( 0, [](auto i) { return "#" + std::to_string(i); }); auto target = cudf::test::strings_column_wrapper( target_elements, target_elements + size, cudf::detail::make_counting_transform_iterator(0, all_valid)); auto source_elements = cudf::detail::make_counting_transform_iterator( 0, [](auto i) { return "#" + std::to_string(i * 2); }); auto source = cudf::test::strings_column_wrapper( source_elements, source_elements + size, cudf::detail::make_counting_transform_iterator(0, even_valid)); auto expected_elements = cudf::detail::make_counting_transform_iterator(0, [target_begin, target_end, row_diff](auto i) { auto num = std::to_string(((i >= target_begin) && (i < target_end)) ? (i + row_diff) * 2 : i); return "#" + num; }); auto expected = cudf::test::strings_column_wrapper( expected_elements, expected_elements + size, cudf::detail::make_counting_transform_iterator(0, [target_begin, target_end, row_diff](auto i) { return ((i >= target_begin) && (i < target_end)) ? even_valid(i + row_diff) : all_valid(i); })); auto p_ret = cudf::copy_range(source, target, source_begin, source_end, target_begin); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*p_ret, expected); } TEST_F(CopyRangeTestFixture, CopyNoNullsString) { cudf::size_type size{100}; cudf::size_type source_begin{9}; cudf::size_type source_end{50}; cudf::size_type target_begin{30}; auto target_end = target_begin + (source_end - source_begin); auto row_diff = source_begin - target_begin; auto target_elements = cudf::detail::make_counting_transform_iterator( 0, [](auto i) { return "#" + std::to_string(i); }); auto target = cudf::test::strings_column_wrapper(target_elements, target_elements + size); auto source_elements = cudf::detail::make_counting_transform_iterator( 0, [](auto i) { return "#" + std::to_string(i * 2); }); auto source = cudf::test::strings_column_wrapper(source_elements, source_elements + size); auto expected_elements = cudf::detail::make_counting_transform_iterator(0, [target_begin, target_end, row_diff](auto i) { auto num = std::to_string(((i >= target_begin) && (i < target_end)) ? (i + row_diff) * 2 : i); return "#" + num; }); auto expected = cudf::test::strings_column_wrapper(expected_elements, expected_elements + size); auto p_ret = cudf::copy_range(source, target, source_begin, source_end, target_begin); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*p_ret, expected); } TEST_F(CopyRangeTestFixture, CopyWithNullsNonzeroOffsetString) { cudf::size_type size{200}; cudf::size_type source_offset{27}; cudf::size_type source_begin{9}; cudf::size_type source_end{50}; cudf::size_type target_offset{58}; cudf::size_type target_begin{30}; auto target_end = target_begin + (source_end - source_begin); auto row_diff = (source_offset + source_begin) - (target_offset + target_begin); auto target_elements = cudf::detail::make_counting_transform_iterator( 0, [](auto i) { return "#" + std::to_string(i); }); auto target = cudf::test::strings_column_wrapper( target_elements, target_elements + size, cudf::detail::make_counting_transform_iterator(0, all_valid)); auto target_slice = cudf::slice(target, std::vector<cudf::size_type>{target_offset, size})[0]; auto source_elements = cudf::detail::make_counting_transform_iterator( 0, [](auto i) { return "#" + std::to_string(i * 2); }); auto source = cudf::test::strings_column_wrapper( source_elements, source_elements + size, cudf::detail::make_counting_transform_iterator(0, even_valid)); auto source_slice = cudf::slice(source, std::vector<cudf::size_type>{source_offset, size})[0]; auto expected_elements = cudf::detail::make_counting_transform_iterator( 0, [target_offset, target_begin, target_end, row_diff](auto i) { auto num = std::to_string(((i >= target_offset + target_begin) && (i < target_offset + target_end)) ? (i + row_diff) * 2 : i); return "#" + num; }); auto expected = cudf::test::strings_column_wrapper( expected_elements, expected_elements + size, cudf::detail::make_counting_transform_iterator( 0, [target_offset, target_begin, target_end, row_diff](auto i) { return ((i >= target_offset + target_begin) && (i < target_offset + target_end)) ? even_valid(i + row_diff) : all_valid(i); })); auto expected_slice = cudf::slice(expected, std::vector<cudf::size_type>{target_offset, size})[0]; auto p_ret = cudf::copy_range(source_slice, target_slice, source_begin, source_end, target_begin); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*p_ret, expected_slice); } TEST_F(CopyRangeTestFixture, CopyDictionary) { cudf::size_type source_begin{1}; cudf::size_type source_end{5}; cudf::size_type target_begin{3}; std::vector<std::string> source_elements({"e", "b", "a", "c", "c", "e", "b", "c", "e", "b"}); std::vector<std::string> target_elements({"a", "e", "d", "c", "c", "b", "b", "a", "f", "f"}); std::vector<std::string> expected_elements(target_elements); std::copy(source_elements.begin() + source_begin, source_elements.begin() + source_end, expected_elements.begin() + target_begin); { auto source = cudf::dictionary::encode( cudf::test::strings_column_wrapper(source_elements.begin(), source_elements.end())); auto target = cudf::dictionary::encode( cudf::test::strings_column_wrapper(target_elements.begin(), target_elements.end())); auto result = cudf::copy_range(source->view(), target->view(), source_begin, source_end, target_begin); auto decoded = cudf::dictionary::decode(cudf::dictionary_column_view(result->view())); auto expected = cudf::test::strings_column_wrapper(expected_elements.begin(), expected_elements.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*decoded, expected); } auto source_validity = thrust::make_transform_iterator( thrust::make_counting_iterator<cudf::size_type>(0), [](auto i) { return i != 3; }); auto target_validity = thrust::make_transform_iterator( thrust::make_counting_iterator<cudf::size_type>(0), [](auto i) { return i != 3 && i != 9; }); auto expected_validity = thrust::make_transform_iterator( thrust::make_counting_iterator<cudf::size_type>(0), [](auto i) { return i != 5 && i != 9; }); { auto source = cudf::dictionary::encode(cudf::test::strings_column_wrapper( source_elements.begin(), source_elements.end(), source_validity)); auto target = cudf::dictionary::encode(cudf::test::strings_column_wrapper( target_elements.begin(), target_elements.end(), target_validity)); auto result = cudf::copy_range(source->view(), target->view(), source_begin, source_end, target_begin); auto decoded = cudf::dictionary::decode(cudf::dictionary_column_view(result->view())); auto expected = cudf::test::strings_column_wrapper( expected_elements.begin(), expected_elements.end(), expected_validity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*decoded, expected); } } class CopyRangeErrorTestFixture : public cudf::test::BaseFixture {}; TEST_F(CopyRangeErrorTestFixture, InvalidInplaceCall) { cudf::size_type size{100}; auto target = cudf::test::fixed_width_column_wrapper<int32_t>( thrust::make_counting_iterator(0), thrust::make_counting_iterator(0) + size); auto source = cudf::test::fixed_width_column_wrapper<int32_t>( thrust::make_counting_iterator(0), thrust::make_counting_iterator(0) + size, cudf::detail::make_counting_transform_iterator(0, even_valid)); cudf::mutable_column_view target_view{target}; // source has null values but target is not nullable. EXPECT_THROW(cudf::copy_range_in_place(source, target_view, 0, size, 0), cudf::logic_error); std::vector<std::string> strings{"", "this", "is", "a", "column", "of", "strings"}; auto target_string = cudf::test::strings_column_wrapper(strings.begin(), strings.end()); auto source_string = cudf::test::strings_column_wrapper(strings.begin(), strings.end()); cudf::mutable_column_view target_view_string{target_string}; EXPECT_THROW(cudf::copy_range_in_place(source_string, target_view_string, 0, size, 0), cudf::logic_error); } TEST_F(CopyRangeErrorTestFixture, InvalidRange) { cudf::size_type size{100}; auto target = cudf::test::fixed_width_column_wrapper<int32_t>( thrust::make_counting_iterator(0), thrust::make_counting_iterator(0) + size); auto source = cudf::test::fixed_width_column_wrapper<int32_t>( thrust::make_counting_iterator(0), thrust::make_counting_iterator(0) + size); cudf::mutable_column_view target_view{target}; cudf::column_view source_view{source}; // empty_range == no-op, this is valid EXPECT_NO_THROW(cudf::copy_range_in_place(source, target_view, 0, 0, 0)); EXPECT_NO_THROW(auto p_ret = cudf::copy_range(source, target, 0, 0, 0)); // source_begin is negative EXPECT_THROW(cudf::copy_range_in_place(source, target_view, -1, size, 0), cudf::logic_error); EXPECT_THROW(auto p_ret = cudf::copy_range(source, target, -1, size, 0), cudf::logic_error); // source_begin > source_end EXPECT_THROW(cudf::copy_range_in_place(source, target_view, 10, 5, 0), cudf::logic_error); EXPECT_THROW(auto p_ret = cudf::copy_range(source, target, 10, 5, 0), cudf::logic_error); // source_begin >= source.size() EXPECT_THROW(cudf::copy_range_in_place(source, target_view, 101, 100, 0), cudf::logic_error); EXPECT_THROW(auto p_ret = cudf::copy_range(source, target, 101, 100, 0), cudf::logic_error); // source_end > source.size() EXPECT_THROW(cudf::copy_range_in_place(source, target_view, 99, 101, 0), cudf::logic_error); EXPECT_THROW(auto p_ret = cudf::copy_range(source, target, 99, 101, 0), cudf::logic_error); // target_begin < 0 EXPECT_THROW(cudf::copy_range_in_place(source, target_view, 50, 100, -5), cudf::logic_error); EXPECT_THROW(auto p_ret = cudf::copy_range(source, target, 50, 100, -5), cudf::logic_error); // target_begin >= target.size() EXPECT_THROW(cudf::copy_range_in_place(source, target_view, 50, 100, 100), cudf::logic_error); EXPECT_THROW(auto p_ret = cudf::copy_range(source, target, 50, 100, 100), cudf::logic_error); // target_begin + (source_end - source_begin) > target.size() EXPECT_THROW(cudf::copy_range_in_place(source, target_view, 50, 100, 80), cudf::logic_error); EXPECT_THROW(auto p_ret = cudf::copy_range(source, target, 50, 100, 80), cudf::logic_error); // Empty column target = cudf::test::fixed_width_column_wrapper<int32_t>{}; source = cudf::test::fixed_width_column_wrapper<int32_t>{}; target_view = target; source_view = source; // empty column == no-op, this is valid EXPECT_NO_THROW(cudf::copy_range_in_place(source_view, target_view, 0, source_view.size(), 0)); EXPECT_NO_THROW(auto p_ret = cudf::copy_range(source_view, target, 0, source_view.size(), 0)); } TEST_F(CopyRangeErrorTestFixture, DTypeMismatch) { cudf::size_type size{100}; auto target = cudf::test::fixed_width_column_wrapper<int32_t>( thrust::make_counting_iterator(0), thrust::make_counting_iterator(0) + size); auto source = cudf::test::fixed_width_column_wrapper<float>( thrust::make_counting_iterator(0), thrust::make_counting_iterator(0) + size); cudf::mutable_column_view target_view{target}; EXPECT_THROW(cudf::copy_range_in_place(source, target_view, 0, 100, 0), cudf::logic_error); EXPECT_THROW(cudf::copy_range(source, target, 0, 100, 0), cudf::logic_error); auto dict_target = cudf::dictionary::encode(target); auto dict_source = cudf::dictionary::encode(source); EXPECT_THROW(cudf::copy_range(dict_source->view(), dict_target->view(), 0, 100, 0), cudf::logic_error); } template <typename T> struct FixedPointTypesCopyRange : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(FixedPointTypesCopyRange, cudf::test::FixedPointTypes); TYPED_TEST(FixedPointTypesCopyRange, FixedPointSimple) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const source = fp_wrapper{{110, 220, 330, 440, 550, 660}, scale_type{-2}}; auto const target = fp_wrapper{{0, 0, 0, 0, 0, 0}, scale_type{-2}}; auto const expected = fp_wrapper{{0, 220, 330, 440, 0, 0}, scale_type{-2}}; auto const result = cudf::copy_range(source, target, 1, 4, 1); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointTypesCopyRange, FixedPointLarge) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto s = thrust::make_counting_iterator(-1000); auto t = thrust::make_constant_iterator(0); auto e = cudf::detail::make_counting_transform_iterator(500, [](int i) { return i < 1000 ? i : 0; }); auto const source = fp_wrapper{s, s + 2000, scale_type{-1}}; auto const target = fp_wrapper{t, t + 2000, scale_type{-1}}; auto const expected = fp_wrapper{e, e + 2000, scale_type{-1}}; auto const result = cudf::copy_range(source, target, 1500, 2000, 0); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointTypesCopyRange, FixedPointScaleMismatch) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const source = fp_wrapper{{110, 220, 330, 440, 550, 660}, scale_type{-2}}; auto const target = fp_wrapper{{0, 0, 0, 0, 0, 0}, scale_type{-3}}; EXPECT_THROW(cudf::copy_range(source, target, 1, 4, 1), cudf::logic_error); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/split_tests.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <tests/copying/slice_tests.cuh> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_list_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/column/column_factories.hpp> #include <cudf/contiguous_split.hpp> #include <cudf/copying.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/filling.hpp> #include <rmm/device_buffer.hpp> #include <thrust/iterator/counting_iterator.h> #include <thrust/iterator/transform_iterator.h> #include <string> #include <vector> std::vector<cudf::size_type> splits_to_indices(std::vector<cudf::size_type> splits, cudf::size_type size) { std::vector<cudf::size_type> indices{0}; std::for_each(splits.begin(), splits.end(), [&indices](auto split) { indices.push_back(split); // This for end indices.push_back(split); // This for the start }); indices.push_back(size); // This to include rest of the elements return indices; } template <typename T> std::vector<cudf::test::fixed_width_column_wrapper<T>> create_expected_columns_for_splits( std::vector<cudf::size_type> const& splits, cudf::size_type size, bool nullable) { // convert splits to slice indices std::vector<cudf::size_type> indices = splits_to_indices(splits, size); return create_expected_columns<T>(indices, nullable); } template <typename T> std::vector<cudf::test::fixed_width_column_wrapper<T>> create_expected_columns_for_splits( std::vector<cudf::size_type> const& splits, std::vector<T> const& elements, bool nullable) { // convert splits to slice indices std::vector<cudf::size_type> indices = splits_to_indices(splits, elements.size()); return create_expected_columns<T>(indices, elements.begin(), nullable); } template <typename T> std::vector<cudf::test::fixed_width_column_wrapper<T>> create_expected_columns_for_splits( std::vector<cudf::size_type> const& splits, cudf::size_type size, std::vector<bool> const& validity) { // convert splits to slice indices std::vector<cudf::size_type> indices = splits_to_indices(splits, size); return create_expected_columns<T>(indices, validity); } template <typename T> std::vector<cudf::test::fixed_width_column_wrapper<T>> create_expected_columns_for_splits( std::vector<cudf::size_type> const& splits, std::vector<T> const& elements, std::vector<bool> const& validity) { // convert splits to slice indices std::vector<cudf::size_type> indices = splits_to_indices(splits, elements.size()); return create_expected_columns<T>(indices, elements.begin(), validity); } std::vector<cudf::test::strings_column_wrapper> create_expected_string_columns_for_splits( std::vector<std::string> strings, std::vector<cudf::size_type> const& splits, bool nullable) { std::vector<cudf::size_type> indices = splits_to_indices(splits, strings.size()); return create_expected_string_columns(strings, indices, nullable); } std::vector<cudf::test::strings_column_wrapper> create_expected_string_columns_for_splits( std::vector<std::string> strings, std::vector<cudf::size_type> const& splits, std::vector<bool> const& validity) { std::vector<cudf::size_type> indices = splits_to_indices(splits, strings.size()); return create_expected_string_columns(strings, indices, validity); } std::vector<std::vector<bool>> create_expected_validity(std::vector<cudf::size_type> const& splits, std::vector<bool> const& validity) { std::vector<std::vector<bool>> result = {}; std::vector<cudf::size_type> indices = splits_to_indices(splits, validity.size()); for (unsigned long index = 0; index < indices.size(); index += 2) { result.push_back( std::vector<bool>(validity.begin() + indices[index], validity.begin() + indices[index + 1])); } return result; } template <typename T> std::vector<cudf::table> create_expected_tables_for_splits( cudf::size_type num_cols, std::vector<cudf::size_type> const& splits, cudf::size_type col_size, bool nullable) { std::vector<cudf::size_type> indices = splits_to_indices(splits, col_size); return create_expected_tables<T>(num_cols, indices, nullable); } std::vector<cudf::table> create_expected_string_tables_for_splits( std::vector<std::string> const strings[2], std::vector<cudf::size_type> const& splits, bool nullable) { std::vector<cudf::size_type> indices = splits_to_indices(splits, strings[0].size()); return create_expected_string_tables(strings, indices, nullable); } std::vector<cudf::table> create_expected_string_tables_for_splits( std::vector<std::string> const strings[2], std::vector<bool> const validity[2], std::vector<cudf::size_type> const& splits) { std::vector<cudf::size_type> indices = splits_to_indices(splits, strings[0].size()); auto ret_cols_0 = create_expected_string_columns(strings[0], indices, validity[0]); auto ret_cols_1 = create_expected_string_columns(strings[1], indices, validity[1]); std::vector<cudf::table> ret_tables; for (std::size_t i = 0; i < ret_cols_0.size(); ++i) { std::vector<std::unique_ptr<cudf::column>> scols; scols.push_back(ret_cols_0[i].release()); scols.push_back(ret_cols_1[i].release()); ret_tables.emplace_back(std::move(scols)); } return ret_tables; } template <typename T> struct SplitTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(SplitTest, cudf::test::NumericTypes); TYPED_TEST(SplitTest, SplitEndLessThanSize) { using T = TypeParam; cudf::size_type start = 0; cudf::size_type size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::test::fixed_width_column_wrapper<T> col = create_fixed_columns<T>(start, size, valids); std::vector<cudf::size_type> splits{2, 5, 7}; std::vector<cudf::test::fixed_width_column_wrapper<T>> expected = create_expected_columns_for_splits<T>(splits, size, true); std::vector<cudf::column_view> result = cudf::split(col, splits); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected[index], result[index]); } } TYPED_TEST(SplitTest, SplitEndToSize) { using T = TypeParam; cudf::size_type start = 0; cudf::size_type size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::test::fixed_width_column_wrapper<T> col = create_fixed_columns<T>(start, size, valids); std::vector<cudf::size_type> splits{2, 5, 10, 10, 10, 10}; std::vector<cudf::test::fixed_width_column_wrapper<T>> expected = create_expected_columns_for_splits<T>(splits, size, true); std::vector<cudf::column_view> result = cudf::split(col, splits); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected[index], result[index]); } } // common functions for testing split/contiguous_split template <typename T, typename SplitFunc, typename CompareFunc> void split_custom_column(SplitFunc Split, CompareFunc Compare, int size, std::vector<cudf::size_type> const& splits, bool include_validity) { // the intent here is to stress the various boundary conditions in contiguous_split - // especially the validity copying code. cudf::size_type start = 0; srand(824); std::vector<std::string> base_strings( {"banana", "pear", "apple", "pecans", "vanilla", "cat", "mouse", "green"}); auto string_randomizer = thrust::make_transform_iterator( thrust::make_counting_iterator(0), [&base_strings](cudf::size_type i) { return base_strings[rand() % base_strings.size()]; }); auto rvalids = cudf::detail::make_counting_transform_iterator(start, [include_validity](auto i) { return include_validity ? (static_cast<float>(rand()) / static_cast<float>(RAND_MAX) < 0.5f ? 0 : 1) : 0; }); std::vector<bool> valids{rvalids, rvalids + size}; cudf::test::fixed_width_column_wrapper<T> col = create_fixed_columns<T>(start, size, valids.begin()); std::vector<bool> valids2{rvalids, rvalids + size}; std::vector<std::string> strings(string_randomizer, string_randomizer + size); cudf::test::strings_column_wrapper col2(strings.begin(), strings.end(), valids2.begin()); std::vector<cudf::table_view> expected; std::vector<cudf::test::fixed_width_column_wrapper<T>> expected_fixed = create_expected_columns_for_splits<T>(splits, size, valids); std::vector<cudf::test::strings_column_wrapper> expected_strings = create_expected_string_columns_for_splits(strings, splits, valids2); std::transform(thrust::make_counting_iterator(static_cast<size_t>(0)), thrust::make_counting_iterator(expected_fixed.size()), std::back_inserter(expected), [&expected_fixed, &expected_strings](size_t i) { return cudf::table_view({expected_fixed[i], expected_strings[i]}); }); cudf::table_view tbl({col, col2}); auto result = Split(tbl, splits); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { Compare(expected[index], result[index]); } } TYPED_TEST(SplitTest, LongColumn) { split_custom_column<TypeParam>( [](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::split(t, splits); }, [](cudf::table_view const& expected, cudf::table_view const& result) { std::for_each(thrust::make_counting_iterator(0), thrust::make_counting_iterator(expected.num_columns()), [&expected, &result](cudf::size_type i) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected.column(i), result.column(i)); }); }, 10002, std::vector<cudf::size_type>{ 2, 16, 31, 35, 64, 97, 158, 190, 638, 899, 900, 901, 996, 4200, 7131, 8111}, true); split_custom_column<TypeParam>( [](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::split(t, splits); }, [](cudf::table_view const& expected, cudf::table_view const& result) { std::for_each(thrust::make_counting_iterator(0), thrust::make_counting_iterator(expected.num_columns()), [&expected, &result](cudf::size_type i) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected.column(i), result.column(i)); }); }, 10002, std::vector<cudf::size_type>{ 2, 16, 31, 35, 64, 97, 158, 190, 638, 899, 900, 901, 996, 4200, 7131, 8111}, false); } struct SplitStringTest : public SplitTest<std::string> {}; TEST_F(SplitStringTest, StringWithInvalids) { std::vector<std::string> strings{ "", "this", "is", "a", "column", "of", "strings", "with", "in", "valid"}; auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); cudf::test::strings_column_wrapper s(strings.begin(), strings.end(), valids); std::vector<cudf::size_type> splits{2, 5, 9}; std::vector<cudf::test::strings_column_wrapper> expected = create_expected_string_columns_for_splits(strings, splits, true); std::vector<cudf::column_view> result = cudf::split(s, splits); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected[index], result[index]); } } struct SplitCornerCases : public SplitTest<int8_t> {}; TEST_F(SplitCornerCases, EmptyColumn) { cudf::column col{}; std::vector<cudf::size_type> splits{2, 5, 9}; std::vector<cudf::column_view> result = cudf::split(col.view(), splits); unsigned long expected = 1; EXPECT_EQ(expected, result.size()); } TEST_F(SplitCornerCases, EmptyIndices) { cudf::size_type start = 0; cudf::size_type size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::test::fixed_width_column_wrapper<int8_t> col = create_fixed_columns<int8_t>(start, size, valids); std::vector<cudf::size_type> splits{}; std::vector<cudf::column_view> result = cudf::split(col, splits); unsigned long expected = 1; EXPECT_EQ(expected, result.size()); } TEST_F(SplitCornerCases, InvalidSetOfIndices) { cudf::size_type start = 0; cudf::size_type size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::test::fixed_width_column_wrapper<int8_t> col = create_fixed_columns<int8_t>(start, size, valids); std::vector<cudf::size_type> splits{11, 12}; EXPECT_THROW(cudf::split(col, splits), cudf::logic_error); } TEST_F(SplitCornerCases, ImproperRange) { cudf::size_type start = 0; cudf::size_type size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::test::fixed_width_column_wrapper<int8_t> col = create_fixed_columns<int8_t>(start, size, valids); std::vector<cudf::size_type> splits{5, 4}; EXPECT_THROW(cudf::split(col, splits), cudf::logic_error); } TEST_F(SplitCornerCases, NegativeValue) { cudf::size_type start = 0; cudf::size_type size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::test::fixed_width_column_wrapper<int8_t> col = create_fixed_columns<int8_t>(start, size, valids); std::vector<cudf::size_type> splits{-1, 4}; EXPECT_THROW(cudf::split(col, splits), cudf::logic_error); } // common functions for testing split/contiguous_split template <typename T, typename SplitFunc, typename CompareFunc> void split_end_less_than_size(SplitFunc Split, CompareFunc Compare) { cudf::size_type start = 0; cudf::size_type col_size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::size_type num_cols = 5; cudf::table src_table = create_fixed_table<T>(num_cols, start, col_size, valids); std::vector<cudf::size_type> splits{2, 5, 7}; std::vector<cudf::table> expected = create_expected_tables_for_splits<T>(num_cols, splits, col_size, true); auto result = Split(src_table, splits); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { Compare(expected[index], result[index]); } } template <typename T, typename SplitFunc, typename CompareFunc> void split_end_to_size(SplitFunc Split, CompareFunc Compare) { cudf::size_type start = 0; cudf::size_type col_size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::size_type num_cols = 5; cudf::table src_table = create_fixed_table<T>(num_cols, start, col_size, valids); std::vector<cudf::size_type> splits{2, 5, 10}; std::vector<cudf::table> expected = create_expected_tables_for_splits<T>(num_cols, splits, col_size, true); auto result = Split(src_table, splits); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { Compare(expected[index], result[index]); } } template <typename SplitFunc> void split_empty_table(SplitFunc Split, std::vector<cudf::size_type> const& splits = {2, 5, 6}) { cudf::table src_table{}; auto result = Split(src_table, splits); unsigned long expected = 0; EXPECT_EQ(expected, result.size()); } template <typename SplitFunc> void split_empty_indices(SplitFunc Split) { cudf::size_type start = 0; cudf::size_type col_size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::size_type num_cols = 5; cudf::table src_table = create_fixed_table<int8_t>(num_cols, start, col_size, valids); std::vector<cudf::size_type> splits{}; auto result = Split(src_table, splits); unsigned long expected = 1; EXPECT_EQ(expected, result.size()); } template <typename SplitFunc> void split_invalid_indices(SplitFunc Split) { cudf::size_type start = 0; cudf::size_type col_size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::size_type num_cols = 5; cudf::table src_table = create_fixed_table<int8_t>(num_cols, start, col_size, valids); std::vector<cudf::size_type> splits{11, 12}; EXPECT_THROW(Split(src_table, splits), cudf::logic_error); } template <typename SplitFunc> void split_improper_range(SplitFunc Split) { cudf::size_type start = 0; cudf::size_type col_size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::size_type num_cols = 5; cudf::table src_table = create_fixed_table<int8_t>(num_cols, start, col_size, valids); std::vector<cudf::size_type> splits{5, 4}; EXPECT_THROW(Split(src_table, splits), cudf::logic_error); } template <typename SplitFunc> void split_negative_value(SplitFunc Split) { cudf::size_type start = 0; cudf::size_type col_size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::size_type num_cols = 5; cudf::table src_table = create_fixed_table<int8_t>(num_cols, start, col_size, valids); std::vector<cudf::size_type> splits{-1, 4}; EXPECT_THROW(Split(src_table, splits), cudf::logic_error); } template <typename SplitFunc, typename CompareFunc> void split_empty_output_column_value(SplitFunc Split, CompareFunc Compare, std::vector<cudf::size_type> const& splits = {0, 2, 2}) { cudf::size_type start = 0; cudf::size_type col_size = 10; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return i % 2 == 0; }); cudf::size_type num_cols = 5; cudf::table src_table = create_fixed_table<int8_t>(num_cols, start, col_size, valids); EXPECT_NO_THROW(Split(src_table, splits)); auto result = Split(src_table, splits); EXPECT_NO_THROW(Compare(result[0], num_cols)); } // regular splits template <typename T> struct SplitTableTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(SplitTableTest, cudf::test::NumericTypes); TYPED_TEST(SplitTableTest, SplitEndLessThanSize) { split_end_less_than_size<TypeParam>( [](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::split(t, splits); }, [](cudf::table_view const& expected, cudf::table_view const& result) { CUDF_TEST_EXPECT_TABLES_EQUAL(expected, result); }); } TYPED_TEST(SplitTableTest, SplitEndToSize) { split_end_to_size<TypeParam>( [](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::split(t, splits); }, [](cudf::table_view const& expected, cudf::table_view const& result) { CUDF_TEST_EXPECT_TABLES_EQUAL(expected, result); }); } struct SplitTableCornerCases : public SplitTest<int8_t> {}; TEST_F(SplitTableCornerCases, EmptyTable) { split_empty_table([](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::split(t, splits); }); } TEST_F(SplitTableCornerCases, EmptyIndices) { split_empty_indices([](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::split(t, splits); }); } TEST_F(SplitTableCornerCases, InvalidSetOfIndices) { split_invalid_indices([](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::split(t, splits); }); } TEST_F(SplitTableCornerCases, ImproperRange) { split_improper_range([](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::split(t, splits); }); } TEST_F(SplitTableCornerCases, NegativeValue) { split_negative_value([](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::split(t, splits); }); } TEST_F(SplitTableCornerCases, EmptyOutputColumn) { split_empty_output_column_value( [](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::split(t, splits); }, [](cudf::table_view const& t, int num_cols) { EXPECT_EQ(t.num_columns(), num_cols); }); } template <typename SplitFunc, typename CompareFunc> void split_string_with_invalids(SplitFunc Split, CompareFunc Compare, std::vector<cudf::size_type> splits = {2, 5, 9}) { auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); std::vector<std::string> strings[2] = { {"", "this", "is", "a", "column", "of", "strings", "with", "in", "valid"}, {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}}; cudf::test::strings_column_wrapper sw[2] = {{strings[0].begin(), strings[0].end(), valids}, {strings[1].begin(), strings[1].end(), valids}}; std::vector<std::unique_ptr<cudf::column>> scols; scols.push_back(sw[0].release()); scols.push_back(sw[1].release()); cudf::table src_table(std::move(scols)); std::vector<cudf::table> expected = create_expected_string_tables_for_splits(strings, splits, true); auto result = Split(src_table, splits); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { Compare(expected[index], result[index]); } } template <typename SplitFunc, typename CompareFunc> void split_empty_output_strings_column_value(SplitFunc Split, CompareFunc Compare, std::vector<cudf::size_type> const& splits = {0, 2, 2}) { auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); std::vector<std::string> strings[2] = { {"", "this", "is", "a", "column", "of", "strings", "with", "in", "valid"}, {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}}; cudf::test::strings_column_wrapper sw[2] = {{strings[0].begin(), strings[0].end(), valids}, {strings[1].begin(), strings[1].end(), valids}}; std::vector<std::unique_ptr<cudf::column>> scols; scols.push_back(sw[0].release()); scols.push_back(sw[1].release()); cudf::table src_table(std::move(scols)); cudf::size_type num_cols = 2; EXPECT_NO_THROW(Split(src_table, splits)); auto result = Split(src_table, splits); EXPECT_NO_THROW(Compare(result[0], num_cols)); } template <typename SplitFunc, typename CompareFunc> void split_null_input_strings_column_value(SplitFunc Split, CompareFunc Compare) { auto no_valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return false; }); auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); std::vector<std::string> strings[2] = { {"", "this", "is", "a", "column", "of", "strings", "with", "in", "valid"}, {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}}; std::vector<cudf::size_type> splits{2, 5, 9}; { cudf::test::strings_column_wrapper empty_str_col{ strings[0].begin(), strings[0].end(), no_valids}; std::vector<std::unique_ptr<cudf::column>> scols; scols.push_back(empty_str_col.release()); cudf::table empty_table(std::move(scols)); EXPECT_NO_THROW(Split(empty_table, splits)); } cudf::test::strings_column_wrapper sw[2] = {{strings[0].begin(), strings[0].end(), no_valids}, {strings[1].begin(), strings[1].end(), valids}}; std::vector<std::unique_ptr<cudf::column>> scols; scols.push_back(sw[0].release()); scols.push_back(sw[1].release()); cudf::table src_table(std::move(scols)); auto result = Split(src_table, splits); std::vector<bool> validity_masks[2] = {std::vector<bool>(strings[0].size()), std::vector<bool>(strings[0].size())}; std::generate( validity_masks[1].begin(), validity_masks[1].end(), [i = 0]() mutable { return i++ % 2 == 0; }); auto expected = create_expected_string_tables_for_splits(strings, validity_masks, splits); for (std::size_t i = 0; i < result.size(); ++i) { Compare(expected[i], result[i]); } } // split with strings struct SplitStringTableTest : public SplitTest<std::string> {}; TEST_F(SplitStringTableTest, StringWithInvalids) { split_string_with_invalids( [](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::split(t, splits); }, [](cudf::table_view const& expected, cudf::table_view const& result) { CUDF_TEST_EXPECT_TABLES_EQUAL(expected, result); }); } TEST_F(SplitStringTableTest, EmptyOutputColumn) { split_empty_output_strings_column_value( [](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::split(t, splits); }, [](cudf::table_view const& t, int num_cols) { EXPECT_EQ(t.num_columns(), num_cols); }); } TEST_F(SplitStringTableTest, NullStringColumn) { split_null_input_strings_column_value( [](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::split(t, splits); }, [](cudf::table const& expected, cudf::table_view const& result) { CUDF_TEST_EXPECT_TABLES_EQUAL(expected.view(), result); }); } struct SplitNestedTypesTest : public cudf::test::BaseFixture {}; // common functions for testing split/contiguous_split template <typename T, typename SplitFunc, typename CompareFunc> void split_lists(SplitFunc Split, CompareFunc Compare, bool split = true) { using LCW = cudf::test::lists_column_wrapper<T>; { cudf::test::lists_column_wrapper<T> list{{1, 2, 3}, {4, 5}, {6}, {7, 8}, {9, 10, 11}, LCW{}, LCW{}, {-1, -2, -3, -4, -5}, {-10}, {-100, -200}}; if (split) { std::vector<cudf::size_type> splits{0, 1, 4, 5, 6, 9}; std::vector<cudf::test::lists_column_wrapper<T>> expected; expected.push_back(LCW{}); expected.push_back(LCW{{1, 2, 3}}); expected.push_back(LCW{{4, 5}, {6}, {7, 8}}); expected.push_back(LCW{{9, 10, 11}}); expected.push_back(LCW{LCW{}}); expected.push_back(LCW{LCW{}, {-1, -2, -3, -4, -5}, {-10}}); expected.push_back(LCW{{-100, -200}}); auto result = Split(list, splits); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { Compare(expected[index], result[index]); } } else { auto result = Split(list, {}); EXPECT_EQ(1, result.size()); Compare(list, result[0]); } } { cudf::test::lists_column_wrapper<T> list{{{1, 2, 3}, {4, 5}}, {LCW{}, LCW{}, {7, 8}, LCW{}}, {LCW{6}}, {{7, 8}, {9, 10, 11}, LCW{}}, {LCW{}, {-1, -2, -3, -4, -5}}, {LCW{}}, {{-10}, {-100, -200}}}; if (split) { std::vector<cudf::size_type> splits{1, 3, 4}; std::vector<cudf::test::lists_column_wrapper<T>> expected; expected.push_back(LCW{{{1, 2, 3}, {4, 5}}}); expected.push_back(LCW{{LCW{}, LCW{}, {7, 8}, LCW{}}, {LCW{6}}}); expected.push_back(LCW{{{7, 8}, {9, 10, 11}, LCW{}}}); expected.push_back(LCW{{LCW{}, {-1, -2, -3, -4, -5}}, {LCW{}}, {{-10}, {-100, -200}}}); auto result = Split(list, splits); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { Compare(expected[index], result[index]); } } else { auto result = Split(list, {}); EXPECT_EQ(1, result.size()); Compare(list, result[0]); } } } template <typename T, typename SplitFunc, typename CompareFunc> void split_lists_with_nulls(SplitFunc Split, CompareFunc Compare, bool split = true) { using LCW = cudf::test::lists_column_wrapper<int>; auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); { cudf::test::lists_column_wrapper<T> list{{1, 2, 3}, {4, 5}, {6}, {{7, 8}, valids}, {9, 10, 11}, LCW{}, LCW{}, {{-1, -2, -3, -4, -5}, valids}, {-10}, {{-100, -200}, valids}}; if (split) { std::vector<cudf::size_type> splits{0, 1, 4, 5, 6, 9}; std::vector<cudf::test::lists_column_wrapper<T>> expected; expected.push_back(LCW{}); expected.push_back(LCW{{1, 2, 3}}); expected.push_back(LCW{{4, 5}, {6}, {{7, 8}, valids}}); expected.push_back(LCW{{9, 10, 11}}); expected.push_back(LCW{LCW{}}); expected.push_back(LCW{LCW{}, {{-1, -2, -3, -4, -5}, valids}, {-10}}); expected.push_back(LCW{{{-100, -200}, valids}}); auto result = Split(list, splits); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { Compare(expected[index], result[index]); } } else { auto result = Split(list, {}); EXPECT_EQ(1, result.size()); Compare(list, result[0]); } } { cudf::test::lists_column_wrapper<T> list{{{{1, 2, 3}, valids}, {4, 5}}, {{LCW{}, LCW{}, {7, 8}, LCW{}}, valids}, {{{6}}}, {{{7, 8}, {{9, 10, 11}, valids}, LCW{}}, valids}, {{LCW{}, {-1, -2, -3, -4, -5}}, valids}, {LCW{}}, {{-10}, {-100, -200}}}; if (split) { std::vector<cudf::size_type> splits{1, 3, 4}; std::vector<cudf::test::lists_column_wrapper<T>> expected; expected.push_back(LCW{{{{1, 2, 3}, valids}, {4, 5}}}); expected.push_back(LCW{{{LCW{}, LCW{}, {7, 8}, LCW{}}, valids}, {{{6}}}}); expected.push_back(LCW{{{{7, 8}, {{9, 10, 11}, valids}, LCW{}}, valids}}); expected.push_back( LCW{{{LCW{}, {-1, -2, -3, -4, -5}}, valids}, {LCW{}}, {{-10}, {-100, -200}}}); auto result = Split(list, splits); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { Compare(expected[index], result[index]); } } else { auto result = Split(list, {}); EXPECT_EQ(1, result.size()); Compare(list, result[0]); } } } template <typename SplitFunc, typename CompareFunc> void split_structs(bool include_validity, SplitFunc Split, CompareFunc Compare, bool split = true) { // 1. String "names" column. std::vector<std::string> names{ "Vimes", "Carrot", "Angua", "Cheery", "Detritus", "Slant", "Fred", "Todd", "Kevin"}; std::vector<bool> names_validity{1, 1, 1, 1, 1, 1, 1, 1, 1}; cudf::test::strings_column_wrapper names_column(names.begin(), names.end()); // 2. Numeric "ages" column. std::vector<int> ages{5, 10, 15, 20, 25, 30, 100, 101, 102}; std::vector<bool> ages_validity = {1, 1, 1, 1, 0, 1, 0, 0, 1}; auto ages_column = include_validity ? cudf::test::fixed_width_column_wrapper<int>(ages.begin(), ages.end(), ages_validity.begin()) : cudf::test::fixed_width_column_wrapper<int>(ages.begin(), ages.end()); // 3. Boolean "is_human" column. std::vector<bool> is_human{true, true, false, false, false, false, true, true, true}; std::vector<bool> is_human_validity{1, 1, 1, 0, 1, 1, 1, 1, 0}; auto is_human_col = include_validity ? cudf::test::fixed_width_column_wrapper<bool>( is_human.begin(), is_human.end(), is_human_validity.begin()) : cudf::test::fixed_width_column_wrapper<bool>(is_human.begin(), is_human.end()); // Assemble struct column. auto const struct_validity = std::vector<bool>{1, 1, 1, 1, 1, 0, 0, 1, 0}; auto struct_column = include_validity ? cudf::test::structs_column_wrapper({names_column, ages_column, is_human_col}, struct_validity.begin()) : cudf::test::structs_column_wrapper({names_column, ages_column, is_human_col}); // split std::vector<cudf::size_type> splits; if (split) { splits = std::vector<cudf::size_type>({0, 1, 3, 8}); } auto result = Split(struct_column, splits); // expected outputs auto expected_names = include_validity ? create_expected_string_columns_for_splits(names, splits, names_validity) : create_expected_string_columns_for_splits(names, splits, false); auto expected_ages = include_validity ? create_expected_columns_for_splits<int>(splits, ages, ages_validity) : create_expected_columns_for_splits<int>(splits, ages, false); auto expected_is_human = include_validity ? create_expected_columns_for_splits<bool>(splits, is_human, is_human_validity) : create_expected_columns_for_splits<bool>(splits, is_human, false); auto expected_struct_validity = create_expected_validity(splits, struct_validity); EXPECT_EQ(expected_names.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { auto expected = include_validity ? cudf::test::structs_column_wrapper( {expected_names[index], expected_ages[index], expected_is_human[index]}, expected_struct_validity[index]) : cudf::test::structs_column_wrapper( {expected_names[index], expected_ages[index], expected_is_human[index]}); Compare(expected, result[index]); } } template <typename SplitFunc, typename CompareFunc> void split_structs_no_children(SplitFunc Split, CompareFunc Compare, bool split = true) { // no nulls { auto struct_column = cudf::make_structs_column(4, {}, 0, rmm::device_buffer{}); if (split) { auto expected = cudf::make_structs_column(2, {}, 0, rmm::device_buffer{}); // split std::vector<cudf::size_type> splits{2}; auto result = Split(*struct_column, splits); EXPECT_EQ(result.size(), 2ul); Compare(*expected, result[0]); Compare(*expected, result[1]); } else { auto result = Split(*struct_column, {}); EXPECT_EQ(1, result.size()); Compare(*struct_column, result[0]); } } // all nulls { std::vector<bool> struct_validity{false, false, false, false}; auto [null_mask, null_count] = cudf::test::detail::make_null_mask(struct_validity.begin(), struct_validity.end()); auto struct_column = cudf::make_structs_column(4, {}, null_count, std::move(null_mask)); if (split) { std::vector<bool> expected_validity{false, false}; std::tie(null_mask, null_count) = cudf::test::detail::make_null_mask(expected_validity.begin(), expected_validity.end()); auto expected = cudf::make_structs_column(2, {}, null_count, std::move(null_mask)); // split std::vector<cudf::size_type> splits{2}; auto result = Split(*struct_column, splits); EXPECT_EQ(result.size(), 2ul); Compare(*expected, result[0]); Compare(*expected, result[1]); } else { auto result = Split(*struct_column, {}); EXPECT_EQ(1, result.size()); Compare(*struct_column, result[0]); } } // no nulls, empty output column { auto struct_column = cudf::make_structs_column(4, {}, 0, rmm::device_buffer{}); if (split) { auto expected0 = cudf::make_structs_column(4, {}, 0, rmm::device_buffer{}); auto expected1 = cudf::make_structs_column(0, {}, 0, rmm::device_buffer{}); // split std::vector<cudf::size_type> splits{4}; auto result = Split(*struct_column, splits); EXPECT_EQ(result.size(), 2ul); Compare(*expected0, result[0]); Compare(*expected1, result[1]); } else { auto result = Split(*struct_column, {}); EXPECT_EQ(1, result.size()); Compare(*struct_column, result[0]); } } // all nulls, empty output column { std::vector<bool> struct_validity{false, false, false, false}; auto [null_mask, null_count] = cudf::test::detail::make_null_mask(struct_validity.begin(), struct_validity.end()); auto struct_column = cudf::make_structs_column(4, {}, null_count, std::move(null_mask)); if (split) { std::vector<bool> expected_validity0{false, false, false, false}; std::tie(null_mask, null_count) = cudf::test::detail::make_null_mask(expected_validity0.begin(), expected_validity0.end()); auto expected0 = cudf::make_structs_column(4, {}, null_count, std::move(null_mask)); auto expected1 = cudf::make_structs_column(0, {}, 0, rmm::device_buffer{}); // split std::vector<cudf::size_type> splits{4}; auto result = Split(*struct_column, splits); EXPECT_EQ(result.size(), 2ul); Compare(*expected0, result[0]); Compare(*expected1, result[1]); } else { auto result = Split(*struct_column, {}); EXPECT_EQ(1, result.size()); Compare(*struct_column, result[0]); } } } template <typename SplitFunc, typename CompareFunc> void split_nested_struct_of_list(SplitFunc Split, CompareFunc Compare, bool split = true) { // Struct<List<List>> using LCW = cudf::test::lists_column_wrapper<float>; // 1. String "names" column. std::vector<std::string> names{ "Vimes", "Carrot", "Angua", "Cheery", "Detritus", "Slant", "Fred", "Todd", "Kevin"}; std::vector<bool> names_validity{1, 1, 1, 1, 1, 1, 1, 1, 1}; cudf::test::strings_column_wrapper names_column(names.begin(), names.end()); // 2. Numeric "ages" column. std::vector<int> ages{5, 10, 15, 20, 25, 30, 100, 101, 102}; std::vector<bool> ages_validity = {1, 1, 1, 1, 0, 1, 0, 0, 1}; auto ages_column = cudf::test::fixed_width_column_wrapper<int>(ages.begin(), ages.end(), ages_validity.begin()); // 3. List column std::vector<bool> list_validity{1, 1, 1, 1, 1, 0, 1, 0, 1}; cudf::test::lists_column_wrapper<float> list({{{1, 2, 3}, {4}}, {{-1, -2}, LCW{}}, LCW{}, {{10}, {20, 30, 40}, {100, -100}}, {LCW{}, LCW{}, {8, 9}}, LCW{}, {{8}, {10, 9, 8, 7, 6, 5}}, {{5, 6}, LCW{}, {8}}, {LCW{-3, 4, -5}}}, list_validity.begin()); // Assemble struct column. auto const struct_validity = std::vector<bool>{1, 1, 1, 1, 1, 0, 0, 1, 0}; auto struct_column = cudf::test::structs_column_wrapper({names_column, ages_column, list}, struct_validity.begin()); if (split) { std::vector<cudf::size_type> splits{1, 3, 8}; auto result = Split(struct_column, splits); // expected results auto expected_names = create_expected_string_columns_for_splits(names, splits, names_validity); auto expected_ages = create_expected_columns_for_splits<int>(splits, ages, ages_validity); std::vector<cudf::test::lists_column_wrapper<float>> expected_lists; expected_lists.push_back(LCW({{{1, 2, 3}, {4}}})); expected_lists.push_back(LCW({{{-1, -2}, LCW{}}, LCW{}})); std::vector<bool> ex_v{1, 1, 0, 1, 0}; expected_lists.push_back(LCW({{{10}, {20, 30, 40}, {100, -100}}, {LCW{}, LCW{}, {8, 9}}, LCW{}, {{8}, {10, 9, 8, 7, 6, 5}}, {{5, 6}, LCW{}, {8}}}, ex_v.begin())); expected_lists.push_back(LCW({{LCW{-3, 4, -5}}})); auto expected_struct_validity = create_expected_validity(splits, struct_validity); EXPECT_EQ(expected_names.size(), result.size()); for (std::size_t index = 0; index < result.size(); index++) { auto expected = cudf::test::structs_column_wrapper( {expected_names[index], expected_ages[index], expected_lists[index]}, expected_struct_validity[index]); Compare(expected, result[index]); } } else { auto result = Split(struct_column, {}); Compare(struct_column, result[0]); } } template <typename SplitFunc, typename CompareFunc> void split_nested_list_of_structs(SplitFunc Split, CompareFunc Compare, bool split = true) { // List<Struct<List<>> using LCW = cudf::test::lists_column_wrapper<cudf::string_view>; // 1. String "names" column. std::vector<std::string> names{"Vimes", "Carrot", "Angua", "Cheery", "Detritus", "Slant", "Fred", "Todd", "Kevin", "Jason", "Clark", "Bob", "Mithun", "Sameer", "Tim", "Mark", "Herman", "Will"}; std::vector<bool> names_validity{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; cudf::test::strings_column_wrapper names_column(names.begin(), names.end()); // 2. Numeric "ages" column. std::vector<int> ages{5, 10, 15, 20, 25, 30, 100, 101, 102, 26, 64, 12, 17, 16, 120, 44, 23, 50}; std::vector<bool> ages_validity = {1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0}; auto ages_column = cudf::test::fixed_width_column_wrapper<int>(ages.begin(), ages.end(), ages_validity.begin()); // 3. List column std::vector<bool> list_validity{1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1}; cudf::test::lists_column_wrapper<cudf::string_view> list( {{"ab", "cd", "ef"}, LCW{"gh"}, {"ijk", "lmn"}, LCW{}, LCW{"o"}, {"pqr", "stu", "vwx"}, {"yz", "aaaa"}, LCW{"bbbb"}, {"cccc", "ddd", "eee", "fff", "ggg", "hh"}, {"b", "cdr", "efh", "um"}, LCW{"gh", "iu"}, {"lmn"}, LCW{"org"}, LCW{}, {"stu", "vwx"}, {"yz", "aaaa", "kem"}, LCW{"bbbb"}, {"cccc", "eee", "faff", "jiea", "fff", "ggg", "hh"}}, list_validity.begin()); // Assembly struct column auto const struct_validity = std::vector<bool>{1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1}; auto struct_column = cudf::test::structs_column_wrapper({names_column, ages_column, list}, struct_validity.begin()); // wrap in a list std::vector<int> outer_offsets{0, 3, 4, 8, 13, 16, 17, 18}; cudf::test::fixed_width_column_wrapper<int> outer_offsets_col(outer_offsets.begin(), outer_offsets.end()); std::vector<bool> outer_validity{1, 1, 1, 0, 1, 1, 0}; auto [outer_null_mask, outer_null_count] = cudf::test::detail::make_null_mask(outer_validity.begin(), outer_validity.end()); auto outer_list = make_lists_column(static_cast<cudf::size_type>(outer_validity.size()), outer_offsets_col.release(), struct_column.release(), outer_null_count, std::move(outer_null_mask)); if (split) { std::vector<cudf::size_type> splits{1, 3, 7}; cudf::table_view tbl({static_cast<cudf::column_view>(*outer_list)}); // we are testing the results of contiguous_split against regular cudf::split, which may seem // weird. however, cudf::split() is a simple operation that just sets offsets at the topmost // output column, whereas contiguous_split is a deep copy of the data to contiguous output // buffers. so as long as we believe the comparison code (expect_columns_equivalent) can compare // these outputs correctly, this should be safe. auto result = Split(*outer_list, splits); auto expected = cudf::split(static_cast<cudf::column_view>(*outer_list), splits); ASSERT_EQ(result.size(), expected.size()); for (std::size_t index = 0; index < result.size(); index++) { Compare(expected[index], result[index]); } } else { auto result = Split(*outer_list, {}); EXPECT_EQ(1, result.size()); Compare(*outer_list, result[0]); } } TEST_F(SplitNestedTypesTest, Lists) { split_lists<int>( [](cudf::column_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::split(t, splits); }, [](cudf::column_view const& expected, cudf::column_view const& result) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result); }); } TEST_F(SplitNestedTypesTest, ListsWithNulls) { split_lists_with_nulls<int>( [](cudf::column_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::split(t, splits); }, [](cudf::column_view const& expected, cudf::column_view const& result) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result); }); } TEST_F(SplitNestedTypesTest, Structs) { split_structs( false, [](cudf::column_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::split(t, splits); }, [](cudf::column_view const& expected, cudf::column_view const& result) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result); }); } TEST_F(SplitNestedTypesTest, StructsWithNulls) { split_structs( true, [](cudf::column_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::split(t, splits); }, [](cudf::column_view const& expected, cudf::column_view const& result) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result); }); } TEST_F(SplitNestedTypesTest, StructsNoChildren) { split_structs_no_children( [](cudf::column_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::split(t, splits); }, [](cudf::column_view const& expected, cudf::column_view const& result) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result); }); } TEST_F(SplitNestedTypesTest, StructsOfList) { split_nested_struct_of_list( [](cudf::column_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::split(t, splits); }, [](cudf::column_view const& expected, cudf::column_view const& result) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result); }); } template <typename T> struct ContiguousSplitTest : public cudf::test::BaseFixture {}; std::vector<cudf::packed_table> do_chunked_pack(cudf::table_view const& input) { auto mr = rmm::mr::get_current_device_resource(); rmm::device_buffer bounce_buff(1 * 1024 * 1024, cudf::get_default_stream(), mr); auto bounce_buff_span = cudf::device_span<uint8_t>(static_cast<uint8_t*>(bounce_buff.data()), bounce_buff.size()); auto chunked_pack = cudf::chunked_pack::create(input, bounce_buff_span.size(), mr); // right size the final buffer rmm::device_buffer final_buff( chunked_pack->get_total_contiguous_size(), cudf::get_default_stream(), mr); std::size_t final_buff_offset = 0; while (chunked_pack->has_next()) { auto bytes_copied = chunked_pack->next(bounce_buff_span); cudaMemcpyAsync((uint8_t*)final_buff.data() + final_buff_offset, bounce_buff.data(), bytes_copied, cudaMemcpyDefault, cudf::get_default_stream()); final_buff_offset += bytes_copied; } auto packed_column_metas = chunked_pack->build_metadata(); // for chunked contig split, this is going to be a size 1 vector if we have // results, or a size 0 if the original table was empty (no columns) std::vector<cudf::packed_table> result; if (packed_column_metas) { result = std::vector<cudf::packed_table>(1); auto pc = cudf::packed_columns(std::move(packed_column_metas), std::make_unique<rmm::device_buffer>(std::move(final_buff))); auto unpacked = cudf::unpack(pc); cudf::packed_table pt{std::move(unpacked), std::move(pc)}; result[0] = std::move(pt); } return result; } // the various utility functions in slice_tests.cuh don't like the chrono types using FixedWidthTypesWithoutChrono = cudf::test::Concat<cudf::test::NumericTypes, cudf::test::FixedPointTypes>; TYPED_TEST_SUITE(ContiguousSplitTest, FixedWidthTypesWithoutChrono); TYPED_TEST(ContiguousSplitTest, LongColumn) { split_custom_column<TypeParam>( [](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::contiguous_split(t, splits); }, [](cudf::table_view const& expected, cudf::packed_table const& result) { std::for_each(thrust::make_counting_iterator(0), thrust::make_counting_iterator(expected.num_columns()), [&expected, &result](cudf::size_type i) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected.column(i), result.table.column(i)); }); }, 10002, std::vector<cudf::size_type>{ 2, 16, 31, 35, 64, 97, 158, 190, 638, 899, 900, 901, 996, 4200, 7131, 8111}, true); split_custom_column<TypeParam>( [](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::contiguous_split(t, splits); }, [](cudf::table_view const& expected, cudf::packed_table const& result) { std::for_each(thrust::make_counting_iterator(0), thrust::make_counting_iterator(expected.num_columns()), [&expected, &result](cudf::size_type i) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected.column(i), result.table.column(i)); }); }, 10002, std::vector<cudf::size_type>{ 2, 16, 31, 35, 64, 97, 158, 190, 638, 899, 900, 901, 996, 4200, 7131, 8111}, false); } TYPED_TEST(ContiguousSplitTest, LongColumnChunked) { split_custom_column<TypeParam>( [](cudf::table_view const& t, std::vector<cudf::size_type> const&) { return do_chunked_pack(t); }, [](cudf::table_view const& expected, cudf::packed_table const& result) { std::for_each(thrust::make_counting_iterator(0), thrust::make_counting_iterator(expected.num_columns()), [&expected, &result](cudf::size_type i) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected.column(i), result.table.column(i)); }); }, 100002, {}, true); split_custom_column<TypeParam>( [](cudf::table_view const& t, std::vector<cudf::size_type> const&) { return do_chunked_pack(t); }, [](cudf::table_view const& expected, cudf::packed_table const& result) { std::for_each(thrust::make_counting_iterator(0), thrust::make_counting_iterator(expected.num_columns()), [&expected, &result](cudf::size_type i) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected.column(i), result.table.column(i)); }); }, 100002, {}, false); } TYPED_TEST(ContiguousSplitTest, LongColumnBigSplits) { split_custom_column<TypeParam>( [](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::contiguous_split(t, splits); }, [](cudf::table_view const& expected, cudf::packed_table const& result) { std::for_each(thrust::make_counting_iterator(0), thrust::make_counting_iterator(expected.num_columns()), [&expected, &result](cudf::size_type i) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected.column(i), result.table.column(i)); }); }, 10007, std::vector<cudf::size_type>{0, 3613, 7777, 10005, 10007}, true); split_custom_column<TypeParam>( [](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::contiguous_split(t, splits); }, [](cudf::table_view const& expected, cudf::packed_table const& result) { std::for_each(thrust::make_counting_iterator(0), thrust::make_counting_iterator(expected.num_columns()), [&expected, &result](cudf::size_type i) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected.column(i), result.table.column(i)); }); }, 10007, std::vector<cudf::size_type>{0, 3613, 7777, 10005, 10007}, false); } // this is a useful test but a little too expensive to run all the time /* TYPED_TEST(ContiguousSplitTest, LongColumnTinySplits) { std::vector<cudf::size_type> splits(thrust::make_counting_iterator(0), thrust::make_counting_iterator(10000)); split_custom_column<TypeParam>( [](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::contiguous_split(t, splits); }, [](cudf::table_view const& expected, cudf::packed_table const& result) { std::for_each(thrust::make_counting_iterator(0), thrust::make_counting_iterator(expected.num_columns()), [&expected, &result](cudf::size_type i){ CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected.column(i), result.table.column(i)); }); }, 10002, splits ); } */ struct ContiguousSplitUntypedTest : public cudf::test::BaseFixture {}; TEST_F(ContiguousSplitUntypedTest, ProgressiveSizes) { constexpr int col_size = 256; // stress test copying a wide amount of bytes. for (int idx = 0; idx < col_size; idx++) { split_custom_column<uint8_t>( [](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::contiguous_split(t, splits); }, [](cudf::table_view const& expected, cudf::packed_table const& result) { std::for_each(thrust::make_counting_iterator(0), thrust::make_counting_iterator(expected.num_columns()), [&expected, &result](cudf::size_type i) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected.column(i), result.table.column(i)); }); }, col_size, std::vector<cudf::size_type>{idx}, true); split_custom_column<uint8_t>( [](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::contiguous_split(t, splits); }, [](cudf::table_view const& expected, cudf::packed_table const& result) { std::for_each(thrust::make_counting_iterator(0), thrust::make_counting_iterator(expected.num_columns()), [&expected, &result](cudf::size_type i) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected.column(i), result.table.column(i)); }); }, col_size, std::vector<cudf::size_type>{idx}, false); } } TEST_F(ContiguousSplitUntypedTest, ProgressiveSizesChunked) { constexpr int col_size = 4096; // stress test copying a wide amount of bytes. for (int idx = 2048; idx < col_size; idx += 128) { split_custom_column<uint64_t>( [](cudf::table_view const& t, std::vector<cudf::size_type> const&) { return do_chunked_pack(t); }, [](cudf::table_view const& expected, cudf::packed_table const& result) { std::for_each(thrust::make_counting_iterator(0), thrust::make_counting_iterator(expected.num_columns()), [&expected, &result](cudf::size_type i) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected.column(i), result.table.column(i)); }); }, col_size, {}, true); split_custom_column<uint64_t>( [](cudf::table_view const& t, std::vector<cudf::size_type> const&) { return do_chunked_pack(t); }, [](cudf::table_view const& expected, cudf::packed_table const& result) { std::for_each(thrust::make_counting_iterator(0), thrust::make_counting_iterator(expected.num_columns()), [&expected, &result](cudf::size_type i) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected.column(i), result.table.column(i)); }); }, col_size, {}, false); } } TEST_F(ContiguousSplitUntypedTest, ValidityRepartition) { // it is tricky to actually get the internal repartitioning/load-balancing code to add new splits // inside a validity buffer. Under almost all situations, the fraction of bytes that validity // represents is so small compared to the bytes for all other data, that those buffers end up not // getting subdivided. this test forces it happen by using a small, single column of int8's, which // keeps the overall fraction that validity takes up large enough to cause a repartition. srand(0); auto rvalids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return static_cast<float>(rand()) / static_cast<float>(RAND_MAX) < 0.5f ? 0 : 1; }); cudf::size_type const num_rows = 2000000; auto col = cudf::sequence(num_rows, cudf::numeric_scalar<int8_t>{0}); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(rvalids, rvalids + num_rows); col->set_null_mask(std::move(null_mask), null_count); cudf::table_view t({*col}); auto result = cudf::contiguous_split(t, {num_rows / 2}); auto expected = cudf::split(t, {num_rows / 2}); ASSERT_EQ(result.size(), expected.size()); for (size_t idx = 0; idx < result.size(); idx++) { CUDF_TEST_EXPECT_TABLES_EQUAL(result[idx].table, expected[idx]); } } TEST_F(ContiguousSplitUntypedTest, ValidityRepartitionChunked) { srand(0); auto rvalids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return static_cast<float>(rand()) / static_cast<float>(RAND_MAX) < 0.5f ? 0 : 1; }); cudf::size_type const num_rows = 2000000; auto col = cudf::sequence(num_rows, cudf::numeric_scalar<int8_t>{0}); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(rvalids, rvalids + num_rows); col->set_null_mask(std::move(null_mask), null_count); cudf::table_view t({*col}); auto result = do_chunked_pack(t); auto& expected = t; EXPECT_EQ(1, result.size()); CUDF_TEST_EXPECT_TABLES_EQUAL(result[0].table, expected); } TEST_F(ContiguousSplitUntypedTest, ValidityEdgeCase) { // tests an edge case where the splits cause the final validity data to be copied // to be < 32 full bits, making sure we don't unintentionally read past the end of the input auto col = cudf::make_numeric_column( cudf::data_type{cudf::type_id::INT32}, 512, cudf::mask_state::ALL_VALID); auto result = cudf::contiguous_split(cudf::table_view{{*col}}, {510}); auto expected = cudf::split(cudf::table_view{{*col}}, {510}); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected[index].column(0), result[index].table.column(0)); } } // This test requires about 25GB of device memory when used with the arena allocator TEST_F(ContiguousSplitUntypedTest, DISABLED_VeryLargeColumnTest) { // tests an edge case where buf.elements * buf.element_size overflows an INT32. auto col = cudf::make_fixed_width_column( cudf::data_type{cudf::type_id::INT64}, 400 * 1024 * 1024, cudf::mask_state::UNALLOCATED); auto result = cudf::contiguous_split(cudf::table_view{{*col}}, {}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*col, result[0].table.column(0)); } // This test requires about 25GB of device memory when used with the arena allocator TEST_F(ContiguousSplitUntypedTest, DISABLED_VeryLargeColumnTestChunked) { // tests an edge case where buf.elements * buf.element_size overflows an INT32. auto col = cudf::make_fixed_width_column( cudf::data_type{cudf::type_id::INT64}, 400 * 1024 * 1024, cudf::mask_state::UNALLOCATED); auto result = do_chunked_pack(cudf::table_view{{*col}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*col, result[0].table.column(0)); } // contiguous split with strings struct ContiguousSplitStringTableTest : public SplitTest<std::string> {}; TEST_F(ContiguousSplitStringTableTest, StringWithInvalids) { split_string_with_invalids( [](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::contiguous_split(t, splits); }, [](cudf::table_view const& expected, cudf::packed_table const& result) { CUDF_TEST_EXPECT_TABLES_EQUAL(expected, result.table); }); } TEST_F(ContiguousSplitStringTableTest, StringWithInvalidsChunked) { split_string_with_invalids( [](cudf::table_view const& t, std::vector<cudf::size_type> const&) { return do_chunked_pack(t); }, [](cudf::table_view const& expected, cudf::packed_table const& result) { CUDF_TEST_EXPECT_TABLES_EQUAL(expected, result.table); }, {}); } TEST_F(ContiguousSplitStringTableTest, EmptyInputColumn) { // build a bunch of empty stuff cudf::test::strings_column_wrapper sw; cudf::test::lists_column_wrapper<int> lw; cudf::test::fixed_width_column_wrapper<float> fw; // cudf::test::strings_column_wrapper ssw; cudf::test::lists_column_wrapper<int> slw; cudf::test::fixed_width_column_wrapper<float> sfw; cudf::test::structs_column_wrapper st_w({sfw, ssw, slw}); cudf::table_view src_table({sw, lw, fw, st_w}); { std::vector<cudf::size_type> splits; auto result = cudf::contiguous_split(src_table, splits); ASSERT_EQ(result.size(), 1); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(src_table, result[0].table); } { auto result = do_chunked_pack(src_table); ASSERT_EQ(result.size(), 1); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(src_table, result[0].table); } { std::vector<cudf::size_type> splits{0, 0, 0, 0}; auto result = cudf::contiguous_split(src_table, splits); ASSERT_EQ(result.size(), 5); for (size_t idx = 0; idx < result.size(); idx++) { CUDF_TEST_EXPECT_TABLES_EQUIVALENT(src_table, result[idx].table); } } } TEST_F(ContiguousSplitStringTableTest, EmptyOutputColumn) { split_empty_output_strings_column_value( [](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::contiguous_split(t, splits); }, [](cudf::packed_table const& t, int num_cols) { EXPECT_EQ(t.table.num_columns(), num_cols); }); } TEST_F(ContiguousSplitStringTableTest, EmptyOutputColumnChunked) { split_empty_output_strings_column_value( [](cudf::table_view const& t, std::vector<cudf::size_type> const&) { return do_chunked_pack(t); }, [](cudf::packed_table const& t, int num_cols) { EXPECT_EQ(t.table.num_columns(), num_cols); }, {}); } TEST_F(ContiguousSplitStringTableTest, NullStringColumn) { split_null_input_strings_column_value( [](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::contiguous_split(t, splits); }, [](cudf::table const& expected, cudf::packed_table const& result) { CUDF_TEST_EXPECT_TABLES_EQUAL(expected.view(), result.table); }); } // contiguous splits template <typename T> struct ContiguousSplitTableTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(ContiguousSplitTableTest, FixedWidthTypesWithoutChrono); TYPED_TEST(ContiguousSplitTableTest, SplitEndLessThanSize) { split_end_less_than_size<TypeParam>( [](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::contiguous_split(t, splits); }, [](cudf::table_view const& expected, cudf::packed_table const& result) { CUDF_TEST_EXPECT_TABLES_EQUAL(expected, result.table); }); } TYPED_TEST(ContiguousSplitTableTest, SplitEndToSize) { split_end_to_size<TypeParam>( [](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::contiguous_split(t, splits); }, [](cudf::table_view const& expected, cudf::packed_table const& result) { CUDF_TEST_EXPECT_TABLES_EQUAL(expected, result.table); }); } struct ContiguousSplitTableCornerCases : public SplitTest<int8_t> {}; TEST_F(ContiguousSplitTableCornerCases, EmptyTable) { split_empty_table([](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::contiguous_split(t, splits); }); } TEST_F(ContiguousSplitTableCornerCases, EmptyTableChunked) { split_empty_table([](cudf::table_view const& t, std::vector<cudf::size_type> const&) { return do_chunked_pack(t); }, {}); } TEST_F(ContiguousSplitTableCornerCases, EmptyIndices) { split_empty_indices([](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::contiguous_split(t, splits); }); } TEST_F(ContiguousSplitTableCornerCases, InvalidSetOfIndices) { split_invalid_indices([](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::contiguous_split(t, splits); }); } TEST_F(ContiguousSplitTableCornerCases, ImproperRange) { split_improper_range([](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::contiguous_split(t, splits); }); } TEST_F(ContiguousSplitTableCornerCases, NegativeValue) { split_negative_value([](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::contiguous_split(t, splits); }); } TEST_F(ContiguousSplitTableCornerCases, EmptyOutputColumn) { split_empty_output_column_value( [](cudf::table_view const& t, std::vector<cudf::size_type> const& splits) { return cudf::contiguous_split(t, splits); }, [](cudf::packed_table const& t, int num_cols) { EXPECT_EQ(t.table.num_columns(), num_cols); }); } TEST_F(ContiguousSplitTableCornerCases, EmptyOutputColumnChunked) { split_empty_output_column_value( [](cudf::table_view const& t, std::vector<cudf::size_type> const&) { return do_chunked_pack(t); }, [](cudf::packed_table const& t, int num_cols) { EXPECT_EQ(t.table.num_columns(), num_cols); }, {}); } TEST_F(ContiguousSplitTableCornerCases, MixedColumnTypes) { cudf::size_type start = 0; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return true; }); std::vector<std::string> strings[2] = { {"", "this", "is", "a", "column", "of", "strings", "with", "in", "valid"}, {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}}; std::vector<std::unique_ptr<cudf::column>> cols; auto iter0 = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return (i); }); auto c0 = cudf::test::fixed_width_column_wrapper<int>(iter0, iter0 + 10, valids); cols.push_back(c0.release()); auto iter1 = cudf::detail::make_counting_transform_iterator(10, [](auto i) { return (i); }); auto c1 = cudf::test::fixed_width_column_wrapper<int>(iter1, iter1 + 10, valids); cols.push_back(c1.release()); auto c2 = cudf::test::strings_column_wrapper(strings[0].begin(), strings[0].end(), valids); cols.push_back(c2.release()); auto c3 = cudf::test::strings_column_wrapper(strings[1].begin(), strings[1].end(), valids); cols.push_back(c3.release()); auto iter4 = cudf::detail::make_counting_transform_iterator(20, [](auto i) { return (i); }); auto c4 = cudf::test::fixed_width_column_wrapper<int>(iter4, iter4 + 10, valids); cols.push_back(c4.release()); auto tbl = cudf::table(std::move(cols)); std::vector<cudf::size_type> splits{5}; auto result = cudf::contiguous_split(tbl, splits); auto expected = cudf::split(tbl, splits); for (unsigned long index = 0; index < expected.size(); index++) { CUDF_TEST_EXPECT_TABLES_EQUIVALENT(expected[index], result[index].table); } } TEST_F(ContiguousSplitTableCornerCases, MixedColumnTypesChunked) { cudf::size_type start = 0; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return true; }); std::size_t num_rows = 1000000; std::vector<std::string> strings1(num_rows); std::vector<std::string> strings2(num_rows); strings1[0] = ""; strings2[0] = ""; for (std::size_t i = 1; i < num_rows; ++i) { auto str = std::to_string(i); strings1[i] = str; strings2[i] = str; } std::vector<std::unique_ptr<cudf::column>> cols; auto iter0 = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return (i); }); auto c0 = cudf::test::fixed_width_column_wrapper<int>(iter0, iter0 + num_rows, valids); cols.push_back(c0.release()); auto iter1 = cudf::detail::make_counting_transform_iterator(10, [](auto i) { return (i); }); auto c1 = cudf::test::fixed_width_column_wrapper<int>(iter1, iter1 + num_rows, valids); cols.push_back(c1.release()); auto c2 = cudf::test::strings_column_wrapper(strings1.begin(), strings1.end(), valids); cols.push_back(c2.release()); auto c3 = cudf::test::strings_column_wrapper(strings2.begin(), strings2.end(), valids); cols.push_back(c3.release()); auto iter4 = cudf::detail::make_counting_transform_iterator(20, [](auto i) { return (i); }); auto c4 = cudf::test::fixed_width_column_wrapper<int>(iter4, iter4 + num_rows, valids); cols.push_back(c4.release()); auto tbl = cudf::table(std::move(cols)); auto results = do_chunked_pack(tbl.view()); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(tbl, results[0].table); } TEST_F(ContiguousSplitTableCornerCases, MixedColumnTypesSingleRowChunked) { cudf::size_type start = 0; auto valids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return true; }); std::size_t num_rows = 1; std::vector<std::unique_ptr<cudf::column>> cols; auto iter0 = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return (i); }); auto c0 = cudf::test::fixed_width_column_wrapper<int32_t>(iter0, iter0 + num_rows, valids); cols.push_back(c0.release()); auto iter1 = cudf::detail::make_counting_transform_iterator(1, [](auto i) { return (i); }); auto c1 = cudf::test::fixed_width_column_wrapper<int64_t>(iter1, iter1 + num_rows); cols.push_back(c1.release()); auto tbl = cudf::table(std::move(cols)); auto results = do_chunked_pack(tbl.view()); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(tbl, results[0].table); } TEST_F(ContiguousSplitTableCornerCases, PreSplitTable) { auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); using LCW = cudf::test::lists_column_wrapper<int>; cudf::test::lists_column_wrapper<int> col0{{{{1, 2, 3}, valids}, {4, 5}}, {{LCW{}, LCW{}, {7, 8}, LCW{}}, valids}, {{{6}}}, {{{7, 8}, {{9, 10, 11}, valids}, LCW{}}, valids}, {{LCW{}, {-1, -2, -3, -4, -5}}, valids}, {LCW{}}, {{-10}, {-100, -200}}}; cudf::test::strings_column_wrapper col1{ "Vimes", "Carrot", "Angua", "Cheery", "Detritus", "Slant", "Fred"}; cudf::test::fixed_width_column_wrapper<float> col2{1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f}; std::vector<std::unique_ptr<cudf::column>> children; children.push_back(std::make_unique<cudf::column>(col2)); children.push_back(std::make_unique<cudf::column>(col0)); children.push_back(std::make_unique<cudf::column>(col1)); auto col3 = cudf::make_structs_column( static_cast<cudf::column_view>(col0).size(), std::move(children), 0, rmm::device_buffer{}); cudf::table_view t({col0, col1, col2, *col3}); auto pre_split = cudf::split(t, {1}); { std::vector<cudf::size_type> splits{1, 4}; auto result = cudf::contiguous_split(pre_split[1], splits); auto expected = cudf::split(pre_split[1], splits); for (size_t index = 0; index < expected.size(); index++) { CUDF_TEST_EXPECT_TABLES_EQUIVALENT(expected[index], result[index].table); } } { std::vector<cudf::size_type> splits{0, 5}; auto result = cudf::contiguous_split(pre_split[1], splits); auto expected = cudf::split(pre_split[1], splits); for (size_t index = 0; index < expected.size(); index++) { CUDF_TEST_EXPECT_TABLES_EQUIVALENT(expected[index], result[index].table); } } { auto result = do_chunked_pack(pre_split[1]); EXPECT_EQ(1, result.size()); auto expected = pre_split[1]; CUDF_TEST_EXPECT_TABLES_EQUIVALENT(expected, result[0].table); } } TEST_F(ContiguousSplitTableCornerCases, PreSplitTableLarge) { // test splitting a table that is already split (has an offset) cudf::size_type start = 0; cudf::size_type presplit_pos = 47; cudf::size_type size = 10002; srand(824); auto rvalids = cudf::detail::make_counting_transform_iterator(start, [](auto i) { return static_cast<float>(rand()) / static_cast<float>(RAND_MAX) < 0.5f ? 0 : 1; }); std::vector<bool> pre_split_valids{rvalids, rvalids + size}; cudf::test::fixed_width_column_wrapper<int> pre_split = create_fixed_columns<int>(start, size, pre_split_valids.begin()); // pre-split this column auto split_cols = cudf::split(pre_split, {47}); std::vector<cudf::size_type> splits{ 2, 16, 31, 35, 64, 97, 158, 190, 638, 899, 900, 901, 996, 4200, 7131, 8111}; auto const post_split_start = start + presplit_pos; auto const post_split_size = size - presplit_pos; auto el_iter = thrust::make_counting_iterator(post_split_start); std::vector<int> post_split_elements{el_iter, el_iter + post_split_size}; std::vector<bool> post_split_valids{ pre_split_valids.begin() + post_split_start, pre_split_valids.begin() + post_split_start + post_split_size}; std::vector<cudf::test::fixed_width_column_wrapper<int>> expected = create_expected_columns_for_splits<int>(splits, post_split_elements, post_split_valids); cudf::table_view t({split_cols[1]}); auto result = cudf::contiguous_split(t, splits); EXPECT_EQ(expected.size(), result.size()); for (unsigned long index = 0; index < result.size(); index++) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected[index], result[index].table.column(0)); } } TEST_F(ContiguousSplitTableCornerCases, PreSplitList) { // list<list<int>> { cudf::test::lists_column_wrapper<int> list{{{1, 2}, {3, 4}}, {{5, 6}, {7}, {8, 9, 10}}, {{11, 12}, {13}}, {{14, 15, 16}, {17, 18}, {}}, {{-1, -2, -3}, {-4, -5, -6, -7}}, {{-8, -9}, {-10, -11}}, {{-12, -13}, {-14}, {-15, -16}}, {{-17, -18}, {}, {-19, -20}}}; auto pre_split = cudf::split(list, {2}); cudf::table_view t({pre_split[1]}); auto result = cudf::contiguous_split(t, {3, 4}); auto expected = cudf::split(t, {3, 4}); auto iter = thrust::make_counting_iterator(0); std::for_each(iter, iter + expected.size(), [&](cudf::size_type index) { CUDF_TEST_EXPECT_TABLES_EQUAL(result[index].table, expected[index]); }); } // list<struct<float>> { cudf::test::fixed_width_column_wrapper<cudf::size_type> offsets{0, 2, 5, 7, 10, 12, 14, 17, 20}; cudf::test::fixed_width_column_wrapper<float> floats{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; cudf::test::structs_column_wrapper data({floats}); auto list = cudf::make_lists_column(8, offsets.release(), data.release(), 0, rmm::device_buffer{}); auto pre_split = cudf::split(*list, {2}); cudf::table_view t({pre_split[1]}); auto result = cudf::contiguous_split(t, {3, 4}); auto expected = cudf::split(t, {3, 4}); auto iter = thrust::make_counting_iterator(0); std::for_each(iter, iter + expected.size(), [&](cudf::size_type index) { CUDF_TEST_EXPECT_TABLES_EQUAL(result[index].table, expected[index]); }); } } TEST_F(ContiguousSplitTableCornerCases, PreSplitStructs) { // includes struct<list> { cudf::test::fixed_width_column_wrapper<int> a{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; cudf::test::fixed_width_column_wrapper<float> b{{0, -1, -2, -3, -4, -5, -6, -7, -8, -9}, {1, 1, 1, 0, 0, 0, 0, 1, 1, 1}}; cudf::test::strings_column_wrapper c{ {"abc", "def", "ghi", "jkl", "mno", "", "st", "uvwx", "yy", "zzzz"}, {0, 0, 1, 1, 1, 1, 1, 1, 1, 1}}; std::vector<bool> list_validity{1, 0, 1, 0, 1, 0, 1, 1, 1, 1}; cudf::test::lists_column_wrapper<int16_t> d{ {{0, 1}, {2, 3, 4}, {5, 6}, {7}, {8, 9, 10}, {11, 12}, {}, {15, 16, 17}, {18, 19}, {20}}, list_validity.begin()}; cudf::test::fixed_width_column_wrapper<int> _a{10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; cudf::test::fixed_width_column_wrapper<float> _b{ -10, -20, -30, -40, -50, -60, -70, -80, -90, -100}; cudf::test::strings_column_wrapper _c{ "aa", "", "ccc", "dddd", "eeeee", "f", "gg", "hhh", "i", "jjj"}; cudf::test::structs_column_wrapper e({_a, _b, _c}, {1, 1, 1, 0, 1, 1, 1, 0, 1, 1}); cudf::test::structs_column_wrapper s({a, b, c, d, e}, {1, 1, 0, 1, 1, 1, 1, 1, 1, 1}); auto pre_split = cudf::split(s, {4}); auto iter = thrust::make_counting_iterator(0); std::for_each(iter, iter + pre_split.size(), [&](cudf::size_type index) { cudf::table_view t({pre_split[index]}); auto result = cudf::contiguous_split(t, {1}); auto expected = cudf::split(t, {1}); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(result[0].table, expected[0]); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(result[1].table, expected[1]); }); } // struct<list<struct>> { cudf::test::fixed_width_column_wrapper<cudf::size_type> offsets{0, 2, 5, 7, 10, 12, 14, 17, 20}; cudf::test::fixed_width_column_wrapper<float> floats{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; cudf::test::structs_column_wrapper data({floats}); auto list = cudf::make_lists_column(8, offsets.release(), data.release(), 0, rmm::device_buffer{}); cudf::test::strings_column_wrapper strings{"a", "bb", "ccc", "dddd", "", "e", "ff", "ggg"}; std::vector<std::unique_ptr<cudf::column>> struct_children; struct_children.push_back(std::move(list)); struct_children.push_back(strings.release()); cudf::test::structs_column_wrapper col(std::move(struct_children)); auto pre_split = cudf::split(col, {2}); cudf::table_view t({pre_split[1]}); auto result = cudf::contiguous_split(t, {3, 4}); auto expected = cudf::split(t, {3, 4}); auto iter = thrust::make_counting_iterator(0); std::for_each(iter, iter + expected.size(), [&](cudf::size_type index) { CUDF_TEST_EXPECT_TABLES_EQUAL(result[index].table, expected[index]); }); } } TEST_F(ContiguousSplitTableCornerCases, NestedEmpty) { // this produces an empty strings column with no children, // nested inside a list { auto empty_string = cudf::make_empty_column(cudf::data_type{cudf::type_id::STRING}); auto offsets = cudf::test::fixed_width_column_wrapper<int>({0, 0}); auto list = cudf::make_lists_column( 1, offsets.release(), std::move(empty_string), 0, rmm::device_buffer{}); cudf::table_view src_table({static_cast<cudf::column_view>(*list)}); std::vector<cudf::size_type> splits({0}); EXPECT_NO_THROW(contiguous_split(src_table, splits)); std::vector<cudf::size_type> splits2({1}); EXPECT_NO_THROW(contiguous_split(src_table, splits2)); EXPECT_NO_THROW(do_chunked_pack(src_table)); } // this produces an empty strings column with children that have no data, // nested inside a list { cudf::test::strings_column_wrapper str{"abc"}; auto empty_string = cudf::empty_like(str); auto offsets = cudf::test::fixed_width_column_wrapper<int>({0, 0}); auto list = cudf::make_lists_column( 1, offsets.release(), std::move(empty_string), 0, rmm::device_buffer{}); cudf::table_view src_table({static_cast<cudf::column_view>(*list)}); std::vector<cudf::size_type> splits({0}); EXPECT_NO_THROW(contiguous_split(src_table, splits)); std::vector<cudf::size_type> splits2({1}); EXPECT_NO_THROW(contiguous_split(src_table, splits2)); EXPECT_NO_THROW(do_chunked_pack(src_table)); } // this produces an empty lists column with children that have no data, // nested inside a list { cudf::test::lists_column_wrapper<float> listw{{1.0f, 2.0f}, {3.0f, 4.0f}}; auto empty_list = cudf::empty_like(listw); auto offsets = cudf::test::fixed_width_column_wrapper<int>({0, 0}); auto list = cudf::make_lists_column(1, offsets.release(), std::move(empty_list), 0, rmm::device_buffer{}); cudf::table_view src_table({static_cast<cudf::column_view>(*list)}); std::vector<cudf::size_type> splits({0}); EXPECT_NO_THROW(contiguous_split(src_table, splits)); std::vector<cudf::size_type> splits2({1}); EXPECT_NO_THROW(contiguous_split(src_table, splits2)); EXPECT_NO_THROW(do_chunked_pack(src_table)); } // this produces an empty lists column with children that have no data, // nested inside a list { cudf::test::lists_column_wrapper<float> listw{{1.0f, 2.0f}, {3.0f, 4.0f}}; auto empty_list = cudf::empty_like(listw); auto offsets = cudf::test::fixed_width_column_wrapper<int>({0, 0}); auto list = cudf::make_lists_column(1, offsets.release(), std::move(empty_list), 0, rmm::device_buffer{}); cudf::table_view src_table({static_cast<cudf::column_view>(*list)}); std::vector<cudf::size_type> splits({0}); EXPECT_NO_THROW(contiguous_split(src_table, splits)); std::vector<cudf::size_type> splits2({1}); EXPECT_NO_THROW(contiguous_split(src_table, splits2)); EXPECT_NO_THROW(do_chunked_pack(src_table)); } // this produces an empty struct column with children that have no data, // nested inside a list { cudf::test::fixed_width_column_wrapper<int> ints{0, 1, 2, 3, 4}; cudf::test::fixed_width_column_wrapper<float> floats{4, 3, 2, 1, 0}; auto struct_column = cudf::test::structs_column_wrapper({ints, floats}); auto empty_struct = cudf::empty_like(struct_column); auto offsets = cudf::test::fixed_width_column_wrapper<int>({0, 0}); auto list = cudf::make_lists_column( 1, offsets.release(), std::move(empty_struct), 0, rmm::device_buffer{}); cudf::table_view src_table({static_cast<cudf::column_view>(*list)}); std::vector<cudf::size_type> splits({0}); EXPECT_NO_THROW(contiguous_split(src_table, splits)); std::vector<cudf::size_type> splits2({1}); EXPECT_NO_THROW(contiguous_split(src_table, splits2)); EXPECT_NO_THROW(do_chunked_pack(src_table)); } } TEST_F(ContiguousSplitTableCornerCases, SplitEmpty) { // empty sliced column. this is specifically testing the corner case: // - a sliced column of size 0 // - having children that are of size > 0 // cudf::test::strings_column_wrapper a{"abc", "def", "ghi", "jkl", "mno", "", "st", "uvwx"}; cudf::test::lists_column_wrapper<int> b{ {0, 1}, {2}, {3, 4, 5}, {6, 7}, {8, 9}, {10}, {11, 12}, {13, 14}}; cudf::test::fixed_width_column_wrapper<float> c{0, 1, 2, 3, 4, 5, 6, 7}; cudf::test::strings_column_wrapper _a{"abc", "def", "ghi", "jkl", "mno", "", "st", "uvwx"}; cudf::test::lists_column_wrapper<float> _b{ {0, 1}, {2}, {3, 4, 5}, {6, 7}, {8, 9}, {10}, {11, 12}, {13, 14}}; cudf::test::fixed_width_column_wrapper<float> _c{0, 1, 2, 3, 4, 5, 6, 7}; cudf::test::structs_column_wrapper d({_a, _b, _c}); cudf::table_view t({a, b, c, d}); auto sliced = cudf::split(t, {0}); { auto result = cudf::contiguous_split(sliced[0], {}); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(sliced[0], result[0].table); } { auto result = do_chunked_pack(sliced[0]); EXPECT_EQ(1, result.size()); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(sliced[0], result[0].table); } { auto result = cudf::contiguous_split(sliced[0], {0}); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(sliced[0], result[0].table); } { EXPECT_THROW(cudf::contiguous_split(sliced[0], {1}), cudf::logic_error); } } TEST_F(ContiguousSplitTableCornerCases, OutBufferToSmall) { // internally, contiguous split chunks GPU work in 1MB contiguous copies // so the output buffer must be 1MB or larger. EXPECT_THROW(cudf::chunked_pack::create({}, 1 * 1024), cudf::logic_error); } TEST_F(ContiguousSplitTableCornerCases, ChunkSpanTooSmall) { auto chunked_pack = cudf::chunked_pack::create({}, 1 * 1024 * 1024); rmm::device_buffer buff( 1 * 1024, cudf::test::get_default_stream(), rmm::mr::get_current_device_resource()); cudf::device_span<uint8_t> too_small(static_cast<uint8_t*>(buff.data()), buff.size()); std::size_t copied = 0; // throws because we created chunked_contig_split with 1MB, but we are giving // it a 1KB span here EXPECT_THROW(copied = chunked_pack->next(too_small), cudf::logic_error); EXPECT_EQ(copied, 0); } TEST_F(ContiguousSplitTableCornerCases, EmptyTableHasNextFalse) { auto chunked_pack = cudf::chunked_pack::create({}, 1 * 1024 * 1024); rmm::device_buffer buff( 1 * 1024 * 1024, cudf::test::get_default_stream(), rmm::mr::get_current_device_resource()); cudf::device_span<uint8_t> bounce_buff(static_cast<uint8_t*>(buff.data()), buff.size()); EXPECT_EQ(chunked_pack->has_next(), false); // empty input table std::size_t copied = 0; EXPECT_THROW(copied = chunked_pack->next(bounce_buff), cudf::logic_error); EXPECT_EQ(copied, 0); } TEST_F(ContiguousSplitTableCornerCases, ExhaustedHasNextFalse) { cudf::test::strings_column_wrapper a{"abc", "def", "ghi", "jkl", "mno", "", "st", "uvwx"}; cudf::table_view t({a}); rmm::device_buffer buff( 1 * 1024 * 1024, cudf::test::get_default_stream(), rmm::mr::get_current_device_resource()); cudf::device_span<uint8_t> bounce_buff(static_cast<uint8_t*>(buff.data()), buff.size()); auto chunked_pack = cudf::chunked_pack::create(t, buff.size()); EXPECT_EQ(chunked_pack->has_next(), true); std::size_t copied = chunked_pack->next(bounce_buff); EXPECT_EQ(copied, chunked_pack->get_total_contiguous_size()); EXPECT_EQ(chunked_pack->has_next(), false); copied = 0; EXPECT_THROW(copied = chunked_pack->next(bounce_buff), cudf::logic_error); EXPECT_EQ(copied, 0); } struct ContiguousSplitNestedTypesTest : public cudf::test::BaseFixture {}; TEST_F(ContiguousSplitNestedTypesTest, Lists) { split_lists<int>( [](cudf::column_view const& c, std::vector<cudf::size_type> const& splits) { cudf::table_view t({c}); return cudf::contiguous_split(t, splits); }, [](cudf::column_view const& expected, cudf::packed_table const& result) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result.table.column(0)); }); } TEST_F(ContiguousSplitNestedTypesTest, ListsChunked) { split_lists<int>( [](cudf::column_view const& c, std::vector<cudf::size_type> const&) { cudf::table_view t({c}); return do_chunked_pack(t); }, [](cudf::column_view const& expected, cudf::packed_table const& result) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result.table.column(0)); }, /*split*/ false); } TEST_F(ContiguousSplitNestedTypesTest, ListsWithNulls) { split_lists_with_nulls<int>( [](cudf::column_view const& c, std::vector<cudf::size_type> const& splits) { cudf::table_view t({c}); return cudf::contiguous_split(t, splits); }, [](cudf::column_view const& expected, cudf::packed_table const& result) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result.table.column(0)); }); } TEST_F(ContiguousSplitNestedTypesTest, ListsWithNullsChunked) { split_lists_with_nulls<int>( [](cudf::column_view const& c, std::vector<cudf::size_type> const&) { cudf::table_view t({c}); return do_chunked_pack(t); }, [](cudf::column_view const& expected, cudf::packed_table const& result) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result.table.column(0)); }, /*split*/ false); } TEST_F(ContiguousSplitNestedTypesTest, Structs) { split_structs( false, [](cudf::column_view const& c, std::vector<cudf::size_type> const& splits) { cudf::table_view t({c}); return cudf::contiguous_split(t, splits); }, [](cudf::column_view const& expected, cudf::packed_table const& result) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result.table.column(0)); }); } TEST_F(ContiguousSplitNestedTypesTest, StructsChunked) { split_structs( false, [](cudf::column_view const& c, std::vector<cudf::size_type> const&) { cudf::table_view t({c}); return do_chunked_pack(t); }, [](cudf::column_view const& expected, cudf::packed_table const& result) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result.table.column(0)); }, /*split*/ false); } TEST_F(ContiguousSplitNestedTypesTest, StructsWithNulls) { split_structs( true, [](cudf::column_view const& c, std::vector<cudf::size_type> const& splits) { cudf::table_view t({c}); return cudf::contiguous_split(t, splits); }, [](cudf::column_view const& expected, cudf::packed_table const& result) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result.table.column(0)); }); } TEST_F(ContiguousSplitNestedTypesTest, StructsWithNullsChunked) { split_structs( true, [](cudf::column_view const& c, std::vector<cudf::size_type> const&) { cudf::table_view t({c}); return do_chunked_pack(t); }, [](cudf::column_view const& expected, cudf::packed_table const& result) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result.table.column(0)); }, {}); } TEST_F(ContiguousSplitNestedTypesTest, StructsNoChildren) { split_structs_no_children( [](cudf::column_view const& c, std::vector<cudf::size_type> const& splits) { cudf::table_view t({c}); return cudf::contiguous_split(t, splits); }, [](cudf::column_view const& expected, cudf::packed_table const& result) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result.table.column(0)); }); } TEST_F(ContiguousSplitNestedTypesTest, StructsNoChildrenChunked) { split_structs_no_children( [](cudf::column_view const& c, std::vector<cudf::size_type> const&) { cudf::table_view t({c}); return do_chunked_pack(t); }, [](cudf::column_view const& expected, cudf::packed_table const& result) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result.table.column(0)); }, /*split*/ false); } TEST_F(ContiguousSplitNestedTypesTest, StructsOfList) { split_nested_struct_of_list( [](cudf::column_view const& c, std::vector<cudf::size_type> const& splits) { cudf::table_view t({c}); return cudf::contiguous_split(t, splits); }, [](cudf::column_view const& expected, cudf::packed_table const& result) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result.table.column(0)); }); } TEST_F(ContiguousSplitNestedTypesTest, StructsOfListChunked) { split_nested_struct_of_list( [](cudf::column_view const& c, std::vector<cudf::size_type> const&) { cudf::table_view t({c}); return do_chunked_pack(t); }, [](cudf::column_view const& expected, cudf::packed_table const& result) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result.table.column(0)); }, /*split*/ false); } TEST_F(ContiguousSplitNestedTypesTest, ListOfStruct) { split_nested_list_of_structs( [](cudf::column_view const& c, std::vector<cudf::size_type> const& splits) { cudf::table_view t({c}); return cudf::contiguous_split(t, splits); }, [](cudf::column_view const& expected, cudf::packed_table const& result) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result.table.column(0)); }); } TEST_F(ContiguousSplitNestedTypesTest, ListOfStructChunked) { split_nested_list_of_structs( [](cudf::column_view const& c, std::vector<cudf::size_type> const&) { cudf::table_view t({c}); return do_chunked_pack(t); }, [](cudf::column_view const& expected, cudf::packed_table const& result) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, result.table.column(0)); }, /*split*/ false); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/pack_tests.cpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf/contiguous_split.hpp> struct PackUnpackTest : public cudf::test::BaseFixture { void run_test(cudf::table_view const& t) { // verify pack/unpack works auto packed = cudf::pack(t); auto unpacked = cudf::unpack(packed); CUDF_TEST_EXPECT_TABLES_EQUAL(t, unpacked); // verify pack_metadata itself works auto metadata = cudf::pack_metadata( unpacked, reinterpret_cast<uint8_t const*>(packed.gpu_data->data()), packed.gpu_data->size()); EXPECT_EQ(metadata.size(), packed.metadata->size()); EXPECT_EQ( std::equal(metadata.data(), metadata.data() + metadata.size(), packed.metadata->data()), true); } void run_test(std::vector<cudf::column_view> const& t) { run_test(cudf::table_view{t}); } }; TEST_F(PackUnpackTest, SingleColumnFixedWidth) { cudf::test::fixed_width_column_wrapper<int64_t> col1({1, 2, 3, 4, 5, 6, 7}, {1, 1, 1, 0, 1, 0, 1}); this->run_test({col1}); } TEST_F(PackUnpackTest, SingleColumnFixedWidthNonNullable) { cudf::test::fixed_width_column_wrapper<int64_t> col1({1, 2, 3, 4, 5, 6, 7}); this->run_test({col1}); } TEST_F(PackUnpackTest, MultiColumnFixedWidth) { cudf::test::fixed_width_column_wrapper<int16_t> col1({1, 2, 3, 4, 5, 6, 7}, {1, 1, 1, 0, 1, 0, 1}); cudf::test::fixed_width_column_wrapper<float> col2({7, 8, 6, 5, 4, 3, 2}, {1, 0, 1, 1, 1, 1, 1}); cudf::test::fixed_width_column_wrapper<double> col3({8, 4, 2, 0, 7, 1, 3}, {0, 1, 1, 1, 1, 1, 1}); this->run_test({col1, col2, col3}); } TEST_F(PackUnpackTest, MultiColumnWithStrings) { cudf::test::fixed_width_column_wrapper<int16_t> col1({1, 2, 3, 4, 5, 6, 7}, {1, 1, 1, 0, 1, 0, 1}); cudf::test::strings_column_wrapper col2({"Lorem", "ipsum", "dolor", "sit", "amet", "ort", "ral"}, {1, 0, 1, 1, 1, 0, 1}); cudf::test::strings_column_wrapper col3({"", "this", "is", "a", "column", "of", "strings"}); this->run_test({col1, col2, col3}); } // clang-format on TEST_F(PackUnpackTest, EmptyColumns) { { auto empty_string = cudf::make_empty_column(cudf::data_type{cudf::type_id::STRING}); cudf::table_view src_table({static_cast<cudf::column_view>(*empty_string)}); this->run_test(src_table); } { cudf::test::strings_column_wrapper str{"abc"}; auto empty_string = cudf::empty_like(str); cudf::table_view src_table({static_cast<cudf::column_view>(*empty_string)}); this->run_test(src_table); } { cudf::test::fixed_width_column_wrapper<int> col0; cudf::test::dictionary_column_wrapper<int> col1; cudf::test::strings_column_wrapper col2; cudf::test::lists_column_wrapper<int> col3; cudf::test::structs_column_wrapper col4({}); cudf::table_view src_table({col0, col1, col2, col3, col4}); this->run_test(src_table); } } std::vector<std::unique_ptr<cudf::column>> generate_lists(bool include_validity) { using LCW = cudf::test::lists_column_wrapper<int>; if (include_validity) { auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); cudf::test::lists_column_wrapper<int> list0{{1, 2, 3}, {4, 5}, {6}, {{7, 8}, valids}, {9, 10, 11}, LCW{}, LCW{}, {{-1, -2, -3, -4, -5}, valids}, {{100, -200}, valids}}; cudf::test::lists_column_wrapper<int> list1{{{{1, 2, 3}, valids}, {4, 5}}, {{LCW{}, LCW{}, {7, 8}, LCW{}}, valids}, {LCW{6}}, {{{7, 8}, {{9, 10, 11}, valids}, LCW{}}, valids}, {{LCW{}, {-1, -2, -3, -4, -5}}, valids}, {LCW{}}, {LCW{-10}, {-100, -200}}, {{-10, -200}, LCW{}, {8, 9}}, {LCW{8}, LCW{}, LCW{9}, {5, 6}}}; std::vector<std::unique_ptr<cudf::column>> out; out.push_back(list0.release()); out.push_back(list1.release()); return out; } cudf::test::lists_column_wrapper<int> list0{ {1, 2, 3}, {4, 5}, {6}, {7, 8}, {9, 10, 11}, LCW{}, LCW{}, {-1, -2, -3, -4, -5}, {-100, -200}}; cudf::test::lists_column_wrapper<int> list1{{{1, 2, 3}, {4, 5}}, {LCW{}, LCW{}, {7, 8}, LCW{}}, {LCW{6}}, {{7, 8}, {9, 10, 11}, LCW{}}, {LCW{}, {-1, -2, -3, -4, -5}}, {LCW{}}, {{-10}, {-100, -200}}, {{-10, -200}, LCW{}, {8, 9}}, {LCW{8}, LCW{}, LCW{9}, {5, 6}}}; std::vector<std::unique_ptr<cudf::column>> out; out.push_back(list0.release()); out.push_back(list1.release()); return out; } std::vector<std::unique_ptr<cudf::column>> generate_structs(bool include_validity) { // 1. String "names" column. std::vector<std::string> names{ "Vimes", "Carrot", "Angua", "Cheery", "Detritus", "Slant", "Fred", "Todd", "Kevin"}; cudf::test::strings_column_wrapper names_column(names.begin(), names.end()); // 2. Numeric "ages" column. std::vector<int> ages{5, 10, 15, 20, 25, 30, 100, 101, 102}; std::vector<bool> ages_validity = {1, 1, 1, 1, 0, 1, 0, 0, 1}; auto ages_column = include_validity ? cudf::test::fixed_width_column_wrapper<int>(ages.begin(), ages.end(), ages_validity.begin()) : cudf::test::fixed_width_column_wrapper<int>(ages.begin(), ages.end()); // 3. Boolean "is_human" column. std::vector<bool> is_human{true, true, false, false, false, false, true, true, true}; std::vector<bool> is_human_validity{1, 1, 1, 0, 1, 1, 1, 1, 0}; auto is_human_col = include_validity ? cudf::test::fixed_width_column_wrapper<bool>( is_human.begin(), is_human.end(), is_human_validity.begin()) : cudf::test::fixed_width_column_wrapper<bool>(is_human.begin(), is_human.end()); // Assemble struct column. auto const struct_validity = std::vector<bool>{1, 1, 1, 1, 1, 0, 0, 1, 0}; auto struct_column = include_validity ? cudf::test::structs_column_wrapper({names_column, ages_column, is_human_col}, struct_validity.begin()) : cudf::test::structs_column_wrapper({names_column, ages_column, is_human_col}); std::vector<std::unique_ptr<cudf::column>> out; out.push_back(struct_column.release()); return out; } std::vector<std::unique_ptr<cudf::column>> generate_struct_of_list() { // 1. String "names" column. std::vector<std::string> names{ "Vimes", "Carrot", "Angua", "Cheery", "Detritus", "Slant", "Fred", "Todd", "Kevin"}; cudf::test::strings_column_wrapper names_column(names.begin(), names.end()); // 2. Numeric "ages" column. std::vector<int> ages{5, 10, 15, 20, 25, 30, 100, 101, 102}; std::vector<bool> ages_validity = {1, 1, 1, 1, 0, 1, 0, 0, 1}; auto ages_column = cudf::test::fixed_width_column_wrapper<int>(ages.begin(), ages.end(), ages_validity.begin()); // 3. List column using LCW = cudf::test::lists_column_wrapper<cudf::string_view>; std::vector<bool> list_validity{1, 1, 1, 1, 1, 0, 1, 0, 1}; cudf::test::lists_column_wrapper<cudf::string_view> list( {{{"abc", "d", "edf"}, {"jjj"}}, {{"dgaer", "-7"}, LCW{}}, {LCW{}}, {{"qwerty"}, {"ral", "ort", "tal"}, {"five", "six"}}, {LCW{}, LCW{}, {"eight", "nine"}}, {LCW{}}, {{"fun"}, {"a", "bc", "def", "ghij", "klmno", "pqrstu"}}, {{"seven", "zz"}, LCW{}, {"xyzzy"}}, {LCW{"negative 3", " ", "cleveland"}}}, list_validity.begin()); // Assemble struct column. auto const struct_validity = std::vector<bool>{1, 1, 1, 1, 1, 0, 0, 1, 0}; auto struct_column = cudf::test::structs_column_wrapper({names_column, ages_column, list}, struct_validity.begin()); std::vector<std::unique_ptr<cudf::column>> out; out.push_back(struct_column.release()); return out; } std::vector<std::unique_ptr<cudf::column>> generate_list_of_struct() { // 1. String "names" column. std::vector<std::string> names{"Vimes", "Carrot", "Angua", "Cheery", "Detritus", "Slant", "Fred", "Todd", "Kevin", "Abc", "Def", "Xyz", "Five", "Seventeen", "Dol", "Est"}; cudf::test::strings_column_wrapper names_column(names.begin(), names.end()); // 2. Numeric "ages" column. std::vector<int> ages{5, 10, 15, 20, 25, 30, 100, 101, 102, -1, -2, -3, -4, -5, -6, -7}; std::vector<bool> ages_validity = {1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1}; auto ages_column = cudf::test::fixed_width_column_wrapper<int>(ages.begin(), ages.end(), ages_validity.begin()); // Assemble struct column. auto const struct_validity = std::vector<bool>{1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1}; auto struct_column = cudf::test::structs_column_wrapper({names_column, ages_column}, struct_validity.begin()); // 3. List column std::vector<bool> list_validity{1, 1, 1, 1, 1, 0, 1, 0, 1}; cudf::test::fixed_width_column_wrapper<int> offsets{0, 1, 4, 5, 7, 7, 10, 13, 14, 16}; auto [null_mask, null_count] = cudf::test::detail::make_null_mask(list_validity.begin(), list_validity.begin() + 9); auto list = cudf::make_lists_column( 9, offsets.release(), struct_column.release(), null_count, std::move(null_mask)); std::vector<std::unique_ptr<cudf::column>> out; out.push_back(std::move(list)); return out; } TEST_F(PackUnpackTest, Lists) { // lists { auto cols = generate_lists(false); std::vector<cudf::column_view> col_views; std::transform(cols.begin(), cols.end(), std::back_inserter(col_views), [](std::unique_ptr<cudf::column> const& col) { return static_cast<cudf::column_view>(*col); }); cudf::table_view src_table(col_views); this->run_test(src_table); } // lists with validity { auto cols = generate_lists(true); std::vector<cudf::column_view> col_views; std::transform(cols.begin(), cols.end(), std::back_inserter(col_views), [](std::unique_ptr<cudf::column> const& col) { return static_cast<cudf::column_view>(*col); }); cudf::table_view src_table(col_views); this->run_test(src_table); } } TEST_F(PackUnpackTest, Structs) { // structs { auto cols = generate_structs(false); std::vector<cudf::column_view> col_views; std::transform(cols.begin(), cols.end(), std::back_inserter(col_views), [](std::unique_ptr<cudf::column> const& col) { return static_cast<cudf::column_view>(*col); }); cudf::table_view src_table(col_views); this->run_test(src_table); } // structs with validity { auto cols = generate_structs(true); std::vector<cudf::column_view> col_views; std::transform(cols.begin(), cols.end(), std::back_inserter(col_views), [](std::unique_ptr<cudf::column> const& col) { return static_cast<cudf::column_view>(*col); }); cudf::table_view src_table(col_views); this->run_test(src_table); } } TEST_F(PackUnpackTest, NestedTypes) { // build one big table containing, lists, structs, structs<list>, list<struct> std::vector<cudf::column_view> col_views; auto lists = generate_lists(true); std::transform( lists.begin(), lists.end(), std::back_inserter(col_views), [](std::unique_ptr<cudf::column> const& col) { return static_cast<cudf::column_view>(*col); }); auto structs = generate_structs(true); std::transform( structs.begin(), structs.end(), std::back_inserter(col_views), [](std::unique_ptr<cudf::column> const& col) { return static_cast<cudf::column_view>(*col); }); auto struct_of_list = generate_struct_of_list(); std::transform( struct_of_list.begin(), struct_of_list.end(), std::back_inserter(col_views), [](std::unique_ptr<cudf::column> const& col) { return static_cast<cudf::column_view>(*col); }); auto list_of_struct = generate_list_of_struct(); std::transform( list_of_struct.begin(), list_of_struct.end(), std::back_inserter(col_views), [](std::unique_ptr<cudf::column> const& col) { return static_cast<cudf::column_view>(*col); }); cudf::table_view src_table(col_views); this->run_test(src_table); } TEST_F(PackUnpackTest, NestedEmpty) { // this produces an empty strings column with no children, // nested inside a list { auto empty_string = cudf::make_empty_column(cudf::data_type{cudf::type_id::STRING}); auto offsets = cudf::test::fixed_width_column_wrapper<int>({0, 0}); auto list = cudf::make_lists_column( 1, offsets.release(), std::move(empty_string), 0, rmm::device_buffer{}); cudf::table_view src_table({static_cast<cudf::column_view>(*list)}); this->run_test(src_table); } // this produces an empty strings column with children that have no data, // nested inside a list { cudf::test::strings_column_wrapper str{"abc"}; auto empty_string = cudf::empty_like(str); auto offsets = cudf::test::fixed_width_column_wrapper<int>({0, 0}); auto list = cudf::make_lists_column( 1, offsets.release(), std::move(empty_string), 0, rmm::device_buffer{}); cudf::table_view src_table({static_cast<cudf::column_view>(*list)}); this->run_test(src_table); } // this produces an empty lists column with children that have no data, // nested inside a list { cudf::test::lists_column_wrapper<float> listw{{1.0f, 2.0f}, {3.0f, 4.0f}}; auto empty_list = cudf::empty_like(listw); auto offsets = cudf::test::fixed_width_column_wrapper<int>({0, 0}); auto list = cudf::make_lists_column(1, offsets.release(), std::move(empty_list), 0, rmm::device_buffer{}); cudf::table_view src_table({static_cast<cudf::column_view>(*list)}); this->run_test(src_table); } // this produces an empty lists column with children that have no data, // nested inside a list { cudf::test::lists_column_wrapper<float> listw{{1.0f, 2.0f}, {3.0f, 4.0f}}; auto empty_list = cudf::empty_like(listw); auto offsets = cudf::test::fixed_width_column_wrapper<int>({0, 0}); auto list = cudf::make_lists_column(1, offsets.release(), std::move(empty_list), 0, rmm::device_buffer{}); cudf::table_view src_table({static_cast<cudf::column_view>(*list)}); this->run_test(src_table); } // this produces an empty struct column with children that have no data, // nested inside a list { cudf::test::fixed_width_column_wrapper<int> ints{0, 1, 2, 3, 4}; cudf::test::fixed_width_column_wrapper<float> floats{4, 3, 2, 1, 0}; auto struct_column = cudf::test::structs_column_wrapper({ints, floats}); auto empty_struct = cudf::empty_like(struct_column); auto offsets = cudf::test::fixed_width_column_wrapper<int>({0, 0}); auto list = cudf::make_lists_column( 1, offsets.release(), std::move(empty_struct), 0, rmm::device_buffer{}); cudf::table_view src_table({static_cast<cudf::column_view>(*list)}); this->run_test(src_table); } } TEST_F(PackUnpackTest, NestedSliced) { // list { auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); using LCW = cudf::test::lists_column_wrapper<int>; cudf::test::lists_column_wrapper<int> col0{{{{1, 2, 3}, valids}, {4, 5}}, {{LCW{}, LCW{}, {7, 8}, LCW{}}, valids}, {{6, 12}}, {{{7, 8}, {{9, 10, 11}, valids}, LCW{}}, valids}, {{LCW{}, {-1, -2, -3, -4, -5}}, valids}, {LCW{}}, {{-10}, {-100, -200}}}; cudf::test::strings_column_wrapper col1{ "Vimes", "Carrot", "Angua", "Cheery", "Detritus", "Slant", "Fred"}; cudf::test::fixed_width_column_wrapper<float> col2{1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f}; std::vector<std::unique_ptr<cudf::column>> children; children.push_back(std::make_unique<cudf::column>(col2)); children.push_back(std::make_unique<cudf::column>(col0)); children.push_back(std::make_unique<cudf::column>(col1)); auto col3 = cudf::make_structs_column( static_cast<cudf::column_view>(col0).size(), std::move(children), 0, rmm::device_buffer{}); cudf::table_view t({col0, col1, col2, *col3}); this->run_test(t); } // struct { cudf::test::fixed_width_column_wrapper<int> a{0, 1, 2, 3, 4, 5, 6, 7}; cudf::test::fixed_width_column_wrapper<float> b{{0, -1, -2, -3, -4, -5, -6, -7}, {1, 1, 1, 0, 0, 0, 0, 1}}; cudf::test::strings_column_wrapper c{{"abc", "def", "ghi", "jkl", "mno", "", "st", "uvwx"}, {0, 0, 1, 1, 1, 1, 1, 1}}; std::vector<bool> list_validity{1, 0, 1, 0, 1, 0, 1, 1}; cudf::test::lists_column_wrapper<int16_t> d{ {{0, 1}, {2, 3, 4}, {5, 6}, {7}, {8, 9, 10}, {11, 12}, {}, {15, 16, 17}}, list_validity.begin()}; cudf::test::fixed_width_column_wrapper<int> _a{10, 20, 30, 40, 50, 60, 70, 80}; cudf::test::fixed_width_column_wrapper<float> _b{-10, -20, -30, -40, -50, -60, -70, -80}; cudf::test::strings_column_wrapper _c{"aa", "", "ccc", "dddd", "eeeee", "f", "gg", "hhh"}; cudf::test::structs_column_wrapper e({_a, _b, _c}, {1, 1, 1, 0, 1, 1, 1, 0}); cudf::test::structs_column_wrapper s({a, b, c, d, e}, {1, 1, 0, 1, 1, 1, 1, 1}); auto split = cudf::split(s, {2, 5}); this->run_test(cudf::table_view({split[0]})); this->run_test(cudf::table_view({split[1]})); this->run_test(cudf::table_view({split[2]})); } } TEST_F(PackUnpackTest, EmptyTable) { // no columns { cudf::table_view t; this->run_test(t); } // no rows { cudf::test::fixed_width_column_wrapper<int> a; cudf::test::strings_column_wrapper b; cudf::test::lists_column_wrapper<float> c; cudf::table_view t({a, b, c}); this->run_test(t); } } TEST_F(PackUnpackTest, SlicedEmpty) { // empty sliced column. this is specifically testing the corner case: // - a sliced column of size 0 // - having children that are of size > 0 // cudf::test::strings_column_wrapper a{"abc", "def", "ghi", "jkl", "mno", "", "st", "uvwx"}; cudf::test::lists_column_wrapper<int> b{ {0, 1}, {2}, {3, 4, 5}, {6, 7}, {8, 9}, {10}, {11, 12}, {13, 14}}; cudf::test::fixed_width_column_wrapper<float> c{0, 1, 2, 3, 4, 5, 6, 7}; cudf::test::strings_column_wrapper _a{"abc", "def", "ghi", "jkl", "mno", "", "st", "uvwx"}; cudf::test::lists_column_wrapper<float> _b{ {0, 1}, {2}, {3, 4, 5}, {6, 7}, {8, 9}, {10}, {11, 12}, {13, 14}}; cudf::test::fixed_width_column_wrapper<float> _c{0, 1, 2, 3, 4, 5, 6, 7}; cudf::test::structs_column_wrapper d({_a, _b, _c}); cudf::table_view t({a, b, c, d}); auto sliced = cudf::split(t, {0}); this->run_test(sliced[0]); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/copying/gather_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/column/column_view.hpp> #include <cudf/copying.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> template <typename T> class GatherTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(GatherTest, cudf::test::NumericTypes); TYPED_TEST(GatherTest, IdentityTest) { constexpr cudf::size_type source_size{1000}; auto data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i; }); cudf::test::fixed_width_column_wrapper<TypeParam> source_column(data, data + source_size); cudf::test::fixed_width_column_wrapper<int32_t> gather_map(data, data + source_size); cudf::table_view source_table({source_column}); std::unique_ptr<cudf::table> result = std::move(cudf::gather(source_table, gather_map)); for (auto i = 0; i < source_table.num_columns(); ++i) { CUDF_TEST_EXPECT_COLUMNS_EQUAL(source_table.column(i), result->view().column(i)); } CUDF_TEST_EXPECT_TABLES_EQUAL(source_table, result->view()); } TYPED_TEST(GatherTest, ReverseIdentityTest) { constexpr cudf::size_type source_size{1000}; auto data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i; }); auto reversed_data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return source_size - 1 - i; }); cudf::test::fixed_width_column_wrapper<TypeParam> source_column(data, data + source_size); cudf::test::fixed_width_column_wrapper<int32_t> gather_map(reversed_data, reversed_data + source_size); cudf::table_view source_table({source_column}); std::unique_ptr<cudf::table> result = std::move(cudf::gather(source_table, gather_map)); cudf::test::fixed_width_column_wrapper<TypeParam> expect_column(reversed_data, reversed_data + source_size); for (auto i = 0; i < source_table.num_columns(); ++i) { CUDF_TEST_EXPECT_COLUMNS_EQUAL(expect_column, result->view().column(i)); } } TYPED_TEST(GatherTest, EveryOtherNullOdds) { constexpr cudf::size_type source_size{1000}; // Every other element is valid auto data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i; }); auto validity = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2; }); cudf::test::fixed_width_column_wrapper<TypeParam> source_column( data, data + source_size, validity); // Gather odd-valued indices auto map_data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i * 2; }); cudf::test::fixed_width_column_wrapper<int32_t> gather_map(map_data, map_data + (source_size / 2)); cudf::table_view source_table({source_column}); std::unique_ptr<cudf::table> result = std::move(cudf::gather(source_table, gather_map)); auto expect_data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return 0; }); auto expect_valid = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return 0; }); cudf::test::fixed_width_column_wrapper<TypeParam> expect_column( expect_data, expect_data + source_size / 2, expect_valid); for (auto i = 0; i < source_table.num_columns(); ++i) { CUDF_TEST_EXPECT_COLUMNS_EQUAL(expect_column, result->view().column(i)); } } TYPED_TEST(GatherTest, EveryOtherNullEvens) { constexpr cudf::size_type source_size{1000}; // Every other element is valid auto data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i; }); auto validity = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2; }); cudf::test::fixed_width_column_wrapper<TypeParam> source_column( data, data + source_size, validity); // Gather even-valued indices auto map_data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i * 2 + 1; }); cudf::test::fixed_width_column_wrapper<int32_t> gather_map(map_data, map_data + (source_size / 2)); cudf::table_view source_table({source_column}); std::unique_ptr<cudf::table> result = std::move(cudf::gather(source_table, gather_map)); auto expect_data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i * 2 + 1; }); auto expect_valid = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return 1; }); cudf::test::fixed_width_column_wrapper<TypeParam> expect_column( expect_data, expect_data + source_size / 2, expect_valid); for (auto i = 0; i < source_table.num_columns(); ++i) { CUDF_TEST_EXPECT_COLUMNS_EQUAL(expect_column, result->view().column(i)); } } TYPED_TEST(GatherTest, AllNull) { constexpr cudf::size_type source_size{1000}; // Every element is invalid auto data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i; }); auto validity = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return 0; }); // Create a gather map that gathers to random locations std::vector<cudf::size_type> host_map_data(source_size); std::iota(host_map_data.begin(), host_map_data.end(), 0); std::mt19937 g(0); std::shuffle(host_map_data.begin(), host_map_data.end(), g); cudf::test::fixed_width_column_wrapper<TypeParam> source_column{ data, data + source_size, validity}; cudf::test::fixed_width_column_wrapper<int32_t> gather_map(host_map_data.begin(), host_map_data.end()); cudf::table_view source_table({source_column}); std::unique_ptr<cudf::table> result = std::move(cudf::gather(source_table, gather_map)); // Check that the result is also all invalid CUDF_TEST_EXPECT_TABLES_EQUAL(source_table, result->view()); } TYPED_TEST(GatherTest, MultiColReverseIdentityTest) { constexpr cudf::size_type source_size{1000}; constexpr cudf::size_type n_cols = 3; auto data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i; }); auto reversed_data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return source_size - 1 - i; }); std::vector<cudf::test::fixed_width_column_wrapper<TypeParam>> source_column_wrappers; std::vector<cudf::column_view> source_columns; for (int i = 0; i < n_cols; ++i) { source_column_wrappers.push_back( cudf::test::fixed_width_column_wrapper<TypeParam>(data, data + source_size)); source_columns.push_back(source_column_wrappers[i]); } cudf::test::fixed_width_column_wrapper<int32_t> gather_map(reversed_data, reversed_data + source_size); cudf::table_view source_table{source_columns}; std::unique_ptr<cudf::table> result = std::move(cudf::gather(source_table, gather_map)); cudf::test::fixed_width_column_wrapper<TypeParam> expect_column(reversed_data, reversed_data + source_size); for (auto i = 0; i < source_table.num_columns(); ++i) { CUDF_TEST_EXPECT_COLUMNS_EQUAL(expect_column, result->view().column(i)); } } TYPED_TEST(GatherTest, MultiColNulls) { constexpr cudf::size_type source_size{1000}; static_assert(0 == source_size % 2, "Size of source data must be a multiple of 2."); constexpr cudf::size_type n_cols = 3; auto data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i; }); auto validity = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2; }); std::vector<cudf::test::fixed_width_column_wrapper<TypeParam>> source_column_wrappers; std::vector<cudf::column_view> source_columns; for (int i = 0; i < n_cols; ++i) { source_column_wrappers.push_back( cudf::test::fixed_width_column_wrapper<TypeParam>(data, data + source_size, validity)); source_columns.push_back(source_column_wrappers[i]); } auto reversed_data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return source_size - 1 - i; }); cudf::test::fixed_width_column_wrapper<int32_t> gather_map(reversed_data, reversed_data + source_size); cudf::table_view source_table{source_columns}; std::unique_ptr<cudf::table> result = std::move(cudf::gather(source_table, gather_map)); // Expected data auto expect_data = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return source_size - i - 1; }); auto expect_valid = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return (i + 1) % 2; }); cudf::test::fixed_width_column_wrapper<TypeParam> expect_column( expect_data, expect_data + source_size, expect_valid); for (auto i = 0; i < source_table.num_columns(); ++i) { CUDF_TEST_EXPECT_COLUMNS_EQUAL(expect_column, result->view().column(i)); } }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/encode/encode_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/table/table.hpp> #include <cudf/transform.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_lists.hpp> template <typename T> class EncodeNumericTests : public cudf::test::BaseFixture {}; using NumericTypesNotBool = cudf::test::Concat<cudf::test::IntegralTypesNotBool, cudf::test::FloatingPointTypes>; TYPED_TEST_SUITE(EncodeNumericTests, NumericTypesNotBool); TYPED_TEST(EncodeNumericTests, SingleNullEncode) { cudf::test::fixed_width_column_wrapper<TypeParam> input({1}, {0}); cudf::test::fixed_width_column_wrapper<cudf::size_type> expect({0}); auto const result = cudf::encode(cudf::table_view({input})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.second->view(), expect); } TYPED_TEST(EncodeNumericTests, EmptyEncode) { cudf::test::fixed_width_column_wrapper<TypeParam> input({}); cudf::test::fixed_width_column_wrapper<cudf::size_type> expect({}); auto const result = cudf::encode(cudf::table_view({input})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.second->view(), expect); } TYPED_TEST(EncodeNumericTests, SimpleNoNulls) { cudf::test::fixed_width_column_wrapper<TypeParam> input{{1, 2, 3, 2, 3, 2, 1}}; cudf::test::fixed_width_column_wrapper<cudf::size_type> expect{{0, 1, 2, 1, 2, 1, 0}}; cudf::test::fixed_width_column_wrapper<TypeParam> expect_keys{{1, 2, 3}}; auto const result = cudf::encode(cudf::table_view({input})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.first->view().column(0), expect_keys); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.second->view(), expect); } TYPED_TEST(EncodeNumericTests, SimpleWithNulls) { cudf::test::fixed_width_column_wrapper<TypeParam> input{{1, 2, 3, 2, 3, 2, 1}, {1, 1, 1, 0, 1, 1, 1}}; cudf::test::fixed_width_column_wrapper<cudf::size_type> expect{{0, 1, 2, 3, 2, 1, 0}}; cudf::test::fixed_width_column_wrapper<TypeParam> expect_keys{{1, 2, 3, 0}, {1, 1, 1, 0}}; auto const result = cudf::encode(cudf::table_view({input})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.first->view().column(0), expect_keys); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.second->view(), expect); } TYPED_TEST(EncodeNumericTests, UnorderedWithNulls) { cudf::test::fixed_width_column_wrapper<TypeParam> input{{2, 1, 5, 1, 1, 3, 2}, {0, 1, 1, 1, 0, 1, 1}}; cudf::test::fixed_width_column_wrapper<cudf::size_type> expect{{4, 0, 3, 0, 4, 2, 1}}; cudf::test::fixed_width_column_wrapper<TypeParam> expect_keys{{1, 2, 3, 5, 0}, {1, 1, 1, 1, 0}}; auto const result = cudf::encode(cudf::table_view({input})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.first->view().column(0), expect_keys); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.second->view(), expect); } struct EncodeStringTest : public cudf::test::BaseFixture {}; TEST_F(EncodeStringTest, SimpleNoNulls) { cudf::test::strings_column_wrapper input{"a", "b", "c", "d", "a"}; cudf::test::fixed_width_column_wrapper<cudf::size_type> expect{0, 1, 2, 3, 0}; cudf::test::strings_column_wrapper expect_keys{"a", "b", "c", "d"}; auto const result = cudf::encode(cudf::table_view({input})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.first->view().column(0), expect_keys); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.second->view(), expect); } TEST_F(EncodeStringTest, SimpleWithNulls) { cudf::test::strings_column_wrapper input{{"a", "b", "c", "d", "a"}, {1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<cudf::size_type> expect{0, 3, 1, 2, 3}; cudf::test::strings_column_wrapper expect_keys{{"a", "c", "d", "0"}, {1, 1, 1, 0}}; auto const result = cudf::encode(cudf::table_view({input})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.first->view().column(0), expect_keys); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.second->view(), expect); } TEST_F(EncodeStringTest, UnorderedWithNulls) { cudf::test::strings_column_wrapper input{{"ef", "a", "c", "d", "ef", "a"}, {1, 0, 1, 1, 0, 1}}; cudf::test::fixed_width_column_wrapper<cudf::size_type> expect{3, 4, 1, 2, 4, 0}; cudf::test::strings_column_wrapper expect_keys{{"a", "c", "d", "ef", "0"}, {1, 1, 1, 1, 0}}; auto const result = cudf::encode(cudf::table_view({input})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.first->view().column(0), expect_keys); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.second->view(), expect); } TYPED_TEST(EncodeNumericTests, TableEncodeWithNulls) { auto col_1 = cudf::test::fixed_width_column_wrapper<TypeParam>({1, 0, 2, 0, 1}, {1, 0, 1, 0, 1}); auto col_2 = cudf::test::fixed_width_column_wrapper<TypeParam>({1, 3, 2, 0, 1}, {1, 1, 1, 0, 1}); auto input = cudf::table_view({col_1, col_2}); auto expect_keys_col1 = cudf::test::fixed_width_column_wrapper<TypeParam>({1, 2, 0, 0}, {1, 1, 0, 0}); auto expect_keys_col2 = cudf::test::fixed_width_column_wrapper<TypeParam>({1, 2, 3, 0}, {1, 1, 1, 0}); auto expect_keys = cudf::table_view({expect_keys_col1, expect_keys_col2}); auto expect = cudf::test::fixed_width_column_wrapper<cudf::size_type>({0, 2, 1, 3, 0}); auto const result = cudf::encode(input); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(result.first->view(), expect_keys); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.second->view(), expect); } CUDF_TEST_PROGRAM_MAIN()
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/search/search_list_test.cpp
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/lists/lists_column_view.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/search.hpp> #include <cudf/table/table_view.hpp> using cudf::test::iterators::null_at; using cudf::test::iterators::nulls_at; using bools_col = cudf::test::fixed_width_column_wrapper<bool>; using int32s_col = cudf::test::fixed_width_column_wrapper<int32_t>; using structs_col = cudf::test::structs_column_wrapper; using strings_col = cudf::test::strings_column_wrapper; constexpr cudf::test::debug_output_level verbosity{cudf::test::debug_output_level::FIRST_ERROR}; constexpr int32_t null{0}; // Mark for null child elements at the current level constexpr int32_t XXX{0}; // Mark for null elements at all levels using TestTypes = cudf::test::Concat<cudf::test::IntegralTypesNotBool, cudf::test::FloatingPointTypes, cudf::test::DurationTypes, cudf::test::TimestampTypes>; template <typename T> struct TypedListsContainsTestScalarNeedle : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(TypedListsContainsTestScalarNeedle, TestTypes); TYPED_TEST(TypedListsContainsTestScalarNeedle, EmptyInput) { using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; using lists_col = cudf::test::lists_column_wrapper<TypeParam, int32_t>; auto const haystack = lists_col{}; auto const needle1 = [] { auto child = tdata_col{}; return cudf::list_scalar(child); }(); auto const needle2 = [] { auto child = tdata_col{1, 2, 3}; return cudf::list_scalar(child); }(); EXPECT_FALSE(cudf::contains(haystack, needle1)); EXPECT_FALSE(cudf::contains(haystack, needle2)); } TYPED_TEST(TypedListsContainsTestScalarNeedle, TrivialInput) { using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; using lists_col = cudf::test::lists_column_wrapper<TypeParam, int32_t>; auto const haystack = lists_col{{1, 2}, {1}, {}, {1, 3}, {4}, {1, 1}}; auto const needle1 = [] { auto child = tdata_col{1, 2}; return cudf::list_scalar(child); }(); auto const needle2 = [] { auto child = tdata_col{2, 1}; return cudf::list_scalar(child); }(); EXPECT_TRUE(cudf::contains(haystack, needle1)); // Lists are order-sensitive. EXPECT_FALSE(cudf::contains(haystack, needle2)); } TYPED_TEST(TypedListsContainsTestScalarNeedle, SlicedColumnInput) { using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; using lists_col = cudf::test::lists_column_wrapper<TypeParam, int32_t>; auto const haystack_original = lists_col{{0, 0}, {0}, {1, 2}, {1}, {}, {1, 3}, {0, 0}}; auto const haystack = cudf::slice(haystack_original, {2, 6})[0]; auto const needle1 = [] { auto child = tdata_col{1, 2}; return cudf::list_scalar(child); }(); auto const needle2 = [] { auto child = tdata_col{}; return cudf::list_scalar(child); }(); auto const needle3 = [] { auto child = tdata_col{0, 0}; return cudf::list_scalar(child); }(); EXPECT_TRUE(cudf::contains(haystack, needle1)); EXPECT_TRUE(cudf::contains(haystack, needle2)); EXPECT_FALSE(cudf::contains(haystack, needle3)); } TYPED_TEST(TypedListsContainsTestScalarNeedle, SimpleInputWithNulls) { using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; using lists_col = cudf::test::lists_column_wrapper<TypeParam, int32_t>; // Test with invalid scalar. { auto const haystack = lists_col{{1, 2}, {1}, {}, {1, 3}, {4}, {}, {1, 1}}; auto const needle = [] { auto child = tdata_col{}; return cudf::list_scalar(child, false); }(); EXPECT_FALSE(cudf::contains(haystack, needle)); } // Test with nulls at the top level. { auto const haystack = lists_col{{{1, 2}, {1}, {} /*NULL*/, {1, 3}, {4}, {} /*NULL*/, {1, 1}}, nulls_at({2, 5})}; auto const needle1 = [] { auto child = tdata_col{1, 2}; return cudf::list_scalar(child); }(); auto const needle2 = [] { auto child = tdata_col{}; return cudf::list_scalar(child, false); }(); EXPECT_TRUE(cudf::contains(haystack, needle1)); EXPECT_TRUE(cudf::contains(haystack, needle2)); } // Test with nulls at the children level. { auto const haystack = lists_col{{lists_col{1, 2}, lists_col{1}, lists_col{{1, null}, null_at(1)}, lists_col{} /*NULL*/, lists_col{1, 3}, lists_col{1, 4}, lists_col{4}, lists_col{} /*NULL*/, lists_col{1, 1}}, nulls_at({3, 7})}; auto const needle1 = [] { auto child = tdata_col{{1, null}, null_at(1)}; return cudf::list_scalar(child); }(); auto const needle2 = [] { auto child = tdata_col{{null, 1}, null_at(0)}; return cudf::list_scalar(child); }(); auto const needle3 = [] { auto child = tdata_col{1, 0}; return cudf::list_scalar(child); }(); EXPECT_TRUE(cudf::contains(haystack, needle1)); EXPECT_FALSE(cudf::contains(haystack, needle2)); EXPECT_FALSE(cudf::contains(haystack, needle3)); } } TYPED_TEST(TypedListsContainsTestScalarNeedle, SlicedInputHavingNulls) { using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; using lists_col = cudf::test::lists_column_wrapper<TypeParam, int32_t>; auto const haystack_original = lists_col{{{0, 0}, {0} /*NULL*/, lists_col{{1, null}, null_at(1)}, {1}, {} /*NULL*/, {1, 3}, {4}, {} /*NULL*/, {1, 1}, {0}}, nulls_at({1, 4, 7})}; auto const haystack = cudf::slice(haystack_original, {2, 9})[0]; auto const needle1 = [] { auto child = tdata_col{{1, null}, null_at(1)}; return cudf::list_scalar(child); }(); auto const needle2 = [] { auto child = tdata_col{}; return cudf::list_scalar(child); }(); auto const needle3 = [] { auto child = tdata_col{0, 0}; return cudf::list_scalar(child); }(); EXPECT_TRUE(cudf::contains(haystack, needle1)); EXPECT_FALSE(cudf::contains(haystack, needle2)); EXPECT_FALSE(cudf::contains(haystack, needle3)); } template <typename T> struct TypedListContainsTestColumnNeedles : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(TypedListContainsTestColumnNeedles, TestTypes); TYPED_TEST(TypedListContainsTestColumnNeedles, EmptyInput) { using lists_col = cudf::test::lists_column_wrapper<TypeParam, int32_t>; auto const haystack = lists_col{}; auto const needles = lists_col{}; auto const expected = bools_col{}; auto const result = cudf::contains(haystack, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result, verbosity); } TYPED_TEST(TypedListContainsTestColumnNeedles, TrivialInput) { using lists_col = cudf::test::lists_column_wrapper<TypeParam, int32_t>; auto const haystack = lists_col{{0, 1}, {2}, {3, 4, 5}, {2, 3, 4}, {}, {0, 2, 0}}; auto const needles = lists_col{{0, 1}, {1}, {3, 5, 4}, {}}; auto const expected = bools_col{1, 0, 0, 1}; auto const result = cudf::contains(haystack, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result, verbosity); } TYPED_TEST(TypedListContainsTestColumnNeedles, SlicedInputNoNulls) { using lists_col = cudf::test::lists_column_wrapper<TypeParam, int32_t>; auto const haystack_original = lists_col{{0, 0}, {0}, {0, 1}, {2}, {3, 4, 5}, {2, 3, 4}, {}, {0, 2, 0}}; auto const haystack = cudf::slice(haystack_original, {2, 8})[0]; auto const needles_original = lists_col{{0}, {0, 1}, {0, 0}, {3, 5, 4}, {}, {0, 0}, {} /*0*/}; auto const needles = cudf::slice(needles_original, {1, 5})[0]; auto const expected = bools_col{1, 0, 0, 1}; auto const result = cudf::contains(haystack, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result, verbosity); } TYPED_TEST(TypedListContainsTestColumnNeedles, SlicedInputHavingNulls) { using lists_col = cudf::test::lists_column_wrapper<TypeParam, int32_t>; auto const haystack_original = lists_col{{{0, 0}, {0} /*NULL*/, lists_col{{1, null}, null_at(1)}, {1}, {} /*NULL*/, {1, 3}, {4}, {} /*NULL*/, {1, 1}, {0}}, nulls_at({1, 4, 7})}; auto const haystack = cudf::slice(haystack_original, {2, 9})[0]; auto const needles_original = lists_col{{{0, 0}, {0} /*NULL*/, lists_col{{1, null}, null_at(1)}, {1}, {} /*NULL*/, {1, 3, 1}, {4}, {} /*NULL*/, {}, {0}}, nulls_at({1, 4, 7})}; auto const needles = cudf::slice(needles_original, {2, 9})[0]; auto const expected = bools_col{{1, 1, null, 0, 1, null, 0}, nulls_at({2, 5})}; auto const result = cudf::contains(haystack, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result, verbosity); } TYPED_TEST(TypedListContainsTestColumnNeedles, ListsOfStructs) { using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto const haystack = [] { auto offsets = int32s_col{0, 2, 3, 5, 8, 10}; // clang-format off auto data1 = tdata_col{1, 2, // 1, // 0, 1, // 1, 3, 4, // 0, 0 // }; auto data2 = tdata_col{1, 3, // 2, // 1, 1, // 0, 2, 0, // 1, 2 // }; // clang-format on auto child = structs_col{{data1, data2}}; return cudf::make_lists_column(5, offsets.release(), child.release(), 0, {}); }(); auto const needles = [] { auto offsets = int32s_col{0, 3, 4, 6, 9, 11}; // clang-format off auto data1 = tdata_col{1, 2, 1, // 1, // 0, 1, // 1, 3, 4, // 0, 0 // }; auto data2 = tdata_col{1, 3, 0, // 2, // 1, 1, // 0, 2, 2, // 1, 1 // }; // clang-format on auto child = structs_col{{data1, data2}}; return cudf::make_lists_column(5, offsets.release(), child.release(), 0, {}); }(); auto const expected = bools_col{0, 1, 1, 0, 0}; auto const result = cudf::contains(*haystack, *needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result, verbosity); } auto search_bounds(cudf::table_view const& t, cudf::table_view const& values, std::vector<cudf::order> const& column_order, std::vector<cudf::null_order> const& null_precedence = { cudf::null_order::BEFORE}) { auto result_lower_bound = cudf::lower_bound(t, values, column_order, null_precedence); auto result_upper_bound = cudf::upper_bound(t, values, column_order, null_precedence); return std::pair(std::move(result_lower_bound), std::move(result_upper_bound)); } struct ListBinarySearch : public cudf::test::BaseFixture {}; TEST_F(ListBinarySearch, ListWithNulls) { { using lcw = cudf::test::lists_column_wrapper<double>; auto const haystack = lcw{ lcw{-3.45967821e+12}, // 0 lcw{-3.6912186e-32}, // 1 lcw{9.721175}, // 2 }; auto const needles = lcw{ lcw{{null, 4.22671e+32}, null_at(0)}, }; auto const expected = int32s_col{0}; auto const [result_lower_bound, result_upper_bound] = search_bounds(cudf::table_view{{haystack}}, cudf::table_view{{needles}}, {cudf::order::ASCENDING}, {cudf::null_order::BEFORE}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result_lower_bound, verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result_upper_bound, verbosity); } { using lcw = cudf::test::lists_column_wrapper<int32_t, int32_t>; auto const col1 = lcw{ lcw{{null}, null_at(0)}, // 0 lcw{-80}, // 1 lcw{-17}, // 2 }; auto const col2 = lcw{ lcw{27}, // 0 lcw{{null}, null_at(0)}, // 1 lcw{}, // 2 }; auto const val1 = lcw{ lcw{87}, }; auto const val2 = lcw{ lcw{}, }; cudf::table_view input{{col1, col2}}; cudf::table_view values{{val1, val2}}; std::vector<cudf::order> column_order{cudf::order::ASCENDING, cudf::order::DESCENDING}; std::vector<cudf::null_order> null_order_flags{cudf::null_order::BEFORE, cudf::null_order::BEFORE}; auto const expected = int32s_col{3}; auto const [result_lower_bound, result_upper_bound] = search_bounds( cudf::table_view{{input}}, cudf::table_view{{values}}, column_order, null_order_flags); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result_lower_bound, verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result_upper_bound, verbosity); } } TEST_F(ListBinarySearch, ListsOfStructs) { // Haystack must be pre-sorted. auto const haystack = [] { auto offsets = int32s_col{0, 2, 3, 4, 5, 7, 10, 13, 16, 18}; // clang-format off auto data1 = int32s_col{1, 2, 3, 3, 3, 4, 5, 4, 5, 4, 4, 5, 4, 4, 5, 4, 4, 6 }; auto data2 = int32s_col{1, 2, 3, 3, 3, 4, 5, 4, 5, 4, 4, 5, 4, 4, 5, 4, 5, 1 }; // clang-format on auto child = structs_col{{data1, data2}}; return cudf::make_lists_column(9, offsets.release(), child.release(), 0, {}); }(); auto const needles = [] { auto offsets = int32s_col{0, 3, 4, 6, 8, 10, 13, 14, 15}; // clang-format off auto data1 = int32s_col{1, 2, 1, 3, 4, 1, 0, 1, 1, 0, 1, 3, 5, 3, 3 }; auto data2 = int32s_col{1, 3, 0, 3, 1, 2, 1, 1, 1, 2, 0, 2, 2, 3, 3 }; // clang-format on auto child = structs_col{{data1, data2}}; return cudf::make_lists_column(8, offsets.release(), child.release(), 0, {}); }(); auto const [result_lower_bound, result_upper_bound] = search_bounds( cudf::table_view{{*haystack}}, cudf::table_view{{*needles}}, {cudf::order::ASCENDING}); auto const expected_lower_bound = int32s_col{1, 1, 4, 0, 0, 0, 1, 1}; auto const expected_upper_bound = int32s_col{1, 4, 4, 0, 0, 0, 4, 4}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, *result_lower_bound, verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, *result_upper_bound, verbosity); } TEST_F(ListBinarySearch, ListsOfEqualStructsInTwoTables) { // Haystack must be pre-sorted. auto const haystack = [] { auto offsets = int32s_col{0, 2, 3, 4, 5, 7, 10, 13, 16, 18}; // clang-format off auto data1 = int32s_col{1, 2, 3, 3, 3, 4, 5, 4, 5, 4, 4, 5, 4, 4, 5, 4, 4, 6 }; auto data2 = int32s_col{1, 2, 3, 3, 3, 4, 5, 4, 5, 4, 4, 5, 4, 4, 5, 4, 5, 1 }; // clang-format on auto child = structs_col{{data1, data2}}; return cudf::make_lists_column(9, offsets.release(), child.release(), 0, {}); }(); auto const needles = [] { auto offsets = int32s_col{0, 2, 3, 4, 5, 7, 10, 13, 15, 17}; // clang-format off auto data1 = int32s_col{1, 2, 3, 4, 5, 4, 5, 5, 5, 4, 4, 5, 4, 4, 4, 4, 6 }; auto data2 = int32s_col{1, 2, 3, 4, 5, 4, 5, 5, 5, 4, 4, 5, 4, 4, 4, 5, 1 }; // clang-format on auto child = structs_col{{data1, data2}}; return cudf::make_lists_column(9, offsets.release(), child.release(), 0, {}); }(); // In this search, the two table have many equal structs. // This help to verify the internal implementation of two-table lex comparator in which the // structs column of two input tables are concatenated, ranked, then split. auto const [result_lower_bound, result_upper_bound] = search_bounds( cudf::table_view{{*haystack}}, cudf::table_view{{*needles}}, {cudf::order::ASCENDING}); auto const expected_lower_bound = int32s_col{0, 1, 4, 9, 4, 9, 5, 4, 8}; auto const expected_upper_bound = int32s_col{1, 4, 4, 9, 5, 9, 8, 4, 9}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, *result_lower_bound, verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, *result_upper_bound, verbosity); } TEST_F(ListBinarySearch, CrazyListTest) { // Data type: List<List<Struct<Struct<List<Struct<int, int>>>>>> // Haystack must be pre-sorted. auto const haystack = [] { auto lists_of_structs_of_ints = [] { auto offsets = int32s_col{0, 2, 3, 4, 5, 7, 10, 13, 16, 18}; // clang-format off auto data1 = int32s_col{1, 2, 3, 3, 3, 4, 5, 4, 5, 4, 4, 5, 4, 4, 5, 4, 4, 6 }; auto data2 = int32s_col{1, 2, 3, 3, 3, 4, 5, 4, 5, 4, 4, 5, 4, 4, 5, 4, 5, 1 }; // clang-format on auto child = structs_col{{data1, data2}}; return cudf::make_lists_column(9, offsets.release(), child.release(), 0, {}); }(); auto struct_nested0 = [&] { std::vector<std::unique_ptr<cudf::column>> child_columns; child_columns.emplace_back(std::move(lists_of_structs_of_ints)); return cudf::make_structs_column(9, std::move(child_columns), 0, {}); }(); auto struct_nested1 = [&] { std::vector<std::unique_ptr<cudf::column>> child_columns; child_columns.emplace_back(std::move(struct_nested0)); return cudf::make_structs_column(9, std::move(child_columns), 0, {}); }(); auto list_nested0 = [&] { auto offsets = int32s_col{0, 3, 3, 4, 6, 9}; return cudf::make_lists_column(5, offsets.release(), std::move(struct_nested1), 0, {}); }(); auto offsets = int32s_col{0, 0, 2, 4, 5, 5}; return cudf::make_lists_column(5, offsets.release(), std::move(list_nested0), 0, {}); }(); auto const needles = [] { auto lists_of_structs_of_ints = [] { auto offsets = int32s_col{0, 2, 3, 4, 5, 7, 10, 13, 15, 17}; // clang-format off auto data1 = int32s_col{1, 2, 3, 4, 5, 4, 5, 5, 5, 4, 4, 5, 4, 4, 4, 4, 6 }; auto data2 = int32s_col{1, 2, 3, 4, 5, 4, 5, 5, 5, 4, 4, 5, 4, 4, 4, 5, 1 }; // clang-format on auto child = structs_col{{data1, data2}}; return cudf::make_lists_column(9, offsets.release(), child.release(), 0, {}); }(); auto struct_nested0 = [&] { std::vector<std::unique_ptr<cudf::column>> child_columns; child_columns.emplace_back(std::move(lists_of_structs_of_ints)); return cudf::make_structs_column(9, std::move(child_columns), 0, {}); }(); auto struct_nested1 = [&] { std::vector<std::unique_ptr<cudf::column>> child_columns; child_columns.emplace_back(std::move(struct_nested0)); return cudf::make_structs_column(9, std::move(child_columns), 0, {}); }(); auto list_nested0 = [&] { auto offsets = int32s_col{0, 3, 3, 4, 6, 9}; return cudf::make_lists_column(5, offsets.release(), std::move(struct_nested1), 0, {}); }(); auto offsets = int32s_col{0, 2, 2, 4, 4, 5}; return cudf::make_lists_column(5, offsets.release(), std::move(list_nested0), 0, {}); }(); // In this search, the two table have many equal structs. // This help to verify the internal implementation of two-table lex comparator in which the // structs column of two input tables are concatenated, ranked, then split. auto const [result_lower_bound, result_upper_bound] = search_bounds( cudf::table_view{{*haystack}}, cudf::table_view{{*needles}}, {cudf::order::ASCENDING}); auto const expected_lower_bound = int32s_col{2, 0, 5, 0, 5}; auto const expected_upper_bound = int32s_col{2, 1, 5, 1, 5}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, *result_lower_bound, verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, *result_upper_bound, verbosity); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/search/search_struct_test.cpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/lists/lists_column_view.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/search.hpp> #include <cudf/table/table_view.hpp> using namespace cudf::test::iterators; using bools_col = cudf::test::fixed_width_column_wrapper<bool>; using int32s_col = cudf::test::fixed_width_column_wrapper<int32_t>; using structs_col = cudf::test::structs_column_wrapper; using strings_col = cudf::test::strings_column_wrapper; constexpr cudf::test::debug_output_level verbosity{cudf::test::debug_output_level::FIRST_ERROR}; constexpr int32_t null{0}; // Mark for null child elements at the current level constexpr int32_t XXX{0}; // Mark for null elements at all levels constexpr int32_t dont_care{0}; // Mark for elements that will be sliced off using TestTypes = cudf::test::Concat<cudf::test::IntegralTypesNotBool, cudf::test::FloatingPointTypes, cudf::test::DurationTypes, cudf::test::TimestampTypes>; template <typename T> struct TypedStructSearchTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(TypedStructSearchTest, TestTypes); namespace { auto search_bounds(cudf::column_view const& t_col_view, std::unique_ptr<cudf::column> const& values_col, std::vector<cudf::order> const& column_orders = {cudf::order::ASCENDING}, std::vector<cudf::null_order> const& null_precedence = { cudf::null_order::BEFORE}) { auto const t = cudf::table_view{std::vector<cudf::column_view>{t_col_view}}; auto const values = cudf::table_view{std::vector<cudf::column_view>{values_col->view()}}; auto result_lower_bound = cudf::lower_bound(t, values, column_orders, null_precedence); auto result_upper_bound = cudf::upper_bound(t, values, column_orders, null_precedence); return std::pair(std::move(result_lower_bound), std::move(result_upper_bound)); } auto search_bounds(std::unique_ptr<cudf::column> const& t_col, std::unique_ptr<cudf::column> const& values_col, std::vector<cudf::order> const& column_orders = {cudf::order::ASCENDING}, std::vector<cudf::null_order> const& null_precedence = { cudf::null_order::BEFORE}) { return search_bounds(t_col->view(), values_col, column_orders, null_precedence); } template <typename... Args> auto make_struct_scalar(Args&&... args) { return cudf::struct_scalar(std::vector<cudf::column_view>{std::forward<Args>(args)...}); } } // namespace // Test case when all input columns are empty TYPED_TEST(TypedStructSearchTest, EmptyInput) { using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto child_col_t = tdata_col{}; auto const structs_t = structs_col{{child_col_t}, std::vector<bool>{}}.release(); auto child_col_values = tdata_col{}; auto const structs_values = structs_col{{child_col_values}, std::vector<bool>{}}.release(); auto const results = search_bounds(structs_t, structs_values); auto const expected = int32s_col{}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, results.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, results.second->view(), verbosity); } TYPED_TEST(TypedStructSearchTest, TrivialInputTests) { using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto child_col_t = tdata_col{10, 20, 30, 40, 50}; auto const structs_t = structs_col{{child_col_t}}.release(); auto child_col_values1 = tdata_col{0, 1, 2, 3, 4}; auto const structs_values1 = structs_col{{child_col_values1}}.release(); auto child_col_values2 = tdata_col{100, 101, 102, 103, 104}; auto const structs_values2 = structs_col{{child_col_values2}}.release(); auto const results1 = search_bounds(structs_t, structs_values1); auto const expected1 = int32s_col{0, 0, 0, 0, 0}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected1, results1.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected1, results1.second->view(), verbosity); auto const results2 = search_bounds(structs_t, structs_values2); auto const expected2 = int32s_col{5, 5, 5, 5, 5}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected2, results2.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected2, results2.second->view(), verbosity); } TYPED_TEST(TypedStructSearchTest, SlicedColumnInputTests) { using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto child_col_values = tdata_col{0, 1, 2, 3, 4, 5}; auto const structs_values = structs_col{child_col_values}.release(); auto child_col_t = tdata_col{0, 1, 2, 2, 2, 2, 3, 3, 4, 4}; auto const structs_t_original = structs_col{child_col_t}.release(); auto structs_t = cudf::slice(structs_t_original->view(), {0, 10})[0]; // the entire column t auto results = search_bounds(structs_t, structs_values); auto expected_lower_bound = int32s_col{0, 1, 2, 6, 8, 10}; auto expected_upper_bound = int32s_col{1, 2, 6, 8, 10, 10}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, results.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, results.second->view(), verbosity); structs_t = cudf::slice(structs_t_original->view(), {0, 5})[0]; results = search_bounds(structs_t, structs_values); expected_lower_bound = int32s_col{0, 1, 2, 5, 5, 5}; expected_upper_bound = int32s_col{1, 2, 5, 5, 5, 5}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, results.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, results.second->view(), verbosity); structs_t = cudf::slice(structs_t_original->view(), {5, 10})[0]; results = search_bounds(structs_t, structs_values); expected_lower_bound = int32s_col{0, 0, 0, 1, 3, 5}; expected_upper_bound = int32s_col{0, 0, 1, 3, 5, 5}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, results.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, results.second->view(), verbosity); } TYPED_TEST(TypedStructSearchTest, SimpleInputWithNullsTests) { using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto child_col_values = tdata_col{{1, null, 70, XXX, 2, 100}, null_at(1)}; auto const structs_values = structs_col{{child_col_values}, null_at(3)}.release(); // Sorted asc, nulls first auto child_col_t = tdata_col{{XXX, null, 0, 1, 2, 2, 2, 2, 3, 3, 4}, null_at(1)}; auto structs_t = structs_col{{child_col_t}, null_at(0)}.release(); auto results = search_bounds(structs_t, structs_values, {cudf::order::ASCENDING}, {cudf::null_order::BEFORE}); auto expected_lower_bound = int32s_col{3, 1, 11, 0, 4, 11}; auto expected_upper_bound = int32s_col{4, 2, 11, 1, 8, 11}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, results.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, results.second->view(), verbosity); // Sorted asc, nulls last child_col_t = tdata_col{{0, 1, 2, 2, 2, 2, 3, 3, 4, null, XXX}, null_at(9)}; structs_t = structs_col{{child_col_t}, null_at(10)}.release(); results = search_bounds(structs_t, structs_values, {cudf::order::ASCENDING}, {cudf::null_order::AFTER}); expected_lower_bound = int32s_col{1, 9, 9, 10, 2, 9}; expected_upper_bound = int32s_col{2, 10, 9, 11, 6, 9}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, results.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, results.second->view(), verbosity); // Sorted dsc, nulls first child_col_t = tdata_col{{XXX, null, 4, 3, 3, 2, 2, 2, 2, 1, 0}, null_at(1)}; structs_t = structs_col{{child_col_t}, null_at(0)}.release(); results = search_bounds(structs_t, structs_values, {cudf::order::DESCENDING}, {cudf::null_order::BEFORE}); expected_lower_bound = int32s_col{9, 11, 0, 11, 5, 0}; expected_upper_bound = int32s_col{10, 11, 0, 11, 9, 0}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, results.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, results.second->view(), verbosity); // Sorted dsc, nulls last child_col_t = tdata_col{{4, 3, 3, 2, 2, 2, 2, 1, 0, null, XXX}, null_at(9)}; structs_t = structs_col{{child_col_t}, null_at(10)}.release(); results = search_bounds(structs_t, structs_values, {cudf::order::DESCENDING}, {cudf::null_order::AFTER}); expected_lower_bound = int32s_col{7, 0, 0, 0, 3, 0}; expected_upper_bound = int32s_col{8, 0, 0, 0, 7, 0}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, results.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, results.second->view(), verbosity); } TYPED_TEST(TypedStructSearchTest, SimpleInputWithValuesHavingNullsTests) { using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto child_col_values = tdata_col{{1, null, 70, XXX, 2, 100}, null_at(1)}; auto const structs_values = structs_col{{child_col_values}, null_at(3)}.release(); // Sorted asc, search nulls first auto child_col_t = tdata_col{0, 0, 0, 1, 2, 2, 2, 2, 3, 3, 4}; auto structs_t = structs_col{{child_col_t}}.release(); auto results = search_bounds(structs_t, structs_values, {cudf::order::ASCENDING}, {cudf::null_order::BEFORE}); auto expected_lower_bound = int32s_col{3, 0, 11, 0, 4, 11}; auto expected_upper_bound = int32s_col{4, 0, 11, 0, 8, 11}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, results.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, results.second->view(), verbosity); // Sorted asc, search nulls last results = search_bounds(structs_t, structs_values, {cudf::order::ASCENDING}, {cudf::null_order::AFTER}); expected_lower_bound = int32s_col{3, 11, 11, 11, 4, 11}; expected_upper_bound = int32s_col{4, 11, 11, 11, 8, 11}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, results.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, results.second->view(), verbosity); // Sorted dsc, search nulls first child_col_t = tdata_col{4, 3, 3, 2, 2, 2, 2, 1, 0, 0, 0}; structs_t = structs_col{{child_col_t}}.release(); results = search_bounds(structs_t, structs_values, {cudf::order::DESCENDING}, {cudf::null_order::BEFORE}); expected_lower_bound = int32s_col{7, 11, 0, 11, 3, 0}; expected_upper_bound = int32s_col{8, 11, 0, 11, 7, 0}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, results.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, results.second->view(), verbosity); // Sorted dsc, search nulls last results = search_bounds(structs_t, structs_values, {cudf::order::DESCENDING}, {cudf::null_order::AFTER}); expected_lower_bound = int32s_col{7, 0, 0, 0, 3, 0}; expected_upper_bound = int32s_col{8, 0, 0, 0, 7, 0}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, results.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, results.second->view(), verbosity); } TYPED_TEST(TypedStructSearchTest, SimpleInputWithTargetHavingNullsTests) { using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto child_col_values = tdata_col{1, 0, 70, 0, 2, 100}; auto const structs_values = structs_col{{child_col_values}}.release(); // Sorted asc, nulls first auto child_col_t = tdata_col{{XXX, null, 0, 1, 2, 2, 2, 2, 3, 3, 4}, null_at(1)}; auto structs_t = structs_col{{child_col_t}, null_at(0)}.release(); auto results = search_bounds(structs_t, structs_values, {cudf::order::ASCENDING}, {cudf::null_order::BEFORE}); auto expected_lower_bound = int32s_col{3, 2, 11, 2, 4, 11}; auto expected_upper_bound = int32s_col{4, 3, 11, 3, 8, 11}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, results.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, results.second->view(), verbosity); // Sorted asc, nulls last child_col_t = tdata_col{{0, 1, 2, 2, 2, 2, 3, 3, 4, null, XXX}, null_at(9)}; structs_t = structs_col{{child_col_t}, null_at(10)}.release(); results = search_bounds(structs_t, structs_values, {cudf::order::ASCENDING}, {cudf::null_order::AFTER}); expected_lower_bound = int32s_col{1, 0, 9, 0, 2, 9}; expected_upper_bound = int32s_col{2, 1, 9, 1, 6, 9}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, results.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, results.second->view(), verbosity); // Sorted dsc, nulls first child_col_t = tdata_col{{XXX, null, 4, 3, 3, 2, 2, 2, 2, 1, 0}, null_at(1)}; structs_t = structs_col{{child_col_t}, null_at(0)}.release(); results = search_bounds(structs_t, structs_values, {cudf::order::DESCENDING}, {cudf::null_order::BEFORE}); expected_lower_bound = int32s_col{9, 10, 0, 10, 5, 0}; expected_upper_bound = int32s_col{10, 11, 0, 11, 9, 0}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, results.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, results.second->view(), verbosity); // Sorted dsc, nulls last child_col_t = tdata_col{{4, 3, 3, 2, 2, 2, 2, 1, 0, null, XXX}, null_at(9)}; structs_t = structs_col{{child_col_t}, null_at(10)}.release(); results = search_bounds(structs_t, structs_values, {cudf::order::DESCENDING}, {cudf::null_order::AFTER}); expected_lower_bound = int32s_col{7, 8, 0, 8, 3, 0}; expected_upper_bound = int32s_col{8, 11, 0, 11, 7, 0}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, results.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, results.second->view(), verbosity); } TYPED_TEST(TypedStructSearchTest, OneColumnHasNullMaskButNoNullElementTest) { using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto child_col1 = tdata_col{1, 20, 30}; auto const structs_col1 = structs_col{{child_col1}}.release(); auto child_col2 = tdata_col{0, 10, 10}; auto const structs_col2 = structs_col{child_col2}.release(); // structs_col3 (and its child column) will have a null mask but no null element auto child_col3 = tdata_col{{0, 10, 10}, no_nulls()}; auto const structs_col3 = structs_col{{child_col3}, no_nulls()}.release(); // Search struct elements of structs_col2 and structs_col3 in the column structs_col1 { auto const results1 = search_bounds(structs_col1, structs_col2); auto const results2 = search_bounds(structs_col1, structs_col3); auto const expected_lower_bound = int32s_col{0, 1, 1}; auto const expected_upper_bound = int32s_col{0, 1, 1}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, results1.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, results2.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, results1.second->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, results2.second->view(), verbosity); } // Search struct elements of structs_col1 in the columns structs_col2 and structs_col3 { auto const results1 = search_bounds(structs_col2, structs_col1); auto const results2 = search_bounds(structs_col3, structs_col1); auto const expected_lower_bound = int32s_col{1, 3, 3}; auto const expected_upper_bound = int32s_col{1, 3, 3}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, results1.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, results2.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, results1.second->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, results2.second->view(), verbosity); } } TYPED_TEST(TypedStructSearchTest, ComplexStructTest) { // Testing on struct<string, numeric, bool>. using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto names_column_t = strings_col{"Cherry", "Kiwi", "Lemon", "Newton", "Tomato", /*NULL*/ "Washington"}; auto ages_column_t = tdata_col{{5, 10, 15, 20, null, XXX}, null_at(4)}; auto is_human_col_t = bools_col{false, false, false, false, false, /*NULL*/ true}; auto const structs_t = structs_col{{names_column_t, ages_column_t, is_human_col_t}, null_at(5)}.release(); auto names_column_values = strings_col{"Bagel", "Tomato", "Lemonade", /*NULL*/ "Donut", "Butter"}; auto ages_column_values = tdata_col{{10, null, 15, XXX, 17}, null_at(1)}; auto is_human_col_values = bools_col{false, false, true, /*NULL*/ true, true}; auto const structs_values = structs_col{{names_column_values, ages_column_values, is_human_col_values}, null_at(3)} .release(); auto const results = search_bounds(structs_t, structs_values, {cudf::order::ASCENDING}, {cudf::null_order::AFTER}); auto const expected_lower_bound = int32s_col{0, 4, 3, 5, 0}; auto const expected_upper_bound = int32s_col{0, 5, 3, 6, 0}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lower_bound, results.first->view(), verbosity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_upper_bound, results.second->view(), verbosity); } template <typename T> struct TypedStructContainsTestScalarNeedle : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(TypedStructContainsTestScalarNeedle, TestTypes); TYPED_TEST(TypedStructContainsTestScalarNeedle, EmptyInput) { using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto const haystack = [] { auto child = tdata_col{}; return structs_col{{child}}; }(); auto const needle1 = [] { auto child = tdata_col{1}; return make_struct_scalar(child); }(); auto const needle2 = [] { auto child1 = tdata_col{1}; auto child2 = tdata_col{1}; return make_struct_scalar(child1, child2); }(); EXPECT_FALSE(cudf::contains(haystack, needle1)); EXPECT_FALSE(cudf::contains(haystack, needle2)); } TYPED_TEST(TypedStructContainsTestScalarNeedle, TrivialInput) { using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto const haystack = [] { auto child1 = tdata_col{1, 2, 3}; auto child2 = tdata_col{4, 5, 6}; auto child3 = strings_col{"x", "y", "z"}; return structs_col{{child1, child2, child3}}; }(); auto const needle1 = [] { auto child1 = tdata_col{1}; auto child2 = tdata_col{4}; auto child3 = strings_col{"x"}; return make_struct_scalar(child1, child2, child3); }(); auto const needle2 = [] { auto child1 = tdata_col{1}; auto child2 = tdata_col{4}; auto child3 = strings_col{"a"}; return make_struct_scalar(child1, child2, child3); }(); EXPECT_TRUE(cudf::contains(haystack, needle1)); EXPECT_FALSE(cudf::contains(haystack, needle2)); } TYPED_TEST(TypedStructContainsTestScalarNeedle, SlicedColumnInput) { using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto const haystack_original = [] { auto child1 = tdata_col{dont_care, dont_care, 1, 2, 3, dont_care}; auto child2 = tdata_col{dont_care, dont_care, 4, 5, 6, dont_care}; auto child3 = strings_col{"dont_care", "dont_care", "x", "y", "z", "dont_care"}; return structs_col{{child1, child2, child3}}; }(); auto const haystack = cudf::slice(haystack_original, {2, 5})[0]; auto const needle1 = [] { auto child1 = tdata_col{1}; auto child2 = tdata_col{4}; auto child3 = strings_col{"x"}; return make_struct_scalar(child1, child2, child3); }(); auto const needle2 = [] { auto child1 = tdata_col{dont_care}; auto child2 = tdata_col{dont_care}; auto child3 = strings_col{"dont_care"}; return make_struct_scalar(child1, child2, child3); }(); EXPECT_TRUE(cudf::contains(haystack, needle1)); EXPECT_FALSE(cudf::contains(haystack, needle2)); } TYPED_TEST(TypedStructContainsTestScalarNeedle, SimpleInputWithNulls) { using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; constexpr int32_t null{0}; // Test with nulls at the top level. { auto const col1 = [] { auto child1 = tdata_col{1, null, 3}; auto child2 = tdata_col{4, null, 6}; auto child3 = strings_col{"x", "" /*NULL*/, "z"}; return structs_col{{child1, child2, child3}, null_at(1)}; }(); auto const needle1 = [] { auto child1 = tdata_col{1}; auto child2 = tdata_col{4}; auto child3 = strings_col{"x"}; return make_struct_scalar(child1, child2, child3); }(); auto const needle2 = [] { auto child1 = tdata_col{1}; auto child2 = tdata_col{4}; auto child3 = strings_col{"a"}; return make_struct_scalar(child1, child2, child3); }(); auto const needle3 = [] { auto child1 = tdata_col{{null}, null_at(0)}; auto child2 = tdata_col{{null}, null_at(0)}; auto child3 = strings_col{{""}, null_at(0)}; return make_struct_scalar(child1, child2, child3); }(); EXPECT_TRUE(cudf::contains(col1, needle1)); EXPECT_FALSE(cudf::contains(col1, needle2)); EXPECT_FALSE(cudf::contains(col1, needle3)); } // Test with nulls at the children level. { auto const col = [] { auto child1 = tdata_col{{1, null, 3}, null_at(1)}; auto child2 = tdata_col{{4, null, 6}, null_at(1)}; auto child3 = strings_col{{"" /*NULL*/, "" /*NULL*/, "z"}, nulls_at({0, 1})}; return structs_col{{child1, child2, child3}}; }(); auto const needle1 = [] { auto child1 = tdata_col{1}; auto child2 = tdata_col{4}; auto child3 = strings_col{{"" /*NULL*/}, null_at(0)}; return make_struct_scalar(child1, child2, child3); }(); auto const needle2 = [] { auto child1 = tdata_col{1}; auto child2 = tdata_col{4}; auto child3 = strings_col{""}; return make_struct_scalar(child1, child2, child3); }(); auto const needle3 = [] { auto child1 = tdata_col{{null}, null_at(0)}; auto child2 = tdata_col{{null}, null_at(0)}; auto child3 = strings_col{{""}, null_at(0)}; return make_struct_scalar(child1, child2, child3); }(); EXPECT_TRUE(cudf::contains(col, needle1)); EXPECT_FALSE(cudf::contains(col, needle2)); EXPECT_TRUE(cudf::contains(col, needle3)); } // Test with nulls in the input scalar. { auto const haystack = [] { auto child1 = tdata_col{1, 2, 3}; auto child2 = tdata_col{4, 5, 6}; auto child3 = strings_col{"x", "y", "z"}; return structs_col{{child1, child2, child3}}; }(); auto const needle1 = [] { auto child1 = tdata_col{1}; auto child2 = tdata_col{4}; auto child3 = strings_col{"x"}; return make_struct_scalar(child1, child2, child3); }(); auto const needle2 = [] { auto child1 = tdata_col{1}; auto child2 = tdata_col{4}; auto child3 = strings_col{{"" /*NULL*/}, null_at(0)}; return make_struct_scalar(child1, child2, child3); }(); EXPECT_TRUE(cudf::contains(haystack, needle1)); EXPECT_FALSE(cudf::contains(haystack, needle2)); } } TYPED_TEST(TypedStructContainsTestScalarNeedle, SlicedInputWithNulls) { using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; // Test with nulls at the top level. { auto const haystack_original = [] { auto child1 = tdata_col{dont_care, dont_care, 1, null, 3, dont_care}; auto child2 = tdata_col{dont_care, dont_care, 4, null, 6, dont_care}; auto child3 = strings_col{"dont_care", "dont_care", "x", "" /*NULL*/, "z", "dont_care"}; return structs_col{{child1, child2, child3}, null_at(3)}; }(); auto const col = cudf::slice(haystack_original, {2, 5})[0]; auto const needle1 = [] { auto child1 = tdata_col{1}; auto child2 = tdata_col{4}; auto child3 = strings_col{"x"}; return make_struct_scalar(child1, child2, child3); }(); auto const needle2 = [] { auto child1 = tdata_col{1}; auto child2 = tdata_col{4}; auto child3 = strings_col{"a"}; return make_struct_scalar(child1, child2, child3); }(); EXPECT_TRUE(cudf::contains(col, needle1)); EXPECT_FALSE(cudf::contains(col, needle2)); } // Test with nulls at the children level. { auto const haystack_original = [] { auto child1 = tdata_col{{dont_care, dont_care /*also NULL*/, 1, null, 3, dont_care}, null_at(3)}; auto child2 = tdata_col{{dont_care, dont_care /*also NULL*/, 4, null, 6, dont_care}, null_at(3)}; auto child3 = strings_col{ {"dont_care", "dont_care" /*also NULL*/, "" /*NULL*/, "y", "z", "dont_care"}, null_at(2)}; return structs_col{{child1, child2, child3}, null_at(1)}; }(); auto const haystack = cudf::slice(haystack_original, {2, 5})[0]; auto const needle1 = [] { auto child1 = tdata_col{1}; auto child2 = tdata_col{4}; auto child3 = strings_col{{"x"}, null_at(0)}; return make_struct_scalar(child1, child2, child3); }(); auto const needle2 = [] { auto child1 = tdata_col{dont_care}; auto child2 = tdata_col{dont_care}; auto child3 = strings_col{"dont_care"}; return make_struct_scalar(child1, child2, child3); }(); EXPECT_TRUE(cudf::contains(haystack, needle1)); EXPECT_FALSE(cudf::contains(haystack, needle2)); } } template <typename T> struct TypedStructContainsTestColumnNeedles : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(TypedStructContainsTestColumnNeedles, TestTypes); TYPED_TEST(TypedStructContainsTestColumnNeedles, EmptyInput) { using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto const haystack = [] { auto child1 = tdata_col{}; auto child2 = tdata_col{}; auto child3 = strings_col{}; return structs_col{{child1, child2, child3}}; }(); { auto const needles = [] { auto child1 = tdata_col{}; auto child2 = tdata_col{}; auto child3 = strings_col{}; return structs_col{{child1, child2, child3}}; }(); auto const expected = bools_col{}; auto const result = cudf::contains(haystack, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result, verbosity); } { auto const needles = [] { auto child1 = tdata_col{1, 2}; auto child2 = tdata_col{0, 2}; auto child3 = strings_col{"x", "y"}; return structs_col{{child1, child2, child3}}; }(); auto const result = cudf::contains(haystack, needles); auto const expected = bools_col{0, 0}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result, verbosity); } } TYPED_TEST(TypedStructContainsTestColumnNeedles, TrivialInput) { using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto const haystack = [] { auto child1 = tdata_col{1, 3, 1, 1, 2, 1, 2, 2, 1, 2}; auto child2 = tdata_col{1, 0, 0, 0, 1, 0, 1, 2, 1, 1}; return structs_col{{child1, child2}}; }(); auto const needles = [] { auto child1 = tdata_col{1, 3, 1, 1, 2, 1, 0, 0, 1, 0}; auto child2 = tdata_col{1, 0, 2, 3, 2, 1, 0, 0, 1, 0}; return structs_col{{child1, child2}}; }(); auto const expected = bools_col{1, 1, 0, 0, 1, 1, 0, 0, 1, 0}; auto const result = cudf::contains(haystack, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result, verbosity); } TYPED_TEST(TypedStructContainsTestColumnNeedles, SlicedInputNoNulls) { using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto const haystack_original = [] { auto child1 = tdata_col{dont_care, dont_care, 1, 3, 1, 1, 2, dont_care}; auto child2 = tdata_col{dont_care, dont_care, 1, 0, 0, 0, 1, dont_care}; auto child3 = strings_col{"dont_care", "dont_care", "x", "y", "z", "a", "b", "dont_care"}; return structs_col{{child1, child2, child3}}; }(); auto const haystack = cudf::slice(haystack_original, {2, 7})[0]; auto const needles_original = [] { auto child1 = tdata_col{dont_care, 1, 1, 1, 1, 2, dont_care, dont_care}; auto child2 = tdata_col{dont_care, 0, 1, 2, 3, 1, dont_care, dont_care}; auto child3 = strings_col{"dont_care", "z", "x", "z", "a", "b", "dont_care", "dont_care"}; return structs_col{{child1, child2, child3}}; }(); auto const needles = cudf::slice(needles_original, {1, 6})[0]; auto const expected = bools_col{1, 1, 0, 0, 1}; auto const result = cudf::contains(haystack, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result, verbosity); } TYPED_TEST(TypedStructContainsTestColumnNeedles, SlicedInputHavingNulls) { using tdata_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto const haystack_original = [] { auto child1 = tdata_col{{dont_care /*null*/, dont_care, 1, null, XXX, 1, 2, null, 2, 2, null, 2, dont_care}, nulls_at({0, 3, 7, 10})}; auto child2 = tdata_col{{dont_care /*null*/, dont_care, 1, null, XXX, 0, null, 0, 1, 2, 1, 1, dont_care}, nulls_at({0, 3, 6})}; return structs_col{{child1, child2}, nulls_at({1, 4})}; }(); auto const haystack = cudf::slice(haystack_original, {2, 12})[0]; auto const needles_original = [] { auto child1 = tdata_col{{dont_care, XXX, null, 1, 1, 2, XXX, null, 1, 1, null, dont_care, dont_care}, nulls_at({2, 7, 10})}; auto child2 = tdata_col{{dont_care, XXX, null, 2, 3, 2, XXX, null, null, 1, 0, dont_care, dont_care}, nulls_at({2, 7, 8})}; return structs_col{{child1, child2}, nulls_at({1, 6})}; }(); auto const needles = cudf::slice(needles_original, {1, 11})[0]; auto const expected = bools_col{{null, 1, 0, 0, 1, null, 1, 0, 1, 1}, nulls_at({0, 5})}; auto const result = cudf::contains(haystack, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result, verbosity); } TYPED_TEST(TypedStructContainsTestColumnNeedles, StructOfLists) { using lists_col = cudf::test::lists_column_wrapper<TypeParam, int32_t>; auto const haystack = [] { // clang-format off auto child1 = lists_col{{1, 2}, {1}, {}, {1, 3}}; auto child2 = lists_col{{1, 3, 4}, {2, 3, 4}, {}, {}}; // clang-format on return structs_col{{child1, child2}}; }(); auto const needles = [] { // clang-format off auto child1 = lists_col{{1, 2}, {1}, {}, {1, 3}, {}}; auto child2 = lists_col{{1, 3, 4}, {2, 3}, {1, 2}, {}, {}}; // clang-format on return structs_col{{child1, child2}}; }(); auto const expected = bools_col{1, 0, 0, 1, 1}; auto const result = cudf::contains(haystack, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result, verbosity); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/search/search_test.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/fixed_point/fixed_point.hpp> #include <cudf/search.hpp> #include <thrust/iterator/transform_iterator.h> struct SearchTest : public cudf::test::BaseFixture {}; using cudf::numeric_scalar; using cudf::size_type; using cudf::string_scalar; using cudf::test::fixed_width_column_wrapper; TEST_F(SearchTest, empty_table) { using element_type = int64_t; fixed_width_column_wrapper<element_type> column{}; fixed_width_column_wrapper<element_type> values{0, 7, 10, 11, 30, 32, 40, 47, 50, 90}; fixed_width_column_wrapper<size_type> expect{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::lower_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::ASCENDING}, {cudf::null_order::BEFORE})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, empty_values) { using element_type = int64_t; fixed_width_column_wrapper<element_type> column{10, 20, 30, 40, 50}; fixed_width_column_wrapper<element_type> values{}; fixed_width_column_wrapper<size_type> expect{}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::lower_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::ASCENDING}, {cudf::null_order::BEFORE})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, non_null_column__find_first) { using element_type = int64_t; fixed_width_column_wrapper<element_type> column{10, 20, 30, 40, 50}; fixed_width_column_wrapper<element_type> values{0, 7, 10, 11, 30, 32, 40, 47, 50, 90}; fixed_width_column_wrapper<size_type> expect{0, 0, 0, 1, 2, 3, 3, 4, 4, 5}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::lower_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::ASCENDING}, {cudf::null_order::BEFORE})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, non_null_column__find_last) { using element_type = int64_t; fixed_width_column_wrapper<element_type> column{10, 20, 30, 40, 50}; fixed_width_column_wrapper<element_type> values{0, 7, 10, 11, 30, 32, 40, 47, 50, 90}; fixed_width_column_wrapper<size_type> expect{0, 0, 1, 1, 3, 3, 4, 4, 5, 5}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::upper_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::ASCENDING}, {cudf::null_order::BEFORE})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, non_null_column_desc__find_first) { using element_type = int64_t; fixed_width_column_wrapper<element_type> column{50, 40, 30, 20, 10}; fixed_width_column_wrapper<element_type> values{0, 7, 10, 11, 30, 32, 40, 47, 50, 90}; fixed_width_column_wrapper<size_type> expect{5, 5, 4, 4, 2, 2, 1, 1, 0, 0}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::lower_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::DESCENDING}, {cudf::null_order::BEFORE})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, non_null_column_desc__find_last) { using element_type = int64_t; fixed_width_column_wrapper<element_type> column{50, 40, 30, 20, 10}; fixed_width_column_wrapper<element_type> values{0, 7, 10, 11, 30, 32, 40, 47, 50, 90}; fixed_width_column_wrapper<size_type> expect{5, 5, 5, 4, 3, 2, 2, 1, 1, 0}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::upper_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::DESCENDING}, {cudf::null_order::BEFORE})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, nullable_column__find_last__nulls_as_smallest) { using element_type = int64_t; fixed_width_column_wrapper<element_type> column{{10, 60, 10, 20, 30, 40, 50}, {0, 0, 1, 1, 1, 1, 1}}; fixed_width_column_wrapper<element_type> values{{8, 8, 10, 11, 30, 32, 40, 47, 50, 90}, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1}}; fixed_width_column_wrapper<size_type> expect{2, 2, 3, 3, 5, 5, 6, 6, 7, 7}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::upper_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::ASCENDING}, {cudf::null_order::BEFORE})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, nullable_column__find_first__nulls_as_smallest) { using element_type = int64_t; fixed_width_column_wrapper<element_type> column{{10, 60, 10, 20, 30, 40, 50}, {0, 0, 1, 1, 1, 1, 1}}; fixed_width_column_wrapper<element_type> values{{8, 8, 10, 11, 30, 32, 40, 47, 50, 90}, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1}}; fixed_width_column_wrapper<size_type> expect{0, 2, 2, 3, 4, 5, 5, 6, 6, 7}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::lower_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::ASCENDING}, {cudf::null_order::BEFORE})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, nullable_column__find_last__nulls_as_largest) { using element_type = int64_t; fixed_width_column_wrapper<element_type> column{{10, 20, 30, 40, 50, 10, 60}, {1, 1, 1, 1, 1, 0, 0}}; fixed_width_column_wrapper<element_type> values{{8, 10, 11, 30, 32, 40, 47, 50, 90, 8}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 0}}; fixed_width_column_wrapper<size_type> expect{0, 1, 1, 3, 3, 4, 4, 5, 5, 7}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::upper_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::ASCENDING}, {cudf::null_order::AFTER})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, nullable_column__find_first__nulls_as_largest) { using element_type = int64_t; fixed_width_column_wrapper<element_type> column{{10, 20, 30, 40, 50, 10, 60}, {1, 1, 1, 1, 1, 0, 0}}; fixed_width_column_wrapper<element_type> values{{8, 10, 11, 30, 32, 40, 47, 50, 90, 8}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 0}}; fixed_width_column_wrapper<size_type> expect{0, 0, 1, 2, 3, 3, 4, 4, 5, 5}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::lower_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::ASCENDING}, {cudf::null_order::AFTER})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, table__find_first) { fixed_width_column_wrapper<int32_t> column_0{10, 20, 20, 20, 20, 20, 50}; fixed_width_column_wrapper<float> column_1{5.0, .5, .5, .7, .7, .7, .7}; fixed_width_column_wrapper<int8_t> column_2{90, 77, 78, 61, 62, 63, 41}; fixed_width_column_wrapper<int32_t> values_0{0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 11, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 30, 50, 60}; fixed_width_column_wrapper<float> values_1{0., 0., 6., 5., 0., 5., 5., 5., 5., 6., 6., 6., 9., 0., .5, .5, .5, .5, .6, .6, .6, .7, .7, .7, .7, .7, .5}; fixed_width_column_wrapper<int8_t> values_2{0, 91, 0, 91, 0, 79, 90, 91, 77, 80, 90, 91, 91, 0, 76, 77, 78, 30, 65, 77, 78, 80, 62, 78, 64, 41, 20}; fixed_width_column_wrapper<size_type> expect{0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 2, 1, 3, 3, 3, 6, 4, 6, 6, 6, 7}; std::vector<std::unique_ptr<cudf::column>> columns; columns.push_back(column_0.release()); columns.push_back(column_1.release()); columns.push_back(column_2.release()); std::vector<std::unique_ptr<cudf::column>> values; values.push_back(values_0.release()); values.push_back(values_1.release()); values.push_back(values_2.release()); cudf::table input_table(std::move(columns)); cudf::table values_table(std::move(values)); std::vector<cudf::order> order_flags{ {cudf::order::ASCENDING, cudf::order::ASCENDING, cudf::order::ASCENDING}}; std::vector<cudf::null_order> null_order_flags{ {cudf::null_order::BEFORE, cudf::null_order::BEFORE, cudf::null_order::BEFORE}}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::lower_bound(input_table, values_table, order_flags, null_order_flags)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, table__find_last) { fixed_width_column_wrapper<int32_t> column_0{10, 20, 20, 20, 20, 20, 50}; fixed_width_column_wrapper<float> column_1{5.0, .5, .5, .7, .7, .7, .7}; fixed_width_column_wrapper<int8_t> column_2{90, 77, 78, 61, 62, 63, 41}; fixed_width_column_wrapper<int32_t> values_0{0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 11, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 30, 50, 60}; fixed_width_column_wrapper<float> values_1{0., 0., 6., 5., 0., 5., 5., 5., 5., 6., 6., 6., 9., 0., .5, .5, .5, .5, .6, .6, .6, .7, .7, .7, .7, .7, .5}; fixed_width_column_wrapper<int8_t> values_2{0, 91, 0, 91, 0, 79, 90, 91, 77, 80, 90, 91, 91, 0, 76, 77, 78, 30, 65, 77, 78, 80, 62, 78, 64, 41, 20}; fixed_width_column_wrapper<size_type> expect{0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 2, 3, 1, 3, 3, 3, 6, 5, 6, 6, 7, 7}; std::vector<std::unique_ptr<cudf::column>> columns; columns.push_back(column_0.release()); columns.push_back(column_1.release()); columns.push_back(column_2.release()); std::vector<std::unique_ptr<cudf::column>> values; values.push_back(values_0.release()); values.push_back(values_1.release()); values.push_back(values_2.release()); cudf::table input_table(std::move(columns)); cudf::table values_table(std::move(values)); std::vector<cudf::order> order_flags{ {cudf::order::ASCENDING, cudf::order::ASCENDING, cudf::order::ASCENDING}}; std::vector<cudf::null_order> null_order_flags{ {cudf::null_order::BEFORE, cudf::null_order::BEFORE, cudf::null_order::BEFORE}}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::upper_bound(input_table, values_table, order_flags, null_order_flags)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, table_partial_desc__find_first) { fixed_width_column_wrapper<int32_t> column_0{50, 20, 20, 20, 20, 20, 10}; fixed_width_column_wrapper<float> column_1{.7, .5, .5, .7, .7, .7, 5.0}; fixed_width_column_wrapper<int8_t> column_2{41, 78, 77, 63, 62, 61, 90}; fixed_width_column_wrapper<int32_t> values_0{0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 11, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 30, 50, 60}; fixed_width_column_wrapper<float> values_1{0., 0., 6., 5., 0., 5., 5., 5., 5., 6., 6., 6., 9., 0., .5, .5, .5, .5, .6, .6, .6, .7, .7, .7, .7, .7, .5}; fixed_width_column_wrapper<int8_t> values_2{0, 91, 0, 91, 0, 79, 90, 91, 77, 80, 90, 91, 91, 0, 76, 77, 78, 30, 65, 77, 78, 80, 62, 78, 64, 41, 20}; fixed_width_column_wrapper<size_type> expect{7, 7, 7, 7, 6, 7, 6, 6, 7, 7, 7, 7, 6, 1, 3, 2, 1, 3, 3, 3, 3, 3, 4, 3, 1, 0, 0}; std::vector<std::unique_ptr<cudf::column>> columns; columns.push_back(column_0.release()); columns.push_back(column_1.release()); columns.push_back(column_2.release()); std::vector<std::unique_ptr<cudf::column>> values; values.push_back(values_0.release()); values.push_back(values_1.release()); values.push_back(values_2.release()); cudf::table input_table(std::move(columns)); cudf::table values_table(std::move(values)); std::vector<cudf::order> order_flags{ {cudf::order::DESCENDING, cudf::order::ASCENDING, cudf::order::DESCENDING}}; std::vector<cudf::null_order> null_order_flags{ {cudf::null_order::BEFORE, cudf::null_order::BEFORE, cudf::null_order::BEFORE}}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::lower_bound(input_table, values_table, order_flags, null_order_flags)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, table_partial_desc__find_last) { fixed_width_column_wrapper<int32_t> column_0{50, 20, 20, 20, 20, 20, 10}; fixed_width_column_wrapper<float> column_1{.7, .5, .5, .7, .7, .7, 5.0}; fixed_width_column_wrapper<int8_t> column_2{41, 78, 77, 63, 62, 61, 90}; fixed_width_column_wrapper<int32_t> values_0{0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 11, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 30, 50, 60}; fixed_width_column_wrapper<float> values_1{0., 0., 6., 5., 0., 5., 5., 5., 5., 6., 6., 6., 9., 0., .5, .5, .5, .5, .6, .6, .6, .7, .7, .7, .7, .7, .5}; fixed_width_column_wrapper<int8_t> values_2{0, 91, 0, 91, 0, 79, 90, 91, 77, 80, 90, 91, 91, 0, 76, 77, 78, 30, 65, 77, 78, 80, 62, 78, 64, 41, 20}; fixed_width_column_wrapper<size_type> expect{7, 7, 7, 7, 6, 7, 7, 6, 7, 7, 7, 7, 6, 1, 3, 3, 2, 3, 3, 3, 3, 3, 5, 3, 1, 1, 0}; std::vector<std::unique_ptr<cudf::column>> columns; columns.push_back(column_0.release()); columns.push_back(column_1.release()); columns.push_back(column_2.release()); std::vector<std::unique_ptr<cudf::column>> values; values.push_back(values_0.release()); values.push_back(values_1.release()); values.push_back(values_2.release()); cudf::table input_table(std::move(columns)); cudf::table values_table(std::move(values)); std::vector<cudf::order> order_flags{ {cudf::order::DESCENDING, cudf::order::ASCENDING, cudf::order::DESCENDING}}; std::vector<cudf::null_order> null_order_flags{ {cudf::null_order::BEFORE, cudf::null_order::BEFORE, cudf::null_order::BEFORE}}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::upper_bound(input_table, values_table, order_flags, null_order_flags)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, table__find_first__nulls_as_smallest) { fixed_width_column_wrapper<int32_t> column_0{{30, 10, 10, 20, 20, 20, 20, 20, 20, 20, 50}, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}; fixed_width_column_wrapper<float> column_1{{.5, 6.0, 5.0, .5, .5, .5, .5, .7, .7, .7, .7}, {1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1}}; fixed_width_column_wrapper<int8_t> column_2{{50, 95, 90, 79, 76, 77, 78, 61, 62, 63, 41}, {1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1}}; fixed_width_column_wrapper<int32_t> values_0{{10, 40, 20}, {1, 0, 1}}; fixed_width_column_wrapper<float> values_1{{6., .5, .5}, {0, 1, 1}}; fixed_width_column_wrapper<int8_t> values_2{{95, 50, 77}, {1, 1, 0}}; fixed_width_column_wrapper<size_type> expect{1, 0, 3}; std::vector<std::unique_ptr<cudf::column>> columns; columns.push_back(column_0.release()); columns.push_back(column_1.release()); columns.push_back(column_2.release()); std::vector<std::unique_ptr<cudf::column>> values; values.push_back(values_0.release()); values.push_back(values_1.release()); values.push_back(values_2.release()); cudf::table input_table(std::move(columns)); cudf::table values_table(std::move(values)); std::vector<cudf::order> order_flags{ {cudf::order::ASCENDING, cudf::order::ASCENDING, cudf::order::ASCENDING}}; std::vector<cudf::null_order> null_order_flags{ {cudf::null_order::BEFORE, cudf::null_order::BEFORE, cudf::null_order::BEFORE}}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::lower_bound(input_table, values_table, order_flags, null_order_flags)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, table__find_last__nulls_as_smallest) { fixed_width_column_wrapper<int32_t> column_0{{30, 10, 10, 20, 20, 20, 20, 20, 20, 20, 50}, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}; fixed_width_column_wrapper<float> column_1{{.5, 6.0, 5.0, .5, .5, .5, .5, .7, .7, .7, .7}, {1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1}}; fixed_width_column_wrapper<int8_t> column_2{{50, 90, 95, 79, 76, 77, 78, 61, 62, 63, 41}, {1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1}}; fixed_width_column_wrapper<int32_t> values_0{{10, 40, 20}, {1, 0, 1}}; fixed_width_column_wrapper<float> values_1{{6., .5, .5}, {0, 1, 1}}; fixed_width_column_wrapper<int8_t> values_2{{95, 50, 77}, {1, 1, 0}}; fixed_width_column_wrapper<size_type> expect{2, 1, 5}; std::vector<std::unique_ptr<cudf::column>> columns; columns.push_back(column_0.release()); columns.push_back(column_1.release()); columns.push_back(column_2.release()); std::vector<std::unique_ptr<cudf::column>> values; values.push_back(values_0.release()); values.push_back(values_1.release()); values.push_back(values_2.release()); cudf::table input_table(std::move(columns)); cudf::table values_table(std::move(values)); std::vector<cudf::order> order_flags{ {cudf::order::ASCENDING, cudf::order::ASCENDING, cudf::order::ASCENDING}}; std::vector<cudf::null_order> null_order_flags{ {cudf::null_order::BEFORE, cudf::null_order::BEFORE, cudf::null_order::BEFORE}}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::upper_bound(input_table, values_table, order_flags, null_order_flags)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, table__find_first__nulls_as_largest) { fixed_width_column_wrapper<int32_t> column_0{{10, 10, 20, 20, 20, 20, 20, 20, 20, 50, 30}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}}; fixed_width_column_wrapper<float> column_1{{5.0, 6.0, .5, .5, .5, .5, .7, .7, .7, .7, .5}, {1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1}}; fixed_width_column_wrapper<int8_t> column_2{{90, 95, 77, 78, 79, 76, 61, 62, 63, 41, 50}, {1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1}}; fixed_width_column_wrapper<int32_t> values_0{{10, 40, 20}, {1, 0, 1}}; fixed_width_column_wrapper<float> values_1{{6., .5, .5}, {0, 1, 1}}; fixed_width_column_wrapper<int8_t> values_2{{95, 50, 77}, {1, 1, 0}}; fixed_width_column_wrapper<size_type> expect{1, 10, 4}; std::vector<std::unique_ptr<cudf::column>> columns; columns.push_back(column_0.release()); columns.push_back(column_1.release()); columns.push_back(column_2.release()); std::vector<std::unique_ptr<cudf::column>> values; values.push_back(values_0.release()); values.push_back(values_1.release()); values.push_back(values_2.release()); cudf::table input_table(std::move(columns)); cudf::table values_table(std::move(values)); std::vector<cudf::order> order_flags{ {cudf::order::ASCENDING, cudf::order::ASCENDING, cudf::order::ASCENDING}}; std::vector<cudf::null_order> null_order_flags{ {cudf::null_order::AFTER, cudf::null_order::AFTER, cudf::null_order::AFTER}}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::lower_bound(input_table, values_table, order_flags, null_order_flags)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, table__find_last__nulls_as_largest) { fixed_width_column_wrapper<int32_t> column_0{{10, 10, 20, 20, 20, 20, 20, 20, 20, 50, 30}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}}; fixed_width_column_wrapper<float> column_1{{5.0, 6.0, .5, .5, .5, .5, .7, .7, .7, .7, .5}, {1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1}}; fixed_width_column_wrapper<int8_t> column_2{{90, 95, 77, 78, 79, 76, 61, 62, 63, 41, 50}, {1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1}}; fixed_width_column_wrapper<int32_t> values_0{{10, 40, 20}, {1, 0, 1}}; fixed_width_column_wrapper<float> values_1{{6., .5, .5}, {0, 1, 1}}; fixed_width_column_wrapper<int8_t> values_2{{95, 50, 77}, {1, 1, 0}}; fixed_width_column_wrapper<size_type> expect{2, 11, 6}; std::vector<std::unique_ptr<cudf::column>> columns; columns.push_back(column_0.release()); columns.push_back(column_1.release()); columns.push_back(column_2.release()); std::vector<std::unique_ptr<cudf::column>> values; values.push_back(values_0.release()); values.push_back(values_1.release()); values.push_back(values_2.release()); cudf::table input_table(std::move(columns)); cudf::table values_table(std::move(values)); std::vector<cudf::order> order_flags{ {cudf::order::ASCENDING, cudf::order::ASCENDING, cudf::order::ASCENDING}}; std::vector<cudf::null_order> null_order_flags{ {cudf::null_order::AFTER, cudf::null_order::AFTER, cudf::null_order::AFTER}}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::upper_bound(input_table, values_table, order_flags, null_order_flags)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, contains_true) { using element_type = int64_t; bool expect = true; bool result = false; fixed_width_column_wrapper<element_type> column{0, 1, 17, 19, 23, 29, 71}; numeric_scalar<element_type> scalar{23}; result = cudf::contains(column, scalar); ASSERT_EQ(result, expect); } TEST_F(SearchTest, contains_false) { using element_type = int64_t; bool expect = false; bool result = false; fixed_width_column_wrapper<element_type> column{0, 1, 17, 19, 23, 29, 71}; numeric_scalar<element_type> scalar{24}; result = cudf::contains(column, scalar); ASSERT_EQ(result, expect); } TEST_F(SearchTest, contains_empty_value) { using element_type = int64_t; bool expect = false; bool result = false; fixed_width_column_wrapper<element_type> column{0, 1, 17, 19, 23, 29, 71}; numeric_scalar<element_type> scalar{23, false}; result = cudf::contains(column, scalar); ASSERT_EQ(result, expect); } TEST_F(SearchTest, contains_empty_column) { using element_type = int64_t; bool expect = false; bool result = false; fixed_width_column_wrapper<element_type> column{}; numeric_scalar<element_type> scalar{24}; result = cudf::contains(column, scalar); ASSERT_EQ(result, expect); } TEST_F(SearchTest, contains_nullable_column_true) { using element_type = int64_t; bool result = false; bool expect = true; fixed_width_column_wrapper<element_type> column{{0, 1, 17, 19, 23, 29, 71}, {0, 0, 1, 1, 1, 1, 1}}; numeric_scalar<element_type> scalar{23}; result = cudf::contains(column, scalar); ASSERT_EQ(result, expect); } TEST_F(SearchTest, contains_nullable_column_false) { using element_type = int64_t; bool result = false; bool expect = false; fixed_width_column_wrapper<element_type> column{{0, 1, 17, 19, 23, 29, 71}, {0, 0, 1, 1, 0, 1, 1}}; numeric_scalar<element_type> scalar{23}; result = cudf::contains(column, scalar); ASSERT_EQ(result, expect); } TEST_F(SearchTest, empty_table_string) { std::vector<char const*> h_col_strings{}; std::vector<char const*> h_val_strings{"0", "10", "11", "30", "32", "40", "47", "50", "7", "90"}; cudf::test::strings_column_wrapper column( h_col_strings.begin(), h_col_strings.end(), thrust::make_transform_iterator(h_col_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values( h_val_strings.begin(), h_val_strings.end(), thrust::make_transform_iterator(h_val_strings.begin(), [](auto str) { return str != nullptr; })); fixed_width_column_wrapper<size_type> expect{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::lower_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::ASCENDING}, {cudf::null_order::BEFORE})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, empty_values_string) { std::vector<char const*> h_col_strings{"10", "20", "30", "40", "50"}; std::vector<char const*> h_val_strings{}; cudf::test::strings_column_wrapper column( h_col_strings.begin(), h_col_strings.end(), thrust::make_transform_iterator(h_col_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values( h_val_strings.begin(), h_val_strings.end(), thrust::make_transform_iterator(h_val_strings.begin(), [](auto str) { return str != nullptr; })); fixed_width_column_wrapper<size_type> expect{}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::lower_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::ASCENDING}, {cudf::null_order::BEFORE})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, non_null_column__find_first_string) { std::vector<char const*> h_col_strings{"10", "20", "30", "40", "50"}; std::vector<char const*> h_val_strings{ "00", "07", "10", "11", "30", "32", "40", "47", "50", "90"}; cudf::test::strings_column_wrapper column( h_col_strings.begin(), h_col_strings.end(), thrust::make_transform_iterator(h_col_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values( h_val_strings.begin(), h_val_strings.end(), thrust::make_transform_iterator(h_val_strings.begin(), [](auto str) { return str != nullptr; })); fixed_width_column_wrapper<size_type> expect{0, 0, 0, 1, 2, 3, 3, 4, 4, 5}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::lower_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::ASCENDING}, {cudf::null_order::BEFORE})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, non_null_column__find_last_string) { std::vector<char const*> h_col_strings{"10", "20", "30", "40", "50"}; std::vector<char const*> h_val_strings{ "00", "07", "10", "11", "30", "32", "40", "47", "50", "90"}; cudf::test::strings_column_wrapper column( h_col_strings.begin(), h_col_strings.end(), thrust::make_transform_iterator(h_col_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values( h_val_strings.begin(), h_val_strings.end(), thrust::make_transform_iterator(h_val_strings.begin(), [](auto str) { return str != nullptr; })); fixed_width_column_wrapper<size_type> expect{0, 0, 1, 1, 3, 3, 4, 4, 5, 5}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::upper_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::ASCENDING}, {cudf::null_order::BEFORE})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, non_null_column_desc__find_first_string) { std::vector<char const*> h_col_strings{"50", "40", "30", "20", "10"}; std::vector<char const*> h_val_strings{ "00", "07", "10", "11", "30", "32", "40", "47", "50", "90"}; cudf::test::strings_column_wrapper column( h_col_strings.begin(), h_col_strings.end(), thrust::make_transform_iterator(h_col_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values( h_val_strings.begin(), h_val_strings.end(), thrust::make_transform_iterator(h_val_strings.begin(), [](auto str) { return str != nullptr; })); fixed_width_column_wrapper<size_type> expect{5, 5, 4, 4, 2, 2, 1, 1, 0, 0}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::lower_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::DESCENDING}, {cudf::null_order::BEFORE})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, non_null_column_desc__find_last_string) { std::vector<char const*> h_col_strings{"50", "40", "30", "20", "10"}; std::vector<char const*> h_val_strings{ "00", "07", "10", "11", "30", "32", "40", "47", "50", "90"}; cudf::test::strings_column_wrapper column( h_col_strings.begin(), h_col_strings.end(), thrust::make_transform_iterator(h_col_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values( h_val_strings.begin(), h_val_strings.end(), thrust::make_transform_iterator(h_val_strings.begin(), [](auto str) { return str != nullptr; })); fixed_width_column_wrapper<size_type> expect{5, 5, 5, 4, 3, 2, 2, 1, 1, 0}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::upper_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::DESCENDING}, {cudf::null_order::BEFORE})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, nullable_column__find_last__nulls_as_smallest_string) { std::vector<char const*> h_col_strings{nullptr, nullptr, "10", "20", "30", "40", "50"}; std::vector<char const*> h_val_strings{ nullptr, "08", "10", "11", "30", "32", "40", "47", "50", "90"}; cudf::test::strings_column_wrapper column( h_col_strings.begin(), h_col_strings.end(), thrust::make_transform_iterator(h_col_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values( h_val_strings.begin(), h_val_strings.end(), thrust::make_transform_iterator(h_val_strings.begin(), [](auto str) { return str != nullptr; })); fixed_width_column_wrapper<size_type> expect{2, 2, 3, 3, 5, 5, 6, 6, 7, 7}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::upper_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::ASCENDING}, {cudf::null_order::BEFORE})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, nullable_column__find_first__nulls_as_smallest_string) { std::vector<char const*> h_col_strings{nullptr, nullptr, "10", "20", "30", "40", "50"}; std::vector<char const*> h_val_strings{ nullptr, "08", "10", "11", "30", "32", "40", "47", "50", "90"}; cudf::test::strings_column_wrapper column( h_col_strings.begin(), h_col_strings.end(), thrust::make_transform_iterator(h_col_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values( h_val_strings.begin(), h_val_strings.end(), thrust::make_transform_iterator(h_val_strings.begin(), [](auto str) { return str != nullptr; })); fixed_width_column_wrapper<size_type> expect{0, 2, 2, 3, 4, 5, 5, 6, 6, 7}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::lower_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::ASCENDING}, {cudf::null_order::BEFORE})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, nullable_column__find_last__nulls_as_largest_string) { std::vector<char const*> h_col_strings{"10", "20", "30", "40", "50", nullptr, nullptr}; std::vector<char const*> h_val_strings{ "08", "10", "11", "30", "32", "40", "47", "50", "90", nullptr}; cudf::test::strings_column_wrapper column( h_col_strings.begin(), h_col_strings.end(), thrust::make_transform_iterator(h_col_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values( h_val_strings.begin(), h_val_strings.end(), thrust::make_transform_iterator(h_val_strings.begin(), [](auto str) { return str != nullptr; })); fixed_width_column_wrapper<size_type> expect{0, 1, 1, 3, 3, 4, 4, 5, 5, 7}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::upper_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::ASCENDING}, {cudf::null_order::AFTER})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, non_null_column__nullable_values__find_last__nulls_as_largest_string) { cudf::test::strings_column_wrapper column({"N", "N", "N", "N", "Y", "Y", "Y", "Y"}, {1, 1, 1, 1, 1, 1, 1, 1}); cudf::test::strings_column_wrapper values({"Y", "Z", "N"}, {1, 0, 1}); fixed_width_column_wrapper<size_type> expect{8, 8, 4}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::upper_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::ASCENDING}, {cudf::null_order::AFTER})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, nullable_column__find_first__nulls_as_largest_string) { std::vector<char const*> h_col_strings{"10", "20", "30", "40", "50", nullptr, nullptr}; std::vector<char const*> h_val_strings{ "08", "10", "11", "30", "32", "40", "47", "50", "90", nullptr}; cudf::test::strings_column_wrapper column( h_col_strings.begin(), h_col_strings.end(), thrust::make_transform_iterator(h_col_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values( h_val_strings.begin(), h_val_strings.end(), thrust::make_transform_iterator(h_val_strings.begin(), [](auto str) { return str != nullptr; })); fixed_width_column_wrapper<size_type> expect{0, 0, 1, 2, 3, 3, 4, 4, 5, 5}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::lower_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::ASCENDING}, {cudf::null_order::AFTER})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, table__find_first_string) { std::vector<char const*> h_col_0_strings{"10", "20", "20", "20", "20", "20", "50"}; std::vector<char const*> h_col_2_strings{"90", "77", "78", "61", "62", "63", "41"}; std::vector<char const*> h_val_0_strings{"0", "0", "0", "0", "10", "10", "10", "10", "10", "10", "10", "10", "11", "20", "20", "20", "20", "20", "20", "20", "20", "20", "20", "20", "30", "50", "60"}; std::vector<char const*> h_val_2_strings{"0", "91", "0", "91", "0", "79", "90", "91", "77", "80", "90", "91", "91", "00", "76", "77", "78", "30", "65", "77", "78", "80", "62", "78", "64", "41", "20"}; fixed_width_column_wrapper<float> column_1{5.0, .5, .5, .7, .7, .7, .7}; fixed_width_column_wrapper<float> values_1{0., 0., 6., 5., 0., 5., 5., 5., 5., 6., 6., 6., 9., 0., .5, .5, .5, .5, .6, .6, .6, .7, .7, .7, .7, .7, .5}; fixed_width_column_wrapper<size_type> expect{0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 2, 1, 3, 3, 3, 6, 4, 6, 6, 6, 7}; cudf::test::strings_column_wrapper column_0( h_col_0_strings.begin(), h_col_0_strings.end(), thrust::make_transform_iterator(h_col_0_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper column_2( h_col_2_strings.begin(), h_col_2_strings.end(), thrust::make_transform_iterator(h_col_2_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values_0( h_val_0_strings.begin(), h_val_0_strings.end(), thrust::make_transform_iterator(h_val_0_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values_2( h_val_2_strings.begin(), h_val_2_strings.end(), thrust::make_transform_iterator(h_val_2_strings.begin(), [](auto str) { return str != nullptr; })); std::vector<std::unique_ptr<cudf::column>> columns; columns.push_back(column_0.release()); columns.push_back(column_1.release()); columns.push_back(column_2.release()); std::vector<std::unique_ptr<cudf::column>> values; values.push_back(values_0.release()); values.push_back(values_1.release()); values.push_back(values_2.release()); cudf::table input_table(std::move(columns)); cudf::table values_table(std::move(values)); std::vector<cudf::order> order_flags{ {cudf::order::ASCENDING, cudf::order::ASCENDING, cudf::order::ASCENDING}}; std::vector<cudf::null_order> null_order_flags{ {cudf::null_order::BEFORE, cudf::null_order::BEFORE, cudf::null_order::BEFORE}}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::lower_bound(input_table, values_table, order_flags, null_order_flags)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, table__find_last_string) { std::vector<char const*> h_col_0_strings{"10", "20", "20", "20", "20", "20", "50"}; std::vector<char const*> h_col_2_strings{"90", "77", "78", "61", "62", "63", "41"}; std::vector<char const*> h_val_0_strings{"0", "0", "0", "0", "10", "10", "10", "10", "10", "10", "10", "10", "11", "20", "20", "20", "20", "20", "20", "20", "20", "20", "20", "20", "30", "50", "60"}; std::vector<char const*> h_val_2_strings{"0", "91", "0", "91", "0", "79", "90", "91", "77", "80", "90", "91", "91", "00", "76", "77", "78", "30", "65", "77", "78", "80", "62", "78", "64", "41", "20"}; fixed_width_column_wrapper<float> column_1{5.0, .5, .5, .7, .7, .7, .7}; fixed_width_column_wrapper<float> values_1{0., 0., 6., 5., 0., 5., 5., 5., 5., 6., 6., 6., 9., 0., .5, .5, .5, .5, .6, .6, .6, .7, .7, .7, .7, .7, .5}; fixed_width_column_wrapper<size_type> expect{0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 2, 3, 1, 3, 3, 3, 6, 5, 6, 6, 7, 7}; cudf::test::strings_column_wrapper column_0( h_col_0_strings.begin(), h_col_0_strings.end(), thrust::make_transform_iterator(h_col_0_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper column_2( h_col_2_strings.begin(), h_col_2_strings.end(), thrust::make_transform_iterator(h_col_2_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values_0( h_val_0_strings.begin(), h_val_0_strings.end(), thrust::make_transform_iterator(h_val_0_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values_2( h_val_2_strings.begin(), h_val_2_strings.end(), thrust::make_transform_iterator(h_val_2_strings.begin(), [](auto str) { return str != nullptr; })); std::vector<std::unique_ptr<cudf::column>> columns; columns.push_back(column_0.release()); columns.push_back(column_1.release()); columns.push_back(column_2.release()); std::vector<std::unique_ptr<cudf::column>> values; values.push_back(values_0.release()); values.push_back(values_1.release()); values.push_back(values_2.release()); cudf::table input_table(std::move(columns)); cudf::table values_table(std::move(values)); std::vector<cudf::order> order_flags{ {cudf::order::ASCENDING, cudf::order::ASCENDING, cudf::order::ASCENDING}}; std::vector<cudf::null_order> null_order_flags{ {cudf::null_order::BEFORE, cudf::null_order::BEFORE, cudf::null_order::BEFORE}}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::upper_bound(input_table, values_table, order_flags, null_order_flags)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, table_partial_desc__find_first_string) { std::vector<char const*> h_col_0_strings{"50", "20", "20", "20", "20", "20", "10"}; std::vector<char const*> h_col_2_strings{"41", "78", "77", "63", "62", "61", "90"}; std::vector<char const*> h_val_0_strings{"0", "0", "0", "0", "10", "10", "10", "10", "10", "10", "10", "10", "11", "20", "20", "20", "20", "20", "20", "20", "20", "20", "20", "20", "30", "50", "60"}; std::vector<char const*> h_val_2_strings{"0", "91", "0", "91", "0", "79", "90", "91", "77", "80", "90", "91", "91", "00", "76", "77", "78", "30", "65", "77", "78", "80", "62", "78", "64", "41", "20"}; fixed_width_column_wrapper<float> column_1{.7, .5, .5, .7, .7, .7, 5.0}; fixed_width_column_wrapper<float> values_1{0., 0., 6., 5., 0., 5., 5., 5., 5., 6., 6., 6., 9., 0., .5, .5, .5, .5, .6, .6, .6, .7, .7, .7, .7, .7, .5}; fixed_width_column_wrapper<size_type> expect{7, 7, 7, 7, 6, 7, 6, 6, 7, 7, 7, 7, 6, 1, 3, 2, 1, 3, 3, 3, 3, 3, 4, 3, 1, 0, 0}; cudf::test::strings_column_wrapper column_0( h_col_0_strings.begin(), h_col_0_strings.end(), thrust::make_transform_iterator(h_col_0_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper column_2( h_col_2_strings.begin(), h_col_2_strings.end(), thrust::make_transform_iterator(h_col_2_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values_0( h_val_0_strings.begin(), h_val_0_strings.end(), thrust::make_transform_iterator(h_val_0_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values_2( h_val_2_strings.begin(), h_val_2_strings.end(), thrust::make_transform_iterator(h_val_2_strings.begin(), [](auto str) { return str != nullptr; })); std::vector<std::unique_ptr<cudf::column>> columns; columns.push_back(column_0.release()); columns.push_back(column_1.release()); columns.push_back(column_2.release()); std::vector<std::unique_ptr<cudf::column>> values; values.push_back(values_0.release()); values.push_back(values_1.release()); values.push_back(values_2.release()); cudf::table input_table(std::move(columns)); cudf::table values_table(std::move(values)); std::vector<cudf::order> order_flags{ {cudf::order::DESCENDING, cudf::order::ASCENDING, cudf::order::DESCENDING}}; std::vector<cudf::null_order> null_order_flags{ {cudf::null_order::BEFORE, cudf::null_order::BEFORE, cudf::null_order::BEFORE}}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::lower_bound(input_table, values_table, order_flags, null_order_flags)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, table_partial_desc__find_last_string) { std::vector<char const*> h_col_0_strings{"50", "20", "20", "20", "20", "20", "10"}; std::vector<char const*> h_col_2_strings{"41", "78", "77", "63", "62", "61", "90"}; std::vector<char const*> h_val_0_strings{"0", "0", "0", "0", "10", "10", "10", "10", "10", "10", "10", "10", "11", "20", "20", "20", "20", "20", "20", "20", "20", "20", "20", "20", "30", "50", "60"}; std::vector<char const*> h_val_2_strings{"0", "91", "0", "91", "0", "79", "90", "91", "77", "80", "90", "91", "91", "00", "76", "77", "78", "30", "65", "77", "78", "80", "62", "78", "64", "41", "20"}; fixed_width_column_wrapper<float> column_1{.7, .5, .5, .7, .7, .7, 5.0}; fixed_width_column_wrapper<float> values_1{0., 0., 6., 5., 0., 5., 5., 5., 5., 6., 6., 6., 9., 0., .5, .5, .5, .5, .6, .6, .6, .7, .7, .7, .7, .7, .5}; fixed_width_column_wrapper<size_type> expect{7, 7, 7, 7, 6, 7, 7, 6, 7, 7, 7, 7, 6, 1, 3, 3, 2, 3, 3, 3, 3, 3, 5, 3, 1, 1, 0}; cudf::test::strings_column_wrapper column_0( h_col_0_strings.begin(), h_col_0_strings.end(), thrust::make_transform_iterator(h_col_0_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper column_2( h_col_2_strings.begin(), h_col_2_strings.end(), thrust::make_transform_iterator(h_col_2_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values_0( h_val_0_strings.begin(), h_val_0_strings.end(), thrust::make_transform_iterator(h_val_0_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values_2( h_val_2_strings.begin(), h_val_2_strings.end(), thrust::make_transform_iterator(h_val_2_strings.begin(), [](auto str) { return str != nullptr; })); std::vector<std::unique_ptr<cudf::column>> columns; columns.push_back(column_0.release()); columns.push_back(column_1.release()); columns.push_back(column_2.release()); std::vector<std::unique_ptr<cudf::column>> values; values.push_back(values_0.release()); values.push_back(values_1.release()); values.push_back(values_2.release()); cudf::table input_table(std::move(columns)); cudf::table values_table(std::move(values)); std::vector<cudf::order> order_flags{ {cudf::order::DESCENDING, cudf::order::ASCENDING, cudf::order::DESCENDING}}; std::vector<cudf::null_order> null_order_flags{ {cudf::null_order::BEFORE, cudf::null_order::BEFORE, cudf::null_order::BEFORE}}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::upper_bound(input_table, values_table, order_flags, null_order_flags)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, table__find_first__nulls_as_smallest_string) { std::vector<char const*> h_col_0_strings{ nullptr, "10", "10", "20", "20", "20", "20", "20", "20", "20", "50"}; std::vector<char const*> h_col_2_strings{ "50", "95", "90", nullptr, nullptr, "77", "78", "61", "62", "63", "41"}; std::vector<char const*> h_val_0_strings{"10", nullptr, "20"}; std::vector<char const*> h_val_2_strings{"95", "50", nullptr}; fixed_width_column_wrapper<float> column_1{{.5, 6.0, 5.0, .5, .5, .5, .5, .7, .7, .7, .7}, {1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1}}; fixed_width_column_wrapper<float> values_1{{6., .5, .5}, {0, 1, 1}}; fixed_width_column_wrapper<size_type> expect{1, 0, 3}; cudf::test::strings_column_wrapper column_0( h_col_0_strings.begin(), h_col_0_strings.end(), thrust::make_transform_iterator(h_col_0_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper column_2( h_col_2_strings.begin(), h_col_2_strings.end(), thrust::make_transform_iterator(h_col_2_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values_0( h_val_0_strings.begin(), h_val_0_strings.end(), thrust::make_transform_iterator(h_val_0_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values_2( h_val_2_strings.begin(), h_val_2_strings.end(), thrust::make_transform_iterator(h_val_2_strings.begin(), [](auto str) { return str != nullptr; })); std::vector<std::unique_ptr<cudf::column>> columns; columns.push_back(column_0.release()); columns.push_back(column_1.release()); columns.push_back(column_2.release()); std::vector<std::unique_ptr<cudf::column>> values; values.push_back(values_0.release()); values.push_back(values_1.release()); values.push_back(values_2.release()); cudf::table input_table(std::move(columns)); cudf::table values_table(std::move(values)); std::vector<cudf::order> order_flags{ {cudf::order::ASCENDING, cudf::order::ASCENDING, cudf::order::ASCENDING}}; std::vector<cudf::null_order> null_order_flags{ {cudf::null_order::BEFORE, cudf::null_order::BEFORE, cudf::null_order::BEFORE}}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::lower_bound(input_table, values_table, order_flags, null_order_flags)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, table__find_last__nulls_as_smallest_string) { std::vector<char const*> h_col_0_strings{ nullptr, "10", "10", "20", "20", "20", "20", "20", "20", "20", "50"}; std::vector<char const*> h_col_2_strings{ "50", "90", "95", nullptr, nullptr, "77", "78", "61", "62", "63", "41"}; std::vector<char const*> h_val_0_strings{"10", nullptr, "20"}; std::vector<char const*> h_val_2_strings{"95", "50", nullptr}; fixed_width_column_wrapper<float> column_1{{.5, 6.0, 5.0, .5, .5, .5, .5, .7, .7, .7, .7}, {1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1}}; fixed_width_column_wrapper<float> values_1{{6., .5, .5}, {0, 1, 1}}; fixed_width_column_wrapper<size_type> expect{2, 1, 5}; cudf::test::strings_column_wrapper column_0( h_col_0_strings.begin(), h_col_0_strings.end(), thrust::make_transform_iterator(h_col_0_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper column_2( h_col_2_strings.begin(), h_col_2_strings.end(), thrust::make_transform_iterator(h_col_2_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values_0( h_val_0_strings.begin(), h_val_0_strings.end(), thrust::make_transform_iterator(h_val_0_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values_2( h_val_2_strings.begin(), h_val_2_strings.end(), thrust::make_transform_iterator(h_val_2_strings.begin(), [](auto str) { return str != nullptr; })); std::vector<std::unique_ptr<cudf::column>> columns; columns.push_back(column_0.release()); columns.push_back(column_1.release()); columns.push_back(column_2.release()); std::vector<std::unique_ptr<cudf::column>> values; values.push_back(values_0.release()); values.push_back(values_1.release()); values.push_back(values_2.release()); cudf::table input_table(std::move(columns)); cudf::table values_table(std::move(values)); std::vector<cudf::order> order_flags{ {cudf::order::ASCENDING, cudf::order::ASCENDING, cudf::order::ASCENDING}}; std::vector<cudf::null_order> null_order_flags{ {cudf::null_order::BEFORE, cudf::null_order::BEFORE, cudf::null_order::BEFORE}}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::upper_bound(input_table, values_table, order_flags, null_order_flags)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, table__find_first__nulls_as_largest_string) { std::vector<char const*> h_col_0_strings{ "10", "10", "20", "20", "20", "20", "20", "20", "20", "50", nullptr}; std::vector<char const*> h_col_2_strings{ "90", "95", "77", "78", nullptr, nullptr, "61", "62", "63", "41", "50"}; std::vector<char const*> h_val_0_strings{"10", nullptr, "20"}; std::vector<char const*> h_val_2_strings{"95", "50", nullptr}; fixed_width_column_wrapper<float> column_1{{5.0, 6.0, .5, .5, .5, .5, .7, .7, .7, .7, .5}, {1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1}}; fixed_width_column_wrapper<float> values_1{{6., .5, .5}, {0, 1, 1}}; fixed_width_column_wrapper<size_type> expect{1, 10, 4}; cudf::test::strings_column_wrapper column_0( h_col_0_strings.begin(), h_col_0_strings.end(), thrust::make_transform_iterator(h_col_0_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper column_2( h_col_2_strings.begin(), h_col_2_strings.end(), thrust::make_transform_iterator(h_col_2_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values_0( h_val_0_strings.begin(), h_val_0_strings.end(), thrust::make_transform_iterator(h_val_0_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values_2( h_val_2_strings.begin(), h_val_2_strings.end(), thrust::make_transform_iterator(h_val_2_strings.begin(), [](auto str) { return str != nullptr; })); std::vector<std::unique_ptr<cudf::column>> columns; columns.push_back(column_0.release()); columns.push_back(column_1.release()); columns.push_back(column_2.release()); std::vector<std::unique_ptr<cudf::column>> values; values.push_back(values_0.release()); values.push_back(values_1.release()); values.push_back(values_2.release()); cudf::table input_table(std::move(columns)); cudf::table values_table(std::move(values)); std::vector<cudf::order> order_flags{ {cudf::order::ASCENDING, cudf::order::ASCENDING, cudf::order::ASCENDING}}; std::vector<cudf::null_order> null_order_flags{ {cudf::null_order::AFTER, cudf::null_order::AFTER, cudf::null_order::AFTER}}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::lower_bound(input_table, values_table, order_flags, null_order_flags)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, table__find_last__nulls_as_largest_string) { std::vector<char const*> h_col_0_strings{ "10", "10", "20", "20", "20", "20", "20", "20", "20", "50", nullptr}; std::vector<char const*> h_col_2_strings{ "90", "95", "77", "78", nullptr, nullptr, "61", "62", "63", "41", "50"}; std::vector<char const*> h_val_0_strings{"10", nullptr, "20"}; std::vector<char const*> h_val_2_strings{"95", "50", nullptr}; fixed_width_column_wrapper<float> column_1{{5.0, 6.0, .5, .5, .5, .5, .7, .7, .7, .7, .5}, {1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1}}; fixed_width_column_wrapper<float> values_1{{6., .5, .5}, {0, 1, 1}}; fixed_width_column_wrapper<size_type> expect{2, 11, 6}; cudf::test::strings_column_wrapper column_0( h_col_0_strings.begin(), h_col_0_strings.end(), thrust::make_transform_iterator(h_col_0_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper column_2( h_col_2_strings.begin(), h_col_2_strings.end(), thrust::make_transform_iterator(h_col_2_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values_0( h_val_0_strings.begin(), h_val_0_strings.end(), thrust::make_transform_iterator(h_val_0_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper values_2( h_val_2_strings.begin(), h_val_2_strings.end(), thrust::make_transform_iterator(h_val_2_strings.begin(), [](auto str) { return str != nullptr; })); std::vector<std::unique_ptr<cudf::column>> columns; columns.push_back(column_0.release()); columns.push_back(column_1.release()); columns.push_back(column_2.release()); std::vector<std::unique_ptr<cudf::column>> values; values.push_back(values_0.release()); values.push_back(values_1.release()); values.push_back(values_2.release()); cudf::table input_table(std::move(columns)); cudf::table values_table(std::move(values)); std::vector<cudf::order> order_flags{ {cudf::order::ASCENDING, cudf::order::ASCENDING, cudf::order::ASCENDING}}; std::vector<cudf::null_order> null_order_flags{ {cudf::null_order::AFTER, cudf::null_order::AFTER, cudf::null_order::AFTER}}; std::unique_ptr<cudf::column> result{}; EXPECT_NO_THROW(result = cudf::upper_bound(input_table, values_table, order_flags, null_order_flags)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, contains_true_string) { std::vector<char const*> h_col_strings{"00", "01", "17", "19", "23", "29", "71"}; string_scalar scalar{"23"}; cudf::test::strings_column_wrapper column( h_col_strings.begin(), h_col_strings.end(), thrust::make_transform_iterator(h_col_strings.begin(), [](auto str) { return str != nullptr; })); bool expect = true; bool result = false; result = cudf::contains(column, scalar); ASSERT_EQ(result, expect); } TEST_F(SearchTest, contains_false_string) { std::vector<char const*> h_col_strings{"0", "1", "17", "19", "23", "29", "71"}; string_scalar scalar{"24"}; cudf::test::strings_column_wrapper column( h_col_strings.begin(), h_col_strings.end(), thrust::make_transform_iterator(h_col_strings.begin(), [](auto str) { return str != nullptr; })); bool expect = false; bool result = false; result = cudf::contains(column, scalar); ASSERT_EQ(result, expect); } TEST_F(SearchTest, contains_empty_value_string) { std::vector<char const*> h_col_strings{"0", "1", "17", "19", "23", "29", "71"}; string_scalar scalar{"23", false}; cudf::test::strings_column_wrapper column( h_col_strings.begin(), h_col_strings.end(), thrust::make_transform_iterator(h_col_strings.begin(), [](auto str) { return str != nullptr; })); bool expect = false; bool result = false; result = cudf::contains(column, scalar); ASSERT_EQ(result, expect); } TEST_F(SearchTest, contains_empty_column_string) { std::vector<char const*> h_col_strings{}; string_scalar scalar{"24"}; cudf::test::strings_column_wrapper column( h_col_strings.begin(), h_col_strings.end(), thrust::make_transform_iterator(h_col_strings.begin(), [](auto str) { return str != nullptr; })); bool expect = false; bool result = false; result = cudf::contains(column, scalar); ASSERT_EQ(result, expect); } TEST_F(SearchTest, contains_nullable_column_true_string) { std::vector<char const*> h_col_strings{nullptr, nullptr, "17", "19", "23", "29", "71"}; string_scalar scalar{"23"}; cudf::test::strings_column_wrapper column( h_col_strings.begin(), h_col_strings.end(), thrust::make_transform_iterator(h_col_strings.begin(), [](auto str) { return str != nullptr; })); bool result = false; bool expect = true; result = cudf::contains(column, scalar); ASSERT_EQ(result, expect); } TEST_F(SearchTest, contains_nullable_column_false_string) { std::vector<char const*> h_col_strings{nullptr, nullptr, "17", "19", nullptr, "29", "71"}; string_scalar scalar{"23"}; cudf::test::strings_column_wrapper column( h_col_strings.begin(), h_col_strings.end(), thrust::make_transform_iterator(h_col_strings.begin(), [](auto str) { return str != nullptr; })); bool result = false; bool expect = false; result = cudf::contains(column, scalar); ASSERT_EQ(result, expect); } TEST_F(SearchTest, multi_contains_some) { using element_type = int64_t; fixed_width_column_wrapper<element_type> haystack{0, 1, 17, 19, 23, 29, 71}; fixed_width_column_wrapper<element_type> needles{17, 19, 45, 72}; fixed_width_column_wrapper<bool> expect{1, 1, 0, 0}; auto result = cudf::contains(haystack, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, multi_contains_none) { using element_type = int64_t; fixed_width_column_wrapper<element_type> haystack{0, 1, 17, 19, 23, 29, 71}; fixed_width_column_wrapper<element_type> needles{2, 3}; fixed_width_column_wrapper<bool> expect{0, 0}; auto result = cudf::contains(haystack, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, multi_contains_some_string) { std::vector<char const*> h_haystack_strings{"0", "1", "17", "19", "23", "29", "71"}; std::vector<char const*> h_needles_strings{"17", "19", "45", "72"}; cudf::test::strings_column_wrapper haystack(h_haystack_strings.begin(), h_haystack_strings.end()); cudf::test::strings_column_wrapper needles(h_needles_strings.begin(), h_needles_strings.end()); fixed_width_column_wrapper<bool> expect{1, 1, 0, 0}; auto result = cudf::contains(haystack, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, multi_contains_none_string) { std::vector<char const*> h_haystack_strings{"0", "1", "17", "19", "23", "29", "71"}; std::vector<char const*> h_needles_strings{"2", "3"}; cudf::test::strings_column_wrapper haystack(h_haystack_strings.begin(), h_haystack_strings.end()); cudf::test::strings_column_wrapper needles(h_needles_strings.begin(), h_needles_strings.end()); fixed_width_column_wrapper<bool> expect{0, 0}; auto result = cudf::contains(haystack, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, multi_contains_some_with_nulls) { using element_type = int64_t; fixed_width_column_wrapper<element_type> haystack{{0, 1, 17, 19, 23, 29, 71}, {1, 1, 0, 1, 1, 1, 1}}; fixed_width_column_wrapper<element_type> needles{{17, 19, 23, 72}, {1, 0, 1, 1}}; fixed_width_column_wrapper<bool> expect{{0, 0, 1, 0}, {1, 0, 1, 1}}; auto result = cudf::contains(haystack, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, multi_contains_none_with_nulls) { using element_type = int64_t; fixed_width_column_wrapper<element_type> haystack{{0, 1, 17, 19, 23, 29, 71}, {1, 1, 0, 1, 1, 1, 1}}; fixed_width_column_wrapper<element_type> needles{{17, 19, 24, 72}, {1, 0, 1, 1}}; fixed_width_column_wrapper<bool> expect{{0, 0, 0, 0}, {1, 0, 1, 1}}; auto result = cudf::contains(haystack, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, multi_contains_some_string_with_nulls) { std::vector<char const*> h_haystack_strings{"0", "1", nullptr, "19", "23", "29", "71"}; std::vector<char const*> h_needles_strings{"17", "23", nullptr, "72"}; fixed_width_column_wrapper<bool> expect{{0, 1, 0, 0}, {1, 1, 0, 1}}; cudf::test::strings_column_wrapper haystack( h_haystack_strings.begin(), h_haystack_strings.end(), thrust::make_transform_iterator(h_haystack_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper needles( h_needles_strings.begin(), h_needles_strings.end(), thrust::make_transform_iterator(h_needles_strings.begin(), [](auto str) { return str != nullptr; })); auto result = cudf::contains(haystack, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, multi_contains_none_string_with_nulls) { std::vector<char const*> h_haystack_strings{"0", "1", nullptr, "19", "23", "29", "71"}; std::vector<char const*> h_needles_strings{"2", nullptr}; fixed_width_column_wrapper<bool> expect{{0, 0}, {1, 0}}; cudf::test::strings_column_wrapper haystack( h_haystack_strings.begin(), h_haystack_strings.end(), thrust::make_transform_iterator(h_haystack_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper needles( h_needles_strings.begin(), h_needles_strings.end(), thrust::make_transform_iterator(h_needles_strings.begin(), [](auto str) { return str != nullptr; })); auto result = cudf::contains(haystack, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, multi_contains_empty_column) { using element_type = int64_t; fixed_width_column_wrapper<element_type> haystack{}; fixed_width_column_wrapper<element_type> needles{2, 3}; fixed_width_column_wrapper<bool> expect{0, 0}; auto result = cudf::contains(haystack, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, multi_contains_empty_column_string) { std::vector<char const*> h_haystack_strings{}; std::vector<char const*> h_needles_strings{"17", "19", "45", "72"}; cudf::test::strings_column_wrapper haystack(h_haystack_strings.begin(), h_haystack_strings.end()); cudf::test::strings_column_wrapper needles(h_needles_strings.begin(), h_needles_strings.end()); fixed_width_column_wrapper<bool> expect{0, 0, 0, 0}; auto result = cudf::contains(haystack, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, multi_contains_empty_input_set) { using element_type = int64_t; fixed_width_column_wrapper<element_type> haystack{0, 1, 17, 19, 23, 29, 71}; fixed_width_column_wrapper<element_type> needles{}; fixed_width_column_wrapper<bool> expect{}; auto result = cudf::contains(haystack, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(SearchTest, multi_contains_empty_input_set_string) { std::vector<char const*> h_haystack_strings{"0", "1", "17", "19", "23", "29", "71"}; std::vector<char const*> h_needles_strings{}; cudf::test::strings_column_wrapper haystack(h_haystack_strings.begin(), h_haystack_strings.end()); cudf::test::strings_column_wrapper needles(h_needles_strings.begin(), h_needles_strings.end()); fixed_width_column_wrapper<bool> expect{}; auto result = cudf::contains(haystack, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } template <typename T> struct FixedPointTestAllReps : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(FixedPointTestAllReps, cudf::test::FixedPointTypes); TYPED_TEST(FixedPointTestAllReps, FixedPointLowerBound) { using namespace numeric; using decimalXX = TypeParam; auto vec = std::vector<decimalXX>(1000); std::iota(std::begin(vec), std::end(vec), decimalXX{}); auto const values = cudf::test::fixed_width_column_wrapper<decimalXX>{decimalXX{200, scale_type{0}}, decimalXX{400, scale_type{0}}, decimalXX{600, scale_type{0}}, decimalXX{800, scale_type{0}}}; auto const expect = cudf::test::fixed_width_column_wrapper<cudf::size_type>{200, 400, 600, 800}; auto const column = cudf::test::fixed_width_column_wrapper<decimalXX>(vec.begin(), vec.end()); auto result = cudf::lower_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::ASCENDING}, {cudf::null_order::BEFORE}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TYPED_TEST(FixedPointTestAllReps, FixedPointUpperBound) { using namespace numeric; using decimalXX = TypeParam; auto vec = std::vector<decimalXX>(1000); std::iota(std::begin(vec), std::end(vec), decimalXX{}); auto const values = cudf::test::fixed_width_column_wrapper<decimalXX>{decimalXX{200, scale_type{0}}, decimalXX{400, scale_type{0}}, decimalXX{600, scale_type{0}}, decimalXX{800, scale_type{0}}}; auto const expect = cudf::test::fixed_width_column_wrapper<cudf::size_type>{201, 401, 601, 801}; auto const column = cudf::test::fixed_width_column_wrapper<decimalXX>(vec.begin(), vec.end()); auto result = cudf::upper_bound({cudf::table_view{{column}}}, {cudf::table_view{{values}}}, {cudf::order::ASCENDING}, {cudf::null_order::BEFORE}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } CUDF_TEST_PROGRAM_MAIN()
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/search/search_dictionary_test.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/search.hpp> struct DictionarySearchTest : public cudf::test::BaseFixture {}; using cudf::numeric_scalar; using cudf::size_type; using cudf::string_scalar; using cudf::test::fixed_width_column_wrapper; TEST_F(DictionarySearchTest, search_dictionary) { cudf::test::dictionary_column_wrapper<std::string> input( {"", "", "10", "10", "20", "20", "30", "40"}, {0, 0, 1, 1, 1, 1, 1, 1}); cudf::test::dictionary_column_wrapper<std::string> values( {"", "08", "10", "11", "30", "32", "90"}, {0, 1, 1, 1, 1, 1, 1}); auto result = cudf::upper_bound({cudf::table_view{{input}}}, {cudf::table_view{{values}}}, {cudf::order::ASCENDING}, {cudf::null_order::BEFORE}); fixed_width_column_wrapper<size_type> expect_upper{2, 2, 4, 4, 7, 7, 8}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect_upper); result = cudf::lower_bound({cudf::table_view{{input}}}, {cudf::table_view{{values}}}, {cudf::order::ASCENDING}, {cudf::null_order::BEFORE}); fixed_width_column_wrapper<size_type> expect_lower{0, 2, 2, 4, 6, 7, 8}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect_lower); } TEST_F(DictionarySearchTest, search_table_dictionary) { fixed_width_column_wrapper<int32_t> column_0{{10, 10, 20, 20, 20, 20, 20, 20, 20, 50, 30}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}}; fixed_width_column_wrapper<float> column_1{{5.0, 6.0, .5, .5, .5, .5, .7, .7, .7, .7, .5}, {1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1}}; cudf::test::dictionary_column_wrapper<int16_t> column_2{ {90, 95, 77, 78, 79, 76, 61, 62, 63, 41, 50}, {1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1}}; cudf::table_view input({column_0, column_1, column_2}); fixed_width_column_wrapper<int32_t> values_0{{10, 40, 20}, {1, 0, 1}}; fixed_width_column_wrapper<float> values_1{{6., .5, .5}, {0, 1, 1}}; cudf::test::dictionary_column_wrapper<int16_t> values_2{{95, 50, 77}, {1, 1, 0}}; cudf::table_view values({values_0, values_1, values_2}); std::vector<cudf::order> order_flags{ {cudf::order::ASCENDING, cudf::order::ASCENDING, cudf::order::DESCENDING}}; std::vector<cudf::null_order> null_order_flags{ {cudf::null_order::AFTER, cudf::null_order::AFTER, cudf::null_order::AFTER}}; auto result = cudf::lower_bound(input, values, order_flags, null_order_flags); fixed_width_column_wrapper<size_type> expect_lower{1, 10, 2}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect_lower); result = cudf::upper_bound(input, values, order_flags, null_order_flags); fixed_width_column_wrapper<size_type> expect_upper{2, 11, 6}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect_upper); } TEST_F(DictionarySearchTest, contains_dictionary) { cudf::test::dictionary_column_wrapper<std::string> column( {"00", "00", "17", "17", "23", "23", "29"}); EXPECT_TRUE(cudf::contains(column, string_scalar{"23"})); EXPECT_FALSE(cudf::contains(column, string_scalar{"28"})); cudf::test::dictionary_column_wrapper<std::string> needles({"00", "17", "23", "27"}); fixed_width_column_wrapper<bool> expect{1, 1, 1, 0}; auto result = cudf::contains(column, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } TEST_F(DictionarySearchTest, contains_nullable_dictionary) { cudf::test::dictionary_column_wrapper<int64_t> column({0, 0, 17, 17, 23, 23, 29}, {1, 0, 1, 1, 1, 1, 1}); EXPECT_TRUE(cudf::contains(column, numeric_scalar<int64_t>{23})); EXPECT_FALSE(cudf::contains(column, numeric_scalar<int64_t>{28})); cudf::test::dictionary_column_wrapper<int64_t> needles({0, 17, 23, 27}); fixed_width_column_wrapper<bool> expect{1, 1, 1, 0}; auto result = cudf::contains(column, needles); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/wrappers/timestamps_test.cu
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/timestamp_utilities.cuh> #include <cudf_test/type_lists.hpp> #include <cudf/binaryop.hpp> #include <cudf/column/column_device_view.cuh> #include <cudf/column/column_factories.hpp> #include <cudf/column/column_view.hpp> #include <cudf/types.hpp> #include <cudf/utilities/default_stream.hpp> #include <cudf/wrappers/durations.hpp> #include <cudf/wrappers/timestamps.hpp> #include <rmm/cuda_stream_view.hpp> #include <rmm/device_uvector.hpp> #include <rmm/exec_policy.hpp> #include <thrust/logical.h> #include <thrust/sequence.h> template <typename T> struct ChronoColumnTest : public cudf::test::BaseFixture { cudf::size_type size() { return cudf::size_type(100); } cudf::data_type type() { return cudf::data_type{cudf::type_to_id<T>()}; } }; template <typename ChronoT> struct compare_chrono_elements_to_primitive_representation { cudf::column_device_view primitives; cudf::column_device_view chronos; compare_chrono_elements_to_primitive_representation(cudf::column_device_view& _primitives, cudf::column_device_view& _chronos) : primitives(_primitives), chronos(_chronos) { } template <typename T = ChronoT, std::enable_if_t<cudf::is_timestamp<T>()>* = nullptr> __host__ __device__ bool operator()(const int32_t element_index) { using Primitive = typename ChronoT::rep; auto primitive = primitives.element<Primitive>(element_index); auto timestamp = chronos.element<ChronoT>(element_index); return primitive == timestamp.time_since_epoch().count(); } template <typename T = ChronoT, std::enable_if_t<cudf::is_duration<T>()>* = nullptr> __host__ __device__ bool operator()(const int32_t element_index) { using Primitive = typename ChronoT::rep; auto primitive = primitives.element<Primitive>(element_index); auto dur = chronos.element<ChronoT>(element_index); return primitive == dur.count(); } }; TYPED_TEST_SUITE(ChronoColumnTest, cudf::test::ChronoTypes); TYPED_TEST(ChronoColumnTest, ChronoDurationsMatchPrimitiveRepresentation) { using T = TypeParam; using Rep = typename T::rep; using namespace cuda::std::chrono; auto start = milliseconds(-2500000000000); // Sat, 11 Oct 1890 19:33:20 GMT auto stop = milliseconds(2500000000000); // Mon, 22 Mar 2049 04:26:40 GMT auto chrono_col = cudf::test::generate_timestamps<T>( this->size(), cudf::test::time_point_ms(start), cudf::test::time_point_ms(stop)); // round-trip through the host to copy `chrono_col` values // to a new fixed_width_column_wrapper `primitive_col` auto const [chrono_col_data, chrono_col_mask] = cudf::test::to_host<Rep>(chrono_col); auto primitive_col = cudf::test::fixed_width_column_wrapper<Rep>(chrono_col_data.begin(), chrono_col_data.end()); rmm::device_uvector<int32_t> indices(this->size(), cudf::get_default_stream()); thrust::sequence(rmm::exec_policy(cudf::get_default_stream()), indices.begin(), indices.end()); EXPECT_TRUE(thrust::all_of(rmm::exec_policy(cudf::get_default_stream()), indices.begin(), indices.end(), compare_chrono_elements_to_primitive_representation<T>{ *cudf::column_device_view::create(primitive_col), *cudf::column_device_view::create(chrono_col)})); } template <typename ChronoT> struct compare_chrono_elements { cudf::binary_operator comp; cudf::column_device_view lhs; cudf::column_device_view rhs; compare_chrono_elements(cudf::binary_operator _comp, cudf::column_device_view& _lhs, cudf::column_device_view& _rhs) : comp(_comp), lhs(_lhs), rhs(_rhs) { } __host__ __device__ bool operator()(const int32_t element_index) { auto lhs_elt = lhs.element<ChronoT>(element_index); auto rhs_elt = rhs.element<ChronoT>(element_index); switch (comp) { case cudf::binary_operator::LESS: return lhs_elt < rhs_elt; case cudf::binary_operator::GREATER: return lhs_elt > rhs_elt; case cudf::binary_operator::LESS_EQUAL: return lhs_elt <= rhs_elt; case cudf::binary_operator::GREATER_EQUAL: return lhs_elt >= rhs_elt; default: return false; } } }; TYPED_TEST(ChronoColumnTest, ChronosCanBeComparedInDeviceCode) { using T = TypeParam; using namespace cuda::std::chrono; auto start_lhs = milliseconds(-2500000000000); // Sat, 11 Oct 1890 19:33:20 GMT auto start_rhs = milliseconds(-2400000000000); // Tue, 12 Dec 1893 05:20:00 GMT auto stop_lhs = milliseconds(2500000000000); // Mon, 22 Mar 2049 04:26:40 GMT auto stop_rhs = milliseconds(2600000000000); // Wed, 22 May 2052 14:13:20 GMT auto chrono_lhs_col = cudf::test::generate_timestamps<T>( this->size(), cudf::test::time_point_ms(start_lhs), cudf::test::time_point_ms(stop_lhs)); auto chrono_rhs_col = cudf::test::generate_timestamps<T>( this->size(), cudf::test::time_point_ms(start_rhs), cudf::test::time_point_ms(stop_rhs)); rmm::device_uvector<int32_t> indices(this->size(), cudf::get_default_stream()); thrust::sequence(rmm::exec_policy(cudf::get_default_stream()), indices.begin(), indices.end()); EXPECT_TRUE(thrust::all_of( rmm::exec_policy(cudf::get_default_stream()), indices.begin(), indices.end(), compare_chrono_elements<TypeParam>{cudf::binary_operator::LESS, *cudf::column_device_view::create(chrono_lhs_col), *cudf::column_device_view::create(chrono_rhs_col)})); EXPECT_TRUE(thrust::all_of( rmm::exec_policy(cudf::get_default_stream()), indices.begin(), indices.end(), compare_chrono_elements<TypeParam>{cudf::binary_operator::GREATER, *cudf::column_device_view::create(chrono_rhs_col), *cudf::column_device_view::create(chrono_lhs_col)})); EXPECT_TRUE(thrust::all_of( rmm::exec_policy(cudf::get_default_stream()), indices.begin(), indices.end(), compare_chrono_elements<TypeParam>{cudf::binary_operator::LESS_EQUAL, *cudf::column_device_view::create(chrono_lhs_col), *cudf::column_device_view::create(chrono_lhs_col)})); EXPECT_TRUE(thrust::all_of( rmm::exec_policy(cudf::get_default_stream()), indices.begin(), indices.end(), compare_chrono_elements<TypeParam>{cudf::binary_operator::GREATER_EQUAL, *cudf::column_device_view::create(chrono_rhs_col), *cudf::column_device_view::create(chrono_rhs_col)})); } TYPED_TEST(ChronoColumnTest, ChronoFactoryNullMaskAsParm) { rmm::device_buffer null_mask{create_null_mask(this->size(), cudf::mask_state::ALL_NULL)}; auto column = make_fixed_width_column(cudf::data_type{cudf::type_to_id<TypeParam>()}, this->size(), std::move(null_mask), this->size()); EXPECT_EQ(column->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(column->size(), this->size()); EXPECT_EQ(this->size(), column->null_count()); EXPECT_TRUE(column->nullable()); EXPECT_TRUE(column->has_nulls()); EXPECT_EQ(0, column->num_children()); } TYPED_TEST(ChronoColumnTest, ChronoFactoryNullMaskAsEmptyParm) { rmm::device_buffer null_mask{}; auto column = make_fixed_width_column( cudf::data_type{cudf::type_to_id<TypeParam>()}, this->size(), std::move(null_mask), 0); EXPECT_EQ(column->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(column->size(), this->size()); EXPECT_EQ(0, column->null_count()); EXPECT_FALSE(column->nullable()); EXPECT_FALSE(column->has_nulls()); EXPECT_EQ(0, column->num_children()); } CUDF_TEST_PROGRAM_MAIN()
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/rolling/range_comparator_test.cu
/* * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/type_lists.hpp> #include <src/rolling/detail/range_comparator_utils.cuh> struct RangeComparatorTest : cudf::test::BaseFixture {}; template <typename T> struct RangeComparatorTypedTest : RangeComparatorTest {}; using TestTypes = cudf::test::Concat<cudf::test::IntegralTypesNotBool, cudf::test::FloatingPointTypes>; TYPED_TEST_SUITE(RangeComparatorTypedTest, TestTypes); TYPED_TEST(RangeComparatorTypedTest, TestLessComparator) { auto const less = cudf::detail::nan_aware_less{}; auto constexpr nine = TypeParam{9}; auto constexpr ten = TypeParam{10}; EXPECT_TRUE(less(nine, ten)); EXPECT_FALSE(less(ten, nine)); EXPECT_FALSE(less(ten, ten)); if constexpr (std::is_floating_point_v<TypeParam>) { auto constexpr NaN = std::numeric_limits<TypeParam>::quiet_NaN(); auto constexpr Inf = std::numeric_limits<TypeParam>::infinity(); // NaN. EXPECT_FALSE(less(NaN, ten)); EXPECT_FALSE(less(NaN, NaN)); EXPECT_FALSE(less(NaN, Inf)); EXPECT_FALSE(less(NaN, -Inf)); // Infinity. EXPECT_TRUE(less(Inf, NaN)); EXPECT_FALSE(less(Inf, Inf)); EXPECT_FALSE(less(Inf, ten)); EXPECT_FALSE(less(Inf, -Inf)); // -Infinity. EXPECT_TRUE(less(-Inf, NaN)); EXPECT_TRUE(less(-Inf, Inf)); EXPECT_TRUE(less(-Inf, ten)); EXPECT_FALSE(less(-Inf, -Inf)); // Finite. EXPECT_TRUE(less(ten, NaN)); EXPECT_TRUE(less(ten, Inf)); EXPECT_FALSE(less(ten, -Inf)); } } TYPED_TEST(RangeComparatorTypedTest, TestGreaterComparator) { auto const greater = cudf::detail::nan_aware_greater{}; auto constexpr nine = TypeParam{9}; auto constexpr ten = TypeParam{10}; EXPECT_FALSE(greater(nine, ten)); EXPECT_TRUE(greater(ten, nine)); EXPECT_FALSE(greater(ten, ten)); if constexpr (std::is_floating_point_v<TypeParam>) { auto constexpr NaN = std::numeric_limits<TypeParam>::quiet_NaN(); auto constexpr Inf = std::numeric_limits<TypeParam>::infinity(); // NaN. EXPECT_TRUE(greater(NaN, ten)); EXPECT_FALSE(greater(NaN, NaN)); EXPECT_TRUE(greater(NaN, Inf)); EXPECT_TRUE(greater(NaN, -Inf)); // Infinity. EXPECT_FALSE(greater(Inf, NaN)); EXPECT_FALSE(greater(Inf, Inf)); EXPECT_TRUE(greater(Inf, ten)); EXPECT_TRUE(greater(Inf, -Inf)); // -Infinity. EXPECT_FALSE(greater(-Inf, NaN)); EXPECT_FALSE(greater(-Inf, Inf)); EXPECT_FALSE(greater(-Inf, ten)); EXPECT_FALSE(greater(-Inf, -Inf)); // Finite. EXPECT_FALSE(greater(ten, NaN)); EXPECT_FALSE(greater(ten, Inf)); EXPECT_TRUE(greater(ten, -Inf)); } } TYPED_TEST(RangeComparatorTypedTest, TestAddSafe) { using T = TypeParam; EXPECT_EQ(cudf::detail::add_safe(T{3}, T{4}), T{7}); if constexpr (cuda::std::numeric_limits<T>::is_signed) { EXPECT_EQ(cudf::detail::add_safe(T{-3}, T{4}), T{1}); } auto constexpr max = cuda::std::numeric_limits<T>::max(); EXPECT_EQ(cudf::detail::add_safe(T{max - 5}, T{4}), max - 1); EXPECT_EQ(cudf::detail::add_safe(T{max - 4}, T{4}), max); EXPECT_EQ(cudf::detail::add_safe(T{max - 3}, T{4}), max); EXPECT_EQ(cudf::detail::add_safe(max, T{4}), max); if constexpr (std::is_floating_point_v<T>) { auto const NaN = std::numeric_limits<T>::quiet_NaN(); auto const Inf = std::numeric_limits<T>::infinity(); EXPECT_TRUE(std::isnan(cudf::detail::add_safe(NaN, T{4}))); EXPECT_EQ(cudf::detail::add_safe(Inf, T{4}), Inf); } } TYPED_TEST(RangeComparatorTypedTest, TestSubtractSafe) { using T = TypeParam; EXPECT_EQ(cudf::detail::subtract_safe(T{4}, T{3}), T{1}); if constexpr (cuda::std::numeric_limits<T>::is_signed) { EXPECT_EQ(cudf::detail::subtract_safe(T{3}, T{4}), T{-1}); } auto constexpr min = cuda::std::numeric_limits<T>::lowest(); EXPECT_EQ(cudf::detail::subtract_safe(T{min + 5}, T{4}), min + 1); EXPECT_EQ(cudf::detail::subtract_safe(T{min + 4}, T{4}), min); EXPECT_EQ(cudf::detail::subtract_safe(T{min + 3}, T{4}), min); EXPECT_EQ(cudf::detail::subtract_safe(min, T{4}), min); if constexpr (std::is_floating_point_v<T>) { auto const NaN = std::numeric_limits<T>::quiet_NaN(); auto const Inf = std::numeric_limits<T>::infinity(); EXPECT_TRUE(std::isnan(cudf::detail::subtract_safe(NaN, T{4}))); EXPECT_EQ(cudf::detail::subtract_safe(-Inf, T{4}), -Inf); } }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/rolling/offset_row_window_test.cpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf/aggregation.hpp> #include <cudf/groupby.hpp> #include <cudf/lists/explode.hpp> #include <cudf/rolling.hpp> #include <cudf/utilities/default_stream.hpp> template <typename T> using fwcw = cudf::test::fixed_width_column_wrapper<T>; template <typename T> using decimals_column = cudf::test::fixed_point_column_wrapper<T>; using ints_column = fwcw<int32_t>; using bigints_column = fwcw<int64_t>; using strings_column = cudf::test::strings_column_wrapper; using lists_column = cudf::test::lists_column_wrapper<int32_t>; using column_ptr = std::unique_ptr<cudf::column>; using cudf::test::iterators::all_nulls; using cudf::test::iterators::no_nulls; using cudf::test::iterators::nulls_at; auto constexpr null = int32_t{0}; // NULL representation for int32_t; struct OffsetRowWindowTest : public cudf::test::BaseFixture { static ints_column const _keys; // {0, 0, 0, 0, 0, 0, 1, 1, 1, 1}; static ints_column const _values; // {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; struct rolling_runner { cudf::window_bounds _preceding, _following; cudf::size_type _min_periods; bool _grouped = true; rolling_runner(cudf::window_bounds const& preceding, cudf::window_bounds const& following, cudf::size_type min_periods_ = 1) : _preceding{preceding}, _following{following}, _min_periods{min_periods_} { } rolling_runner& min_periods(cudf::size_type min_periods_) { _min_periods = min_periods_; return *this; } rolling_runner& grouped(bool grouped_) { _grouped = grouped_; return *this; } std::unique_ptr<cudf::column> operator()(cudf::rolling_aggregation const& agg) const { auto const grouping_keys = _grouped ? std::vector<cudf::column_view>{_keys} : std::vector<cudf::column_view>{}; return cudf::grouped_rolling_window( cudf::table_view{grouping_keys}, _values, _preceding, _following, _min_periods, agg); } }; }; ints_column const OffsetRowWindowTest::_keys{0, 0, 0, 0, 0, 0, 1, 1, 1, 1}; ints_column const OffsetRowWindowTest::_values{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto const AGG_COUNT_NON_NULL = cudf::make_count_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE); auto const AGG_COUNT_ALL = cudf::make_count_aggregation<cudf::rolling_aggregation>(cudf::null_policy::INCLUDE); auto const AGG_MIN = cudf::make_min_aggregation<cudf::rolling_aggregation>(); auto const AGG_MAX = cudf::make_max_aggregation<cudf::rolling_aggregation>(); auto const AGG_SUM = cudf::make_sum_aggregation<cudf::rolling_aggregation>(); auto const AGG_COLLECT_LIST = cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(); TEST_F(OffsetRowWindowTest, OffsetRowWindow_Grouped_3_to_Minus_1) { auto const preceding = cudf::window_bounds::get(3); auto const following = cudf::window_bounds::get(-1); auto run_rolling = rolling_runner{preceding, following}.min_periods(1).grouped(true); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*run_rolling(*AGG_COUNT_NON_NULL), ints_column{{0, 1, 2, 2, 2, 2, 0, 1, 2, 2}, nulls_at({0, 6})}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*run_rolling(*AGG_COUNT_ALL), ints_column{{0, 1, 2, 2, 2, 2, 0, 1, 2, 2}, nulls_at({0, 6})}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *run_rolling(*AGG_MIN), ints_column{{null, 0, 0, 1, 2, 3, null, 6, 6, 7}, nulls_at({0, 6})}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *run_rolling(*AGG_MAX), ints_column{{null, 0, 1, 2, 3, 4, null, 6, 7, 8}, nulls_at({0, 6})}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *run_rolling(*AGG_SUM), bigints_column{{null, 0, 1, 3, 5, 7, null, 6, 13, 15}, nulls_at({0, 6})}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *run_rolling(*AGG_COLLECT_LIST), lists_column{{{}, {0}, {0, 1}, {1, 2}, {2, 3}, {3, 4}, {}, {6}, {6, 7}, {7, 8}}, nulls_at({0, 6})}); run_rolling.min_periods(0); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*run_rolling(*AGG_COUNT_NON_NULL), ints_column{{0, 1, 2, 2, 2, 2, 0, 1, 2, 2}, no_nulls()}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*run_rolling(*AGG_COUNT_ALL), ints_column{{0, 1, 2, 2, 2, 2, 0, 1, 2, 2}, no_nulls()}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *run_rolling(*AGG_COLLECT_LIST), lists_column{{{}, {0}, {0, 1}, {1, 2}, {2, 3}, {3, 4}, {}, {6}, {6, 7}, {7, 8}}, no_nulls()}); } TEST_F(OffsetRowWindowTest, OffsetRowWindow_Ungrouped_3_to_Minus_1) { auto const preceding = cudf::window_bounds::get(3); auto const following = cudf::window_bounds::get(-1); auto run_rolling = rolling_runner{preceding, following}.min_periods(1).grouped(false); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*run_rolling(*AGG_COUNT_NON_NULL), ints_column{{0, 1, 2, 2, 2, 2, 2, 2, 2, 2}, nulls_at({0})}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*run_rolling(*AGG_COUNT_ALL), ints_column{{0, 1, 2, 2, 2, 2, 2, 2, 2, 2}, nulls_at({0})}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*run_rolling(*AGG_MIN), ints_column{{null, 0, 0, 1, 2, 3, 4, 5, 6, 7}, nulls_at({0})}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*run_rolling(*AGG_MAX), ints_column{{null, 0, 1, 2, 3, 4, 5, 6, 7, 8}, nulls_at({0})}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *run_rolling(*AGG_SUM), bigints_column{{null, 0, 1, 3, 5, 7, 9, 11, 13, 15}, nulls_at({0})}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *run_rolling(*AGG_COLLECT_LIST), lists_column{{{}, {0}, {0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}, {6, 7}, {7, 8}}, nulls_at({0})}); run_rolling.min_periods(0); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*run_rolling(*AGG_COUNT_NON_NULL), ints_column{{0, 1, 2, 2, 2, 2, 2, 2, 2, 2}, no_nulls()}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*run_rolling(*AGG_COUNT_ALL), ints_column{{0, 1, 2, 2, 2, 2, 2, 2, 2, 2}, no_nulls()}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *run_rolling(*AGG_COLLECT_LIST), lists_column{{{}, {0}, {0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}, {6, 7}, {7, 8}}, no_nulls()}); } TEST_F(OffsetRowWindowTest, OffsetRowWindow_Grouped_0_to_2) { auto const preceding = cudf::window_bounds::get(0); auto const following = cudf::window_bounds::get(2); auto run_rolling = rolling_runner{preceding, following}.min_periods(1).grouped(true); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *run_rolling(*AGG_COUNT_NON_NULL), ints_column{{2, 2, 2, 2, 1, null, 2, 2, 1, null}, nulls_at({5, 9})}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *run_rolling(*AGG_COUNT_ALL), ints_column{{2, 2, 2, 2, 1, null, 2, 2, 1, null}, nulls_at({5, 9})}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *run_rolling(*AGG_MIN), ints_column{{1, 2, 3, 4, 5, null, 7, 8, 9, null}, nulls_at({5, 9})}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *run_rolling(*AGG_MAX), ints_column{{2, 3, 4, 5, 5, null, 8, 9, 9, null}, nulls_at({5, 9})}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *run_rolling(*AGG_SUM), bigints_column{{3, 5, 7, 9, 5, null, 15, 17, 9, null}, nulls_at({5, 9})}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *run_rolling(*AGG_COLLECT_LIST), lists_column{{{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5}, {}, {7, 8}, {8, 9}, {9}, {}}, nulls_at({5, 9})}); run_rolling.min_periods(0); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*run_rolling(*AGG_COUNT_NON_NULL), ints_column{{2, 2, 2, 2, 1, 0, 2, 2, 1, 0}, no_nulls()}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*run_rolling(*AGG_COUNT_ALL), ints_column{{2, 2, 2, 2, 1, 0, 2, 2, 1, 0}, no_nulls()}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *run_rolling(*AGG_COLLECT_LIST), lists_column{{{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5}, {}, {7, 8}, {8, 9}, {9}, {}}, no_nulls}); } TEST_F(OffsetRowWindowTest, OffsetRowWindow_Ungrouped_0_to_2) { auto const preceding = cudf::window_bounds::get(0); auto const following = cudf::window_bounds::get(2); auto run_rolling = rolling_runner{preceding, following}.min_periods(1).grouped(false); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*run_rolling(*AGG_COUNT_NON_NULL), ints_column{{2, 2, 2, 2, 2, 2, 2, 2, 1, null}, nulls_at({9})}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*run_rolling(*AGG_COUNT_ALL), ints_column{{2, 2, 2, 2, 2, 2, 2, 2, 1, null}, nulls_at({9})}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*run_rolling(*AGG_MIN), ints_column{{1, 2, 3, 4, 5, 6, 7, 8, 9, null}, nulls_at({9})}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*run_rolling(*AGG_MAX), ints_column{{2, 3, 4, 5, 6, 7, 8, 9, 9, null}, nulls_at({9})}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *run_rolling(*AGG_SUM), bigints_column{{3, 5, 7, 9, 11, 13, 15, 17, 9, null}, nulls_at({9})}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *run_rolling(*AGG_COLLECT_LIST), lists_column{{{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}, {6, 7}, {7, 8}, {8, 9}, {9}, {}}, nulls_at({9})}); run_rolling.min_periods(0); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*run_rolling(*AGG_COUNT_NON_NULL), ints_column{{2, 2, 2, 2, 2, 2, 2, 2, 1, 0}, no_nulls()}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*run_rolling(*AGG_COUNT_ALL), ints_column{{2, 2, 2, 2, 2, 2, 2, 2, 1, 0}, no_nulls()}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *run_rolling(*AGG_COLLECT_LIST), lists_column{{{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}, {6, 7}, {7, 8}, {8, 9}, {9}, {}}, no_nulls}); } // To test that preceding bounds are clamped correctly at group boundaries. TEST_F(OffsetRowWindowTest, TestNegativeBoundsClamp) { auto const grp_iter = thrust::make_transform_iterator(thrust::make_counting_iterator(0), [](auto const& i) { return i / 10; // 0-9 in the first group, 10-19 in the second, etc. }); auto const agg_iter = thrust::make_constant_iterator(1); auto const grp = ints_column(grp_iter, grp_iter + 30); auto const agg = ints_column(agg_iter, agg_iter + 30); auto const min_periods = 0; auto const rolling_sum = [&](auto const preceding, auto const following) { return cudf::grouped_rolling_window( cudf::table_view{{grp}}, agg, preceding, following, min_periods, *AGG_SUM); }; // Testing negative preceding. for (auto const preceding : {0, -1, -2, -5, -10, -20, -50}) { auto const results = rolling_sum(preceding, 100); auto const expected_fun = [&](auto const& i) { assert(preceding < 1); auto const index_in_group = i % 10; auto const start = std::min(-(preceding - 1) + index_in_group, 10); return int64_t{10 - start}; }; auto const expected_iter = thrust::make_transform_iterator(thrust::make_counting_iterator(0), expected_fun); auto const expected = bigints_column(expected_iter, expected_iter + 30, no_nulls()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } // Testing negative following. for (auto const following : {-1, -2, -5, -10, -20, -50}) { auto const results = rolling_sum(100, following); auto const expected_fun = [&](auto const& i) { assert(following < 0); auto const index_in_group = i % 10; auto const end = std::max(index_in_group + following, -1); return int64_t{end + 1}; }; auto const expected_iter = thrust::make_transform_iterator(thrust::make_counting_iterator(0), expected_fun); auto const expected = bigints_column(expected_iter, expected_iter + 30, no_nulls()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } } TEST_F(OffsetRowWindowTest, CheckGroupBoundaries) { auto grp_iter = thrust::make_transform_iterator(thrust::make_counting_iterator(0), [](auto const& i) { if (i < 10) return 1; if (i < 20) return 2; return 3; }); auto const grp = ints_column(grp_iter, grp_iter + 30); auto const agg = ints_column(grp_iter, grp_iter + 30); { auto const results = cudf::grouped_rolling_window(cudf::table_view{{grp}}, agg, -80, 100, 1, *cudf::make_max_aggregation<cudf::rolling_aggregation>()); auto const null_iter = thrust::make_constant_iterator<int32_t>(null); auto const expected = ints_column(null_iter, null_iter + 30, all_nulls()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected); } { auto const results = cudf::grouped_rolling_window(cudf::table_view{{grp}}, agg, -1, 4, 1, *cudf::make_min_aggregation<cudf::rolling_aggregation>()); auto const expected = ints_column{{1, 1, 1, 1, 1, 1, 1, 1, null, null, 2, 2, 2, 2, 2, 2, 2, 2, null, null, 3, 3, 3, 3, 3, 3, 3, 3, null, null}, nulls_at({8, 9, 18, 19, 28, 29})}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(results->view(), expected); } }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/rolling/nth_element_test.cpp
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/aggregation.hpp> #include <cudf/groupby.hpp> #include <cudf/null_mask.hpp> #include <cudf/rolling.hpp> #include <gtest/gtest-typed-test.h> #include <rmm/device_buffer.hpp> #include <thrust/iterator/counting_iterator.h> #include <thrust/iterator/transform_iterator.h> #include <memory> #include <optional> auto constexpr X = int32_t{0}; // Placeholder for null. template <typename T> using fwcw = cudf::test::fixed_width_column_wrapper<T>; using grouping_keys_column = fwcw<int32_t>; /// Rolling test executor with fluent interface. class rolling_exec { cudf::size_type _preceding{1}; cudf::size_type _following{0}; cudf::size_type _min_periods{1}; cudf::column_view _grouping; cudf::column_view _input; cudf::null_policy _null_handling = cudf::null_policy::INCLUDE; public: rolling_exec& preceding(cudf::size_type preceding) { _preceding = preceding; return *this; } rolling_exec& following(cudf::size_type following) { _following = following; return *this; } rolling_exec& min_periods(cudf::size_type min_periods) { _min_periods = min_periods; return *this; } rolling_exec& grouping(cudf::column_view grouping) { _grouping = grouping; return *this; } rolling_exec& input(cudf::column_view input) { _input = input; return *this; } rolling_exec& null_handling(cudf::null_policy null_handling) { _null_handling = null_handling; return *this; } std::unique_ptr<cudf::column> test_grouped_nth_element( cudf::size_type n, std::optional<cudf::null_policy> null_handling = std::nullopt) const { return cudf::grouped_rolling_window( cudf::table_view{{_grouping}}, _input, _preceding, _following, _min_periods, *cudf::make_nth_element_aggregation<cudf::rolling_aggregation>( n, null_handling.value_or(_null_handling))); } std::unique_ptr<cudf::column> test_nth_element( cudf::size_type n, std::optional<cudf::null_policy> null_handling = std::nullopt) const { return cudf::rolling_window(_input, _preceding, _following, _min_periods, *cudf::make_nth_element_aggregation<cudf::rolling_aggregation>( n, null_handling.value_or(_null_handling))); } }; struct NthElementTest : public cudf::test::BaseFixture {}; template <typename T> struct NthElementTypedTest : public NthElementTest {}; using TypesForTest = cudf::test::Concat<cudf::test::IntegralTypes, cudf::test::FloatingPointTypes, cudf::test::DurationTypes, cudf::test::TimestampTypes>; TYPED_TEST_SUITE(NthElementTypedTest, TypesForTest); TYPED_TEST(NthElementTypedTest, RollingWindow) { using T = TypeParam; auto const input_col = fwcw<T>{{0, 1, 2, 3, 4, X, 10, 11, 12, 13, 14, 15, 16, 20}, cudf::test::iterators::null_at(5)}; auto tester = rolling_exec{}.input(input_col); { // Window of 5 elements, min-periods == 1. tester.preceding(3).following(2).min_periods(1); auto const first_element = tester.test_nth_element(0); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *first_element, fwcw<T>{{0, 0, 0, 1, 2, 3, 4, X, 10, 11, 12, 13, 14, 15}, cudf::test::iterators::null_at(7)}); auto const last_element = tester.test_nth_element(-1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *last_element, fwcw<T>{{2, 3, 4, X, 10, 11, 12, 13, 14, 15, 16, 20, 20, 20}, cudf::test::iterators::null_at(3)}); auto const third_element = tester.test_nth_element(2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*third_element, fwcw<T>{{2, 2, 2, 3, 4, X, 10, 11, 12, 13, 14, 15, 16, 20}, cudf::test::iterators::null_at(5)}); auto const second_last_element = tester.test_nth_element(-2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*second_last_element, fwcw<T>{{1, 2, 3, 4, X, 10, 11, 12, 13, 14, 15, 16, 16, 16}, cudf::test::iterators::null_at(4)}); } { // Window of 3 elements, min-periods == 3. Expect null elements at column margins. tester.preceding(2).following(1).min_periods(3); auto const first_element = tester.test_nth_element(0); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*first_element, fwcw<T>{{X, 0, 1, 2, 3, 4, X, 10, 11, 12, 13, 14, 15, X}, cudf::test::iterators::nulls_at({0, 6, 13})}); auto const last_element = tester.test_nth_element(-1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*last_element, fwcw<T>{{X, 2, 3, 4, X, 10, 11, 12, 13, 14, 15, 16, 20, X}, cudf::test::iterators::nulls_at({0, 4, 13})}); auto const second_element = tester.test_nth_element(1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*second_element, fwcw<T>{{X, 1, 2, 3, 4, X, 10, 11, 12, 13, 14, 15, 16, X}, cudf::test::iterators::nulls_at({0, 5, 13})}); auto const second_last_element = tester.test_nth_element(-2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*second_last_element, fwcw<T>{{X, 1, 2, 3, 4, X, 10, 11, 12, 13, 14, 15, 16, X}, cudf::test::iterators::nulls_at({0, 5, 13})}); } { // Too large values for `min_periods`. No window has enough periods. tester.preceding(2).following(1).min_periods(4); auto const all_null_values = fwcw<T>{{X, X, X, X, X, X, X, X, X, X, X, X, X, X}, cudf::test::iterators::all_nulls()}; auto const first_element = tester.test_nth_element(0); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*first_element, all_null_values); auto const last_element = tester.test_nth_element(-1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*last_element, all_null_values); auto const second_element = tester.test_nth_element(1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*second_element, all_null_values); auto const second_last_element = tester.test_nth_element(-2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*second_last_element, all_null_values); } } TYPED_TEST(NthElementTypedTest, RollingWindowExcludeNulls) { using T = TypeParam; auto const input_col = fwcw<T>{{0, X, X, X, 4, X, 6, 7}, cudf::test::iterators::nulls_at({1, 2, 3, 5})}; auto tester = rolling_exec{}.input(input_col); { // Window of 5 elements, min-periods == 2. tester.preceding(3).following(2).min_periods(1).null_handling(cudf::null_policy::EXCLUDE); auto const first_element = tester.test_nth_element(0); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *first_element, fwcw<T>{{0, 0, 0, 4, 4, 4, 4, 6}, cudf::test::iterators::no_nulls()}); auto const last_element = tester.test_nth_element(-1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *last_element, fwcw<T>{{0, 0, 4, 4, 6, 7, 7, 7}, cudf::test::iterators::no_nulls()}); auto const second_element = tester.test_nth_element(1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *second_element, fwcw<T>{{X, X, 4, X, 6, 6, 6, 7}, cudf::test::iterators::nulls_at({0, 1, 3})}); auto const second_last_element = tester.test_nth_element(-2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *second_last_element, fwcw<T>{{X, X, 0, X, 4, 6, 6, 6}, cudf::test::iterators::nulls_at({0, 1, 3})}); } { // Window of 3 elements, min-periods == 1. tester.preceding(2).following(1).min_periods(1).null_handling(cudf::null_policy::EXCLUDE); auto const first_element = tester.test_nth_element(0); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *first_element, fwcw<T>{{0, 0, X, 4, 4, 4, 6, 6}, cudf::test::iterators::null_at(2)}); auto const last_element = tester.test_nth_element(-1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *last_element, fwcw<T>{{0, 0, X, 4, 4, 6, 7, 7}, cudf::test::iterators::null_at(2)}); auto const second_element = tester.test_nth_element(1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *second_element, fwcw<T>{{X, X, X, X, X, 6, 7, 7}, cudf::test::iterators::nulls_at({0, 1, 2, 3, 4})}); auto const second_last_element = tester.test_nth_element(-2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *second_last_element, fwcw<T>{{X, X, X, X, X, 4, 6, 6}, cudf::test::iterators::nulls_at({0, 1, 2, 3, 4})}); } { // Too large values for `min_periods`. No window has enough periods. tester.preceding(2).following(1).min_periods(4); auto const all_null_values = fwcw<T>{{X, X, X, X, X, X, X, X}, cudf::test::iterators::all_nulls()}; auto const first_element = tester.test_nth_element(0); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*first_element, all_null_values); auto const last_element = tester.test_nth_element(-1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*last_element, all_null_values); auto const second_element = tester.test_nth_element(1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*second_element, all_null_values); auto const second_last_element = tester.test_nth_element(-2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*second_last_element, all_null_values); } } TYPED_TEST(NthElementTypedTest, GroupedRollingWindow) { using T = TypeParam; // clang-format off auto const group_col = fwcw<int32_t>{0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 20}; auto const input_col = fwcw<T> {0, 1, 2, 3, 4, 5, // Group 0 10, 11, 12, 13, 14, 15, 16, // Group 10 20}; // Group 20 // clang-format on auto tester = rolling_exec{}.grouping(group_col).input(input_col); { // Window of 5 elements, min-periods == 1. tester.preceding(3).following(2).min_periods(1); auto const first_element = tester.test_grouped_nth_element(0); // clang-format off CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*first_element, fwcw<T>{{0, 0, 0, 1, 2, 3, // Group 0 10, 10, 10, 11, 12, 13, 14, // Group 10 20}, // Group 20 cudf::test::iterators::no_nulls()}); auto const last_element = tester.test_grouped_nth_element(-1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*last_element, fwcw<T>{{2, 3, 4, 5, 5, 5, // Group 0 12, 13, 14, 15, 16, 16, 16, // Group 10 20}, // Group 20 cudf::test::iterators::no_nulls()}); auto const third_element = tester.test_grouped_nth_element(2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*third_element, fwcw<T>{{2, 2, 2, 3, 4, 5, // Group 0 12, 12, 12, 13, 14, 15, 16, // Group 10 X}, // Group 20 cudf::test::iterators::null_at(13)}); auto const second_last_element = tester.test_grouped_nth_element(-2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*second_last_element, fwcw<T>{{1, 2, 3, 4, 4, 4, // Group 0 11, 12, 13, 14, 15, 15, 15, // Group 10 X}, // Group 20 cudf::test::iterators::null_at(13)}); // clang-format on } { // Window of 3 elements, min-periods == 3. Expect null elements at group margins. tester.preceding(2).following(1).min_periods(3); auto const first_element = tester.test_grouped_nth_element(0); // clang-format off CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*first_element, fwcw<T>{{X, 0, 1, 2, 3, X, // Group 0 X, 10, 11, 12, 13, 14, X, // Group 10 X}, // Group 20 cudf::test::iterators::nulls_at({0, 5, 6, 12, 13})}); auto const last_element = tester.test_grouped_nth_element(-1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*last_element, fwcw<T>{{X, 2, 3, 4, 5, X, // Group 0 X, 12, 13, 14, 15, 16, X, // Group 10 X}, // Group 20 cudf::test::iterators::nulls_at({0, 5, 6, 12, 13})}); auto const second_element = tester.test_grouped_nth_element(1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*second_element, fwcw<T>{{X, 1, 2, 3, 4, X, // Group 0 X, 11, 12, 13, 14, 15, X, // Group 10 X}, // Group 20 cudf::test::iterators::nulls_at({0, 5, 6, 12, 13})}); auto const second_last_element = tester.test_grouped_nth_element(-2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*second_last_element, fwcw<T>{{X, 1, 2, 3, 4, X, // Group 0 X, 11, 12, 13, 14, 15, X, // Group 10 X}, // Group 20 cudf::test::iterators::nulls_at({0, 5, 6, 12, 13})}); // clang-format on } { // Too large values for `min_periods`. No window has enough periods. tester.preceding(2).following(1).min_periods(4); auto const all_null_values = fwcw<T>{{X, X, X, X, X, X, X, X, X, X, X, X, X, X}, cudf::test::iterators::all_nulls()}; auto const first_element = tester.test_grouped_nth_element(0); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*first_element, all_null_values); auto const last_element = tester.test_grouped_nth_element(-1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*last_element, all_null_values); auto const second_element = tester.test_grouped_nth_element(1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*second_element, all_null_values); auto const second_last_element = tester.test_grouped_nth_element(-2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*second_last_element, all_null_values); } } TYPED_TEST(NthElementTypedTest, GroupedRollingWindowExcludeNulls) { using T = TypeParam; // clang-format off auto const group_col = fwcw<int32_t>{0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 20, 30}; auto const input_col = fwcw<T> {{0, 1, X, 3, X, 5, // Group 0 10, X, X, 13, 14, 15, 16, // Group 10 20, // Group 20 X}, // Group 30 cudf::test::iterators::nulls_at({2, 4, 7, 8, 14})}; // clang-format on auto tester = rolling_exec{}.grouping(group_col).input(input_col); { // Window of 5 elements, min-periods == 1. tester.preceding(3).following(2).min_periods(1).null_handling(cudf::null_policy::EXCLUDE); auto const first_element = tester.test_grouped_nth_element(0); // clang-format off CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*first_element, fwcw<T>{{0, 0, 0, 1, 3, 3, // Group 0 10, 10, 10, 13, 13, 13, 14, // Group 10 20, // Group 20 X}, // Group 30 cudf::test::iterators::null_at(14)}); auto const last_element = tester.test_grouped_nth_element(-1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*last_element, fwcw<T>{{1, 3, 3, 5, 5, 5, // Group 0 10, 13, 14, 15, 16, 16, 16, // Group 10 20, // Group 20 X}, // Group 30 cudf::test::iterators::null_at(14)}); auto const third_element = tester.test_grouped_nth_element(2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*third_element, fwcw<T>{{X, 3, 3, 5, X, X, // Group 0 X, X, 14, 15, 15, 15, 16, // Group 10 X, // Group 20 X}, // Group 30 cudf::test::iterators::nulls_at({0, 4, 5, 6, 7, 13, 14})}); auto const second_last_element = tester.test_grouped_nth_element(-2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*second_last_element, fwcw<T>{{0, 1, 1, 3, 3, 3, // Group 0 X, 10, 13, 14, 15, 15, 15, // Group 10 X, // Group 20 X}, // Group 30 cudf::test::iterators::nulls_at({6, 13, 14})}); // clang-format on } { // Window of 3 elements, min-periods == 3. Expect null elements at group margins. tester.preceding(2).following(1).min_periods(3); auto const first_element = tester.test_grouped_nth_element(0); // clang-format off CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*first_element, fwcw<T>{{X, 0, 1, 3, 3, X, // Group 0 X, 10, 13, 13, 13, 14, X, // Group 10 X, // Group 20 X}, // Group 30 cudf::test::iterators::nulls_at({0, 5, 6, 12, 13, 14})}); auto const last_element = tester.test_grouped_nth_element(-1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*last_element, fwcw<T>{{X, 1, 3, 3, 5, X, // Group 0 X, 10, 13, 14, 15, 16, X, // Group 10 X, // Group 20 X}, // Group 30 cudf::test::iterators::nulls_at({0, 5, 6, 12, 13, 14})}); auto const second_element = tester.test_grouped_nth_element(1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*second_element, fwcw<T>{{X, 1, 3, X, 5, X, // Group 0 X, X, X, 14, 14, 15, X, // Group 10 X, // Group 20 X}, // Group 30 cudf::test::iterators::nulls_at({0, 3, 5, 6, 7, 8, 12, 13, 14})}); auto const second_last_element = tester.test_grouped_nth_element(-2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*second_last_element, fwcw<T>{{X, 0, 1, X, 3, X, // Group 0 X, X, X, 13, 14, 15, X, // Group 10 X, // Group 20 X}, // Group 30 cudf::test::iterators::nulls_at({0, 3, 5, 6, 7, 8, 12, 13, 14})}); // clang-format on } { // Too large values for `min_periods`. No window has enough periods. tester.preceding(2).following(1).min_periods(4); auto const all_null_values = fwcw<T>{{X, X, X, X, X, X, X, X, X, X, X, X, X, X, X}, cudf::test::iterators::all_nulls()}; auto const first_element = tester.test_grouped_nth_element(0); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*first_element, all_null_values); auto const last_element = tester.test_grouped_nth_element(-1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*last_element, all_null_values); auto const second_element = tester.test_grouped_nth_element(1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*second_element, all_null_values); auto const second_last_element = tester.test_grouped_nth_element(-2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*second_last_element, all_null_values); } } TYPED_TEST(NthElementTypedTest, EmptyInput) { using T = TypeParam; auto const group_col = fwcw<int32_t>{}; auto const input_col = fwcw<T>{}; auto tester = rolling_exec{}.grouping(group_col).input(input_col).preceding(3).following(1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*tester.test_grouped_nth_element(0), fwcw<T>{}); } TEST_F(NthElementTest, RollingWindowOnStrings) { using strings = cudf::test::strings_column_wrapper; auto constexpr X = ""; // Placeholder for null string. auto const input_col = strings{{"", "1", "22", "333", "4444", "", "10", "11", "12", "13", "14", "15", "16", "20"}, cudf::test::iterators::null_at(5)}; auto tester = rolling_exec{}.input(input_col); { // Window of 5 elements, min-periods == 1. tester.preceding(3).following(2).min_periods(1); auto const first_element = tester.test_nth_element(0); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *first_element, strings{{"", "", "", "1", "22", "333", "4444", X, "10", "11", "12", "13", "14", "15"}, cudf::test::iterators::null_at(7)}); auto const last_element = tester.test_nth_element(-1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *last_element, strings{{"22", "333", "4444", X, "10", "11", "12", "13", "14", "15", "16", "20", "20", "20"}, cudf::test::iterators::null_at(3)}); auto const third_element = tester.test_nth_element(2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *third_element, strings{{"22", "22", "22", "333", "4444", X, "10", "11", "12", "13", "14", "15", "16", "20"}, cudf::test::iterators::null_at(5)}); auto const second_last_element = tester.test_nth_element(-2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *second_last_element, strings{{"1", "22", "333", "4444", X, "10", "11", "12", "13", "14", "15", "16", "16", "16"}, cudf::test::iterators::null_at(4)}); } { // Window of 3 elements, min-periods == 3. Expect null elements at column margins. tester.preceding(2).following(1).min_periods(3); auto const first_element = tester.test_nth_element(0); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *first_element, strings{{X, "", "1", "22", "333", "4444", X, "10", "11", "12", "13", "14", "15", X}, cudf::test::iterators::nulls_at({0, 6, 13})}); auto const last_element = tester.test_nth_element(-1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *last_element, strings{{X, "22", "333", "4444", X, "10", "11", "12", "13", "14", "15", "16", "20", X}, cudf::test::iterators::nulls_at({0, 4, 13})}); auto const second_element = tester.test_nth_element(1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *second_element, strings{{X, "1", "22", "333", "4444", X, "10", "11", "12", "13", "14", "15", "16", X}, cudf::test::iterators::nulls_at({0, 5, 13})}); auto const second_last_element = tester.test_nth_element(-2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *second_last_element, strings{{X, "1", "22", "333", "4444", X, "10", "11", "12", "13", "14", "15", "16", X}, cudf::test::iterators::nulls_at({0, 5, 13})}); } { // Too large values for `min_periods`. No window has enough periods. tester.preceding(2).following(1).min_periods(4); auto const all_null_values = strings{{X, X, X, X, X, X, X, X, X, X, X, X, X, X}, cudf::test::iterators::all_nulls()}; auto const first_element = tester.test_nth_element(0); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*first_element, all_null_values); auto const last_element = tester.test_nth_element(-1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*last_element, all_null_values); auto const second_element = tester.test_nth_element(1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*second_element, all_null_values); auto const second_last_element = tester.test_nth_element(-2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*second_last_element, all_null_values); } } TEST_F(NthElementTest, GroupedRollingWindowForStrings) { using strings = cudf::test::strings_column_wrapper; auto constexpr X = ""; // Placeholder for null strings. // clang-format off auto const group_col = fwcw<int32_t>{0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 20}; auto const input_col = strings{{"", "1", "22", "333", "4444", X, // Group 0 "10", "11", "12", "13", "14", "15", "16", // Group 10 "20"}, // Group 20 cudf::test::iterators::null_at(5)}; // clang-format on auto tester = rolling_exec{}.grouping(group_col).input(input_col); { // Window of 5 elements, min-periods == 1. tester.preceding(3).following(2).min_periods(1); auto const first_element = tester.test_grouped_nth_element(0); // clang-format off CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *first_element, strings{{"", "", "", "1", "22", "333", // Group 0 "10", "10", "10", "11", "12", "13", "14", // Group 10 "20"}, // Group 20 cudf::test::iterators::no_nulls()}); auto const last_element = tester.test_grouped_nth_element(-1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *last_element, strings{{"22", "333", "4444", X, X, X, // Group 0 "12", "13", "14", "15", "16", "16", "16", // Group 10 "20"}, // Group 20 cudf::test::iterators::nulls_at({3, 4, 5})}); auto const third_element = tester.test_grouped_nth_element(2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *third_element, strings{{"22", "22", "22", "333", "4444", X, // Group 0 "12", "12", "12", "13", "14", "15", "16", // Group 10 X}, // Group 20 cudf::test::iterators::nulls_at({5, 13})}); auto const second_last_element = tester.test_grouped_nth_element(-2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *second_last_element, strings{{"1", "22", "333", "4444", "4444", "4444", // Group 0 "11", "12", "13", "14", "15", "15", "15", // Group 10 X}, // Group 20 cudf::test::iterators::null_at(13)}); // clang-format on } { // Window of 3 elements, min-periods == 3. Expect null elements at group margins. tester.preceding(2).following(1).min_periods(3); auto const first_element = tester.test_grouped_nth_element(0); // clang-format off CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *first_element, strings{{X, "", "1", "22", "333", X, // Group 0 X, "10", "11", "12", "13", "14", X, // Group 10 X}, // Group 20 cudf::test::iterators::nulls_at({0, 5, 6, 12, 13})}); auto const last_element = tester.test_grouped_nth_element(-1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *last_element, strings{{X, "22", "333", "4444", X, X, // Group 0 X, "12", "13", "14", "15", "16", X, // Group 10 X}, // Group 20 cudf::test::iterators::nulls_at({0, 4, 5, 6, 12, 13})}); auto const second_element = tester.test_grouped_nth_element(1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *second_element, strings{{X, "1", "22", "333", "4444", X, // Group 0 X, "11", "12", "13", "14", "15", X, // Group 10 X}, // Group 20 cudf::test::iterators::nulls_at({0, 5, 6, 12, 13})}); auto const second_last_element = tester.test_grouped_nth_element(-2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *second_last_element, strings{{X, "1", "22", "333", "4444", X, // Group 0 X, "11", "12", "13", "14", "15", X, // Group 10 X}, // Group 20 cudf::test::iterators::nulls_at({0, 5, 6, 12, 13})}); // clang-format on } { // Too large values for `min_periods`. No window has enough periods. tester.preceding(2).following(1).min_periods(4); auto const all_null_strings = strings{{X, X, X, X, X, X, X, X, X, X, X, X, X, X}, cudf::test::iterators::all_nulls()}; auto const first_element = tester.test_grouped_nth_element(0); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*first_element, all_null_strings); auto const last_element = tester.test_grouped_nth_element(-1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*last_element, all_null_strings); auto const second_element = tester.test_grouped_nth_element(1); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*second_element, all_null_strings); auto const second_last_element = tester.test_grouped_nth_element(-2); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*second_last_element, all_null_strings); } }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/rolling/grouped_rolling_range_test.cpp
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/aggregation.hpp> #include <cudf/column/column.hpp> #include <cudf/detail/aggregation/aggregation.hpp> #include <cudf/fixed_point/fixed_point.hpp> #include <cudf/null_mask.hpp> #include <cudf/rolling.hpp> #include <cudf/scalar/scalar_factories.hpp> #include <cudf/table/table_view.hpp> #include <cudf/utilities/bit.hpp> #include <thrust/host_vector.h> #include <thrust/iterator/counting_iterator.h> #include <algorithm> #include <vector> template <typename T> using fwcw = cudf::test::fixed_width_column_wrapper<T>; template <typename T> using decimals_column = cudf::test::fixed_point_column_wrapper<T>; using ints_column = fwcw<int32_t>; using bigints_column = fwcw<int64_t>; using strings_column = cudf::test::strings_column_wrapper; using column_ptr = std::unique_ptr<cudf::column>; template <typename T> struct BaseGroupedRollingRangeOrderByTest : cudf::test::BaseFixture { // Stand-in for std::pow(10, n), but for integral return. static constexpr std::array<int32_t, 6> pow10{1, 10, 100, 1000, 10000, 100000}; // Test data. column_ptr const grouping_keys = ints_column{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2}.release(); column_ptr const agg_values = ints_column{1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3}.release(); cudf::size_type const num_rows = grouping_keys->size(); /** * @brief Get grouped rolling results for specified order-by column and range bounds. */ [[nodiscard]] column_ptr get_grouped_range_rolling_result( cudf::range_window_bounds const& preceding, cudf::range_window_bounds const& following, cudf::column_view const& order_by_column, cudf::rolling_aggregation const& agg, cudf::order const& order = cudf::order::ASCENDING) const { return cudf::grouped_range_rolling_window(cudf::table_view{{grouping_keys->view()}}, order_by_column, order, agg_values->view(), preceding, following, 1, // min_periods agg); } [[nodiscard]] column_ptr get_grouped_range_rolling_sum_result( cudf::range_window_bounds const& preceding, cudf::range_window_bounds const& following, cudf::column_view const& order_by_column, cudf::order const& order = cudf::order::ASCENDING) const { return get_grouped_range_rolling_result( preceding, following, order_by_column, *cudf::make_sum_aggregation<cudf::rolling_aggregation>(), order); } }; template <typename T> struct GroupedRollingRangeOrderByNumericTest : public BaseGroupedRollingRangeOrderByTest<T> { using base = BaseGroupedRollingRangeOrderByTest<T>; using base::agg_values; using base::get_grouped_range_rolling_sum_result; using base::grouping_keys; using base::num_rows; static auto constexpr inf = std::numeric_limits<T>::infinity(); static auto constexpr nan = std::numeric_limits<T>::quiet_NaN(); [[nodiscard]] auto make_range_bounds(T const& value) const { return cudf::range_window_bounds::get(*cudf::make_fixed_width_scalar(value)); } [[nodiscard]] auto make_unbounded_range_bounds() const { return cudf::range_window_bounds::unbounded(cudf::data_type{cudf::type_to_id<T>()}); } /// Generate order-by column with values: [0, 100, 200, 300, ... 1100, 1200, 1300] [[nodiscard]] column_ptr generate_order_by_column() const { auto const begin = thrust::make_transform_iterator( thrust::make_counting_iterator<cudf::size_type>(0), [&](T const& i) -> T { return i * 100; }); return fwcw<T>(begin, begin + num_rows).release(); } /// Generate order-by column with values: [-1400, -1300, -1200 ... -300, -200, -100] [[nodiscard]] column_ptr generate_negative_order_by_column() const { auto const begin = thrust::make_transform_iterator(thrust::make_counting_iterator<cudf::size_type>(0), [&](T const& i) -> T { return (i - num_rows) * 100; }); return fwcw<T>(begin, begin + num_rows).release(); } /** * @brief Run grouped_rolling test with no nulls in the order-by column */ void run_test_no_null_oby() const { auto const preceding = make_range_bounds(T{200}); auto const following = make_range_bounds(T{100}); auto const order_by = generate_order_by_column(); auto const results = get_grouped_range_rolling_sum_result(preceding, following, *order_by); auto const expected_results = bigints_column{{2, 3, 4, 4, 4, 3, 4, 6, 8, 6, 6, 9, 12, 9}, cudf::test::iterators::no_nulls()}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_results); } /** * @brief Run grouped_rolling test with no nulls in the order-by column */ void run_test_negative_oby() const { auto const preceding = make_range_bounds(T{200}); auto const following = make_range_bounds(T{100}); auto const order_by = generate_negative_order_by_column(); auto const results = get_grouped_range_rolling_sum_result(preceding, following, *order_by); auto const expected_results = bigints_column{{2, 3, 4, 4, 4, 3, 4, 6, 8, 6, 6, 9, 12, 9}, cudf::test::iterators::no_nulls()}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_results); } /** * @brief Run grouped_rolling test with nulls in the order-by column * (i.e. 2 nulls at the beginning of each group) * */ void run_test_nulls_in_oby() const { auto const preceding = make_range_bounds(T{200}); auto const following = make_range_bounds(T{100}); // Nullify the first two rows of each group in the order_by column. auto const nulled_order_by = [&] { auto col = generate_order_by_column(); auto new_null_mask = create_null_mask(col->size(), cudf::mask_state::ALL_VALID); cudf::set_null_mask(static_cast<cudf::bitmask_type*>(new_null_mask.data()), 0, 2, false); // Nulls in first group. cudf::set_null_mask(static_cast<cudf::bitmask_type*>(new_null_mask.data()), 6, 8, false); // Nulls in second group. cudf::set_null_mask(static_cast<cudf::bitmask_type*>(new_null_mask.data()), 10, 12, false); // Nulls in third group. col->set_null_mask(std::move(new_null_mask), 6); return col; }(); auto const results = get_grouped_range_rolling_sum_result(preceding, following, *nulled_order_by); auto const expected_results = bigints_column{{2, 2, 2, 3, 4, 3, 4, 4, 4, 4, 6, 6, 6, 6}, cudf::test::iterators::no_nulls()}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_results); } /** * @brief Run grouped_rolling test with unbounded preceding and unbounded following. */ void run_test_unbounded_preceding_to_unbounded_following() { auto const order_by = generate_order_by_column(); auto const preceding = make_unbounded_range_bounds(); auto const following = make_unbounded_range_bounds(); auto const results = get_grouped_range_rolling_sum_result(preceding, following, *order_by); auto const expected_results = bigints_column{6, 6, 6, 6, 6, 6, 8, 8, 8, 8, 12, 12, 12, 12}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_results); } /** * @brief Run grouped_rolling test with unbounded preceding and current row. */ void run_test_unbounded_preceding_to_current_row() { auto const order_by = generate_order_by_column(); auto const unbounded_preceding = make_unbounded_range_bounds(); auto const current_row = make_range_bounds(T{0}); auto const results = get_grouped_range_rolling_sum_result(unbounded_preceding, current_row, *order_by); auto const expected_results = bigints_column{{1, 2, 3, 4, 5, 6, 2, 4, 6, 8, 3, 6, 9, 12}, cudf::test::iterators::no_nulls()}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_results); } /** * @brief Run grouped_rolling test with current row and unbounded following. */ void run_test_current_row_to_unbounded_following() { auto const order_by = generate_order_by_column(); auto const unbounded_following = make_unbounded_range_bounds(); auto const current_row = make_range_bounds(T{0}); auto const results = get_grouped_range_rolling_sum_result(current_row, unbounded_following, *order_by); auto const expected_results = bigints_column{{6, 5, 4, 3, 2, 1, 8, 6, 4, 2, 12, 9, 6, 3}, cudf::test::iterators::no_nulls()}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_results); } [[nodiscard]] column_ptr generate_ascending_order_by_NaNs_infinity() { auto const vec = std::vector<T>{-inf, -inf, -50, 0, 7, nan, -inf, 0, inf, nan, 0, inf, nan, nan}; return fwcw<T>(vec.begin(), vec.end()).release(); } void run_test_bounded_ascending_order_by_NaNs_infinity() { auto const order_by = generate_ascending_order_by_NaNs_infinity(); auto const preceding = make_range_bounds(T{200}); auto const following = make_range_bounds(T{100}); auto const results = get_grouped_range_rolling_sum_result(preceding, following, *order_by); auto const expected_results = bigints_column{{2, 2, 3, 3, 3, 1, 2, 2, 2, 2, 3, 3, 6, 6}, cudf::test::iterators::no_nulls()}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_results); } void run_test_unbounded_ascending_order_by_NaNs_infinity() { auto const order_by = generate_ascending_order_by_NaNs_infinity(); { // UNBOUNDED PRECEDING to CURRENT ROW. auto const preceding = make_unbounded_range_bounds(); auto const following = make_range_bounds(T{0}); auto const results = get_grouped_range_rolling_sum_result(preceding, following, *order_by); auto const expected_results = bigints_column{{2, 2, 3, 4, 5, 6, 2, 4, 6, 8, 3, 6, 12, 12}, cudf::test::iterators::no_nulls()}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_results); } { // CURRENT ROW to UNBOUNDED FOLLOWING auto const preceding = make_range_bounds(T{0}); auto const following = make_unbounded_range_bounds(); auto const results = get_grouped_range_rolling_sum_result(preceding, following, *order_by); auto const expected_results = bigints_column{{6, 6, 4, 3, 2, 1, 8, 6, 4, 2, 12, 9, 6, 6}, cudf::test::iterators::no_nulls()}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_results); } { // UNBOUNDED PRECEDING to UNBOUNDED FOLLOWING auto const preceding = make_unbounded_range_bounds(); auto const following = make_unbounded_range_bounds(); auto const results = get_grouped_range_rolling_sum_result(preceding, following, *order_by); auto const expected_results = bigints_column{6, 6, 6, 6, 6, 6, 8, 8, 8, 8, 12, 12, 12, 12}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_results); } } [[nodiscard]] column_ptr generate_descending_order_by_NaNs_infinity() { auto const vec = std::vector<T>{nan, 7, 0, -50, -inf, -inf, nan, inf, 0, -inf, nan, nan, inf, 0}; return fwcw<T>(vec.begin(), vec.end()).release(); } void run_test_bounded_descending_order_by_NaNs_infinity() { auto const order_by = generate_descending_order_by_NaNs_infinity(); auto const preceding = make_range_bounds(T{200}); auto const following = make_range_bounds(T{100}); auto const results = get_grouped_range_rolling_sum_result( preceding, following, *order_by, cudf::order::DESCENDING); auto const expected_results = bigints_column{{1, 3, 3, 3, 2, 2, 2, 2, 2, 2, 6, 6, 3, 3}, cudf::test::iterators::no_nulls()}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_results); } void run_test_unbounded_descending_order_by_NaNs_infinity() { auto const order_by = generate_descending_order_by_NaNs_infinity(); { // UNBOUNDED PRECEDING to CURRENT ROW. auto const preceding = make_unbounded_range_bounds(); auto const following = make_range_bounds(T{0}); auto const results = get_grouped_range_rolling_sum_result( preceding, following, *order_by, cudf::order::DESCENDING); auto const expected_results = bigints_column{{1, 2, 3, 4, 6, 6, 2, 4, 6, 8, 6, 6, 9, 12}, cudf::test::iterators::no_nulls()}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_results); } { // CURRENT ROW to UNBOUNDED FOLLOWING auto const preceding = make_range_bounds(T{0}); auto const following = make_unbounded_range_bounds(); auto const results = get_grouped_range_rolling_sum_result( preceding, following, *order_by, cudf::order::DESCENDING); auto const expected_results = bigints_column{{6, 5, 4, 3, 2, 2, 8, 6, 4, 2, 12, 12, 6, 3}, cudf::test::iterators::no_nulls()}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_results); } { // UNBOUNDED PRECEDING to UNBOUNDED FOLLOWING auto const preceding = make_unbounded_range_bounds(); auto const following = make_unbounded_range_bounds(); auto const results = get_grouped_range_rolling_sum_result( preceding, following, *order_by, cudf::order::DESCENDING); auto const expected_results = bigints_column{6, 6, 6, 6, 6, 6, 8, 8, 8, 8, 12, 12, 12, 12}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_results); } } }; template <typename FloatingPointType> struct GroupedRollingRangeOrderByFloatingPointTest : GroupedRollingRangeOrderByNumericTest<FloatingPointType> {}; TYPED_TEST_SUITE(GroupedRollingRangeOrderByFloatingPointTest, cudf::test::FloatingPointTypes); TYPED_TEST(GroupedRollingRangeOrderByFloatingPointTest, BoundedRanges) { this->run_test_no_null_oby(); this->run_test_negative_oby(); this->run_test_nulls_in_oby(); this->run_test_bounded_ascending_order_by_NaNs_infinity(); this->run_test_bounded_descending_order_by_NaNs_infinity(); } TYPED_TEST(GroupedRollingRangeOrderByFloatingPointTest, UnboundedRanges) { this->run_test_unbounded_preceding_to_unbounded_following(); this->run_test_unbounded_preceding_to_current_row(); this->run_test_current_row_to_unbounded_following(); this->run_test_unbounded_ascending_order_by_NaNs_infinity(); this->run_test_unbounded_descending_order_by_NaNs_infinity(); } template <typename DecimalT> struct GroupedRollingRangeOrderByDecimalTypedTest : BaseGroupedRollingRangeOrderByTest<typename DecimalT::rep> { using Rep = typename DecimalT::rep; using base = BaseGroupedRollingRangeOrderByTest<Rep>; using base::agg_values; using base::grouping_keys; using base::num_rows; [[nodiscard]] auto make_fixed_point_range_bounds(typename DecimalT::rep value, numeric::scale_type scale) const { return cudf::range_window_bounds::get(*cudf::make_fixed_point_scalar<DecimalT>(value, scale)); } [[nodiscard]] auto make_unbounded_fixed_point_range_bounds() const { return cudf::range_window_bounds::unbounded(cudf::data_type{cudf::type_to_id<DecimalT>()}); } /// For different scales, generate order_by column with /// the same effective values: [0, 100, 200, 300, ... 1100, 1200, 1300] /// For scale == -2, the rep values are: [0, 10000, 20000, 30000, ... 110000, 120000, 130000] /// For scale == 2, the rep values are: [0, 1, 2, 3, ... 11, 12, 13] [[nodiscard]] column_ptr generate_order_by_column(numeric::scale_type scale) const { auto const begin = thrust::make_transform_iterator( thrust::make_counting_iterator<Rep>(0), [&](auto i) -> Rep { return (i * 10000) / base::pow10[scale + 2]; }); return decimals_column<Rep>{begin, begin + num_rows, numeric::scale_type{scale}}.release(); } /** * @brief Scale the range bounds value to new scale, so that effective * value remains identical. * * Keeping the effective range bounds value identical ensures that * the expected result from grouped_rolling remains the same. */ [[nodiscard]] Rep rescale_range_value(Rep const& value_at_scale_0, numeric::scale_type new_scale) const { // Scale -> Rep (for value == 200) // -2 -> 20000 // -1 -> 2000 // 0 -> 200 // 1 -> 20 // 2 -> 2 return (value_at_scale_0 * 100) / base::pow10[new_scale + 2]; } /** * @brief Get grouped rolling results for specified order-by column and range scale * */ [[nodiscard]] column_ptr get_grouped_range_rolling_result( cudf::column_view const& order_by_column, numeric::scale_type const& range_scale) const { auto const preceding = this->make_fixed_point_range_bounds(rescale_range_value(Rep{200}, range_scale), range_scale); auto const following = this->make_fixed_point_range_bounds(rescale_range_value(Rep{100}, range_scale), range_scale); return base::get_grouped_range_rolling_sum_result(preceding, following, order_by_column); } /** * @brief Run grouped_rolling test for specified order-by column scale with * no nulls in the order-by column * */ void run_test_no_null_oby(numeric::scale_type const& order_by_column_scale) const { auto const order_by = generate_order_by_column(order_by_column_scale); // Run tests for range bounds generated for all scales >= oby_column_scale. for (int32_t range_scale = order_by_column_scale; range_scale <= 2; ++range_scale) { auto const results = get_grouped_range_rolling_result(*order_by, numeric::scale_type{range_scale}); auto const expected_results = bigints_column{{2, 3, 4, 4, 4, 3, 4, 6, 8, 6, 6, 9, 12, 9}, cudf::test::iterators::no_nulls()}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_results); } } /** * @brief Run grouped_rolling test for specified order-by column scale with * nulls in the order-by column (i.e. 2 nulls at the beginning of each group) * */ void run_test_nulls_in_oby(numeric::scale_type const& order_by_column_scale) const { // Nullify the first two rows of each group in the order_by column. auto const nulled_order_by = [&] { auto col = generate_order_by_column(order_by_column_scale); auto new_null_mask = create_null_mask(col->size(), cudf::mask_state::ALL_VALID); cudf::set_null_mask(static_cast<cudf::bitmask_type*>(new_null_mask.data()), 0, 2, false); // Nulls in first group. cudf::set_null_mask(static_cast<cudf::bitmask_type*>(new_null_mask.data()), 6, 8, false); // Nulls in second group. cudf::set_null_mask(static_cast<cudf::bitmask_type*>(new_null_mask.data()), 10, 12, false); // Nulls in third group. col->set_null_mask(std::move(new_null_mask), 6); return col; }(); // Run tests for range bounds generated for all scales >= oby_column_scale. for (auto range_scale = int32_t{order_by_column_scale}; range_scale <= 2; ++range_scale) { auto const results = get_grouped_range_rolling_result(*nulled_order_by, numeric::scale_type{range_scale}); auto const expected_results = bigints_column{{2, 2, 2, 3, 4, 3, 4, 4, 4, 4, 6, 6, 6, 6}, cudf::test::iterators::no_nulls()}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_results); } } /** * @brief Run grouped_rolling test for specified order-by column scale with * unbounded preceding and unbounded following. * */ void run_test_unbounded_preceding_to_unbounded_following(numeric::scale_type oby_column_scale) { auto const order_by = generate_order_by_column(oby_column_scale); auto const preceding = make_unbounded_fixed_point_range_bounds(); auto const following = make_unbounded_fixed_point_range_bounds(); auto results = cudf::grouped_range_rolling_window(cudf::table_view{{grouping_keys->view()}}, order_by->view(), cudf::order::ASCENDING, agg_values->view(), preceding, following, 1, // min_periods *cudf::make_sum_aggregation<cudf::rolling_aggregation>()); auto expected_results = bigints_column{6, 6, 6, 6, 6, 6, 8, 8, 8, 8, 12, 12, 12, 12}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_results); } /** * @brief Run grouped_rolling test for specified order-by column scale with * unbounded preceding and current row. * */ void run_test_unbounded_preceding_to_current_row(numeric::scale_type oby_column_scale) { auto const order_by = generate_order_by_column(oby_column_scale); auto const unbounded_preceding = make_unbounded_fixed_point_range_bounds(); for (int32_t range_scale = oby_column_scale; range_scale <= 2; ++range_scale) { auto const current_row = make_fixed_point_range_bounds(rescale_range_value(Rep{0}, numeric::scale_type{range_scale}), numeric::scale_type{range_scale}); auto const results = cudf::grouped_range_rolling_window( cudf::table_view{{grouping_keys->view()}}, order_by->view(), cudf::order::ASCENDING, agg_values->view(), unbounded_preceding, current_row, 1, // min_periods *cudf::make_sum_aggregation<cudf::rolling_aggregation>()); auto expected_results = bigints_column{{1, 2, 3, 4, 5, 6, 2, 4, 6, 8, 3, 6, 9, 12}, cudf::test::iterators::no_nulls()}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_results); } } /** * @brief Run grouped_rolling test for specified order-by column scale with * current row and unbounded following. * */ void run_test_current_row_to_unbounded_following(numeric::scale_type oby_column_scale) { auto const order_by = generate_order_by_column(oby_column_scale); auto const unbounded_following = make_unbounded_fixed_point_range_bounds(); for (int32_t range_scale = oby_column_scale; range_scale <= 2; ++range_scale) { auto const current_row = make_fixed_point_range_bounds(rescale_range_value(Rep{0}, numeric::scale_type{range_scale}), numeric::scale_type{range_scale}); auto const results = cudf::grouped_range_rolling_window( cudf::table_view{{grouping_keys->view()}}, order_by->view(), cudf::order::ASCENDING, agg_values->view(), current_row, unbounded_following, 1, // min_periods *cudf::make_sum_aggregation<cudf::rolling_aggregation>()); auto expected_results = bigints_column{{6, 5, 4, 3, 2, 1, 8, 6, 4, 2, 12, 9, 6, 3}, cudf::test::iterators::no_nulls()}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_results); } } }; TYPED_TEST_SUITE(GroupedRollingRangeOrderByDecimalTypedTest, cudf::test::FixedPointTypes); TYPED_TEST(GroupedRollingRangeOrderByDecimalTypedTest, BoundedRanges) { for (auto const order_by_column_scale : {-2, -1, 0, 1, 2}) { auto const oby_scale = numeric::scale_type{order_by_column_scale}; this->run_test_no_null_oby(oby_scale); this->run_test_nulls_in_oby(oby_scale); } } TYPED_TEST(GroupedRollingRangeOrderByDecimalTypedTest, UnboundedRanges) { for (auto const order_by_scale : {-2, -1, 0, 1, 2}) { auto const order_by_column_scale = numeric::scale_type{order_by_scale}; this->run_test_unbounded_preceding_to_unbounded_following(order_by_column_scale); this->run_test_unbounded_preceding_to_current_row(order_by_column_scale); this->run_test_current_row_to_unbounded_following(order_by_column_scale); } } struct GroupedRollingRangeOrderByStringTest : public cudf::test::BaseFixture { // Test data. column_ptr const grouping_keys = ints_column{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2}.release(); column_ptr const agg_values = ints_column{1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3}.release(); cudf::size_type const num_rows = grouping_keys->size(); cudf::size_type const min_periods = 1; cudf::data_type const string_type{cudf::type_id::STRING}; cudf::range_window_bounds const unbounded_preceding = cudf::range_window_bounds::unbounded(string_type); cudf::range_window_bounds const unbounded_following = cudf::range_window_bounds::unbounded(string_type); cudf::range_window_bounds const current_row = cudf::range_window_bounds::current_row(string_type); [[nodiscard]] static auto nullable_ints_column(std::initializer_list<int> const& ints) { return ints_column{ints, cudf::test::iterators::no_nulls()}; } [[nodiscard]] auto get_count_over_partitioned_window( cudf::column_view const& order_by, cudf::order const& order, cudf::range_window_bounds const& preceding, cudf::range_window_bounds const& following) const { return cudf::grouped_range_rolling_window( cudf::table_view{{*grouping_keys}}, order_by, order, *agg_values, preceding, following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); } [[nodiscard]] auto get_count_over_unpartitioned_window( cudf::column_view const& order_by, cudf::order const& order, cudf::range_window_bounds const& preceding, cudf::range_window_bounds const& following) const { return cudf::grouped_range_rolling_window( cudf::table_view{std::vector<cudf::column_view>{}}, order_by, order, *agg_values, preceding, following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); } }; TEST_F(GroupedRollingRangeOrderByStringTest, Ascending_Partitioned_NoNulls) { // clang-format off auto const orderby = strings_column{ "A", "A", "A", "B", "B", "B", // Group 0. "C", "C", "C", "C", // Group 1. "D", "D", "E", "E" // Group 2. }.release(); // clang-format on // Partitioned cases. CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_partitioned_window( *orderby, cudf::order::ASCENDING, unbounded_preceding, current_row), nullable_ints_column({3, 3, 3, 6, 6, 6, 4, 4, 4, 4, 2, 2, 4, 4})); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_partitioned_window( *orderby, cudf::order::ASCENDING, current_row, unbounded_following), nullable_ints_column({6, 6, 6, 3, 3, 3, 4, 4, 4, 4, 4, 4, 2, 2})); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_partitioned_window( *orderby, cudf::order::ASCENDING, unbounded_preceding, unbounded_following), ints_column{6, 6, 6, 6, 6, 6, 4, 4, 4, 4, 4, 4, 4, 4}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_partitioned_window(*orderby, cudf::order::ASCENDING, current_row, current_row), nullable_ints_column({3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 2, 2, 2, 2})); } TEST_F(GroupedRollingRangeOrderByStringTest, Ascending_NoParts_NoNulls) { // clang-format off auto const orderby = strings_column{ "A", "A", "A", "B", "B", "B", "C", "C", "C", "C", "D", "D", "E", "E" }.release(); // clang-format on // Un-partitioned cases. CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_unpartitioned_window( *orderby, cudf::order::ASCENDING, unbounded_preceding, current_row), nullable_ints_column({3, 3, 3, 6, 6, 6, 10, 10, 10, 10, 12, 12, 14, 14})); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_unpartitioned_window( *orderby, cudf::order::ASCENDING, current_row, unbounded_following), nullable_ints_column({14, 14, 14, 11, 11, 11, 8, 8, 8, 8, 4, 4, 2, 2})); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_unpartitioned_window( *orderby, cudf::order::ASCENDING, unbounded_preceding, unbounded_following), ints_column{14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*get_count_over_unpartitioned_window( *orderby, cudf::order::ASCENDING, current_row, current_row), nullable_ints_column({3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 2, 2, 2, 2})); } TEST_F(GroupedRollingRangeOrderByStringTest, Ascending_Partitioned_WithNulls) { // clang-format off auto const orderby = strings_column{ { "X", "X", "X", "B", "B", "B", // Group 0. "C", "C", "C", "C", // Group 1. "X", "X", "E", "E" // Group 2. }, cudf::test::iterators::nulls_at({0, 1, 2, 10, 11}) }.release(); // clang-format on // Partitioned cases. CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_partitioned_window( *orderby, cudf::order::ASCENDING, unbounded_preceding, current_row), nullable_ints_column({3, 3, 3, 6, 6, 6, 4, 4, 4, 4, 2, 2, 4, 4})); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_partitioned_window( *orderby, cudf::order::ASCENDING, current_row, unbounded_following), nullable_ints_column({6, 6, 6, 3, 3, 3, 4, 4, 4, 4, 4, 4, 2, 2})); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_partitioned_window( *orderby, cudf::order::ASCENDING, unbounded_preceding, unbounded_following), ints_column{6, 6, 6, 6, 6, 6, 4, 4, 4, 4, 4, 4, 4, 4}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_partitioned_window(*orderby, cudf::order::ASCENDING, current_row, current_row), nullable_ints_column({3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 2, 2, 2, 2})); } TEST_F(GroupedRollingRangeOrderByStringTest, Ascending_NoParts_WithNulls) { // Un-partitioned cases. Null values have to be clustered together. // clang-format off auto const orderby = strings_column{ { "X", "X", "X", "B", "B", "B", "C", "C", "C", "C", "D", "D", "E", "E" }, cudf::test::iterators::nulls_at({0, 1, 2}) }.release(); // clang-format on CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_unpartitioned_window( *orderby, cudf::order::ASCENDING, unbounded_preceding, current_row), nullable_ints_column({3, 3, 3, 6, 6, 6, 10, 10, 10, 10, 12, 12, 14, 14})); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_unpartitioned_window( *orderby, cudf::order::ASCENDING, current_row, unbounded_following), nullable_ints_column({14, 14, 14, 11, 11, 11, 8, 8, 8, 8, 4, 4, 2, 2})); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_unpartitioned_window( *orderby, cudf::order::ASCENDING, unbounded_preceding, unbounded_following), ints_column{14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*get_count_over_unpartitioned_window( *orderby, cudf::order::ASCENDING, current_row, current_row), nullable_ints_column({3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 2, 2, 2, 2})); } TEST_F(GroupedRollingRangeOrderByStringTest, Descending_Partitioned_NoNulls) { // clang-format off auto const orderby = strings_column{ "B", "B", "B", "A", "A", "A", // Group 0. "C", "C", "C", "C", // Group 1. "E", "E", "D", "D" // Group 2. }.release(); // clang-format on // Partitioned cases. CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_partitioned_window( *orderby, cudf::order::DESCENDING, unbounded_preceding, current_row), nullable_ints_column({3, 3, 3, 6, 6, 6, 4, 4, 4, 4, 2, 2, 4, 4})); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_partitioned_window( *orderby, cudf::order::DESCENDING, current_row, unbounded_following), nullable_ints_column({6, 6, 6, 3, 3, 3, 4, 4, 4, 4, 4, 4, 2, 2})); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_partitioned_window( *orderby, cudf::order::DESCENDING, unbounded_preceding, unbounded_following), ints_column{6, 6, 6, 6, 6, 6, 4, 4, 4, 4, 4, 4, 4, 4}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_partitioned_window(*orderby, cudf::order::DESCENDING, current_row, current_row), nullable_ints_column({3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 2, 2, 2, 2})); } TEST_F(GroupedRollingRangeOrderByStringTest, Descending_NoParts_NoNulls) { // Un-partitioned cases. Order-by column must be entirely in descending order. // clang-format off auto const orderby = strings_column{ "E", "E", "E", "D", "D", "D", "C", "C", "C", "C", "B", "B", "A", "A" }.release(); // clang-format on CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_unpartitioned_window( *orderby, cudf::order::DESCENDING, unbounded_preceding, current_row), nullable_ints_column({3, 3, 3, 6, 6, 6, 10, 10, 10, 10, 12, 12, 14, 14})); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_unpartitioned_window( *orderby, cudf::order::DESCENDING, current_row, unbounded_following), nullable_ints_column({14, 14, 14, 11, 11, 11, 8, 8, 8, 8, 4, 4, 2, 2})); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_unpartitioned_window( *orderby, cudf::order::DESCENDING, unbounded_preceding, unbounded_following), ints_column{14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*get_count_over_unpartitioned_window( *orderby, cudf::order::DESCENDING, current_row, current_row), nullable_ints_column({3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 2, 2, 2, 2})); } TEST_F(GroupedRollingRangeOrderByStringTest, Descending_Partitioned_WithNulls) { // clang-format off auto const orderby = strings_column{ { "X", "X", "X", "A", "A", "A", // Group 0. "C", "C", "C", "C", // Group 1. "X", "X", "D", "D" // Group 2. }, cudf::test::iterators::nulls_at({0, 1, 2, 10, 11}) }.release(); // clang-format on CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_partitioned_window( *orderby, cudf::order::DESCENDING, unbounded_preceding, current_row), nullable_ints_column({3, 3, 3, 6, 6, 6, 4, 4, 4, 4, 2, 2, 4, 4})); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_partitioned_window( *orderby, cudf::order::DESCENDING, current_row, unbounded_following), nullable_ints_column({6, 6, 6, 3, 3, 3, 4, 4, 4, 4, 4, 4, 2, 2})); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_partitioned_window( *orderby, cudf::order::DESCENDING, unbounded_preceding, unbounded_following), ints_column{6, 6, 6, 6, 6, 6, 4, 4, 4, 4, 4, 4, 4, 4}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_partitioned_window(*orderby, cudf::order::DESCENDING, current_row, current_row), nullable_ints_column({3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 2, 2, 2, 2})); } TEST_F(GroupedRollingRangeOrderByStringTest, Descending_NoParts_WithNulls) { // Order-by column must be ordered completely in descending. // clang-format off auto const orderby = strings_column{ { "X", "X", "X", "D", "D", "D", "C", "C", "C", "C", "B", "B", "A", "A" }, cudf::test::iterators::nulls_at({0, 1, 2}) }.release(); // clang-format on CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_unpartitioned_window( *orderby, cudf::order::DESCENDING, unbounded_preceding, current_row), nullable_ints_column({3, 3, 3, 6, 6, 6, 10, 10, 10, 10, 12, 12, 14, 14})); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_unpartitioned_window( *orderby, cudf::order::DESCENDING, current_row, unbounded_following), nullable_ints_column({14, 14, 14, 11, 11, 11, 8, 8, 8, 8, 4, 4, 2, 2})); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *get_count_over_unpartitioned_window( *orderby, cudf::order::DESCENDING, unbounded_preceding, unbounded_following), ints_column{14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*get_count_over_unpartitioned_window( *orderby, cudf::order::DESCENDING, current_row, current_row), nullable_ints_column({3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 2, 2, 2, 2})); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/rolling/range_rolling_window_test.cpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/aggregation.hpp> #include <cudf/detail/aggregation/aggregation.hpp> #include <cudf/rolling.hpp> #include <cudf/table/table_view.hpp> #include <cudf/unary.hpp> #include <cudf/utilities/bit.hpp> #include <src/rolling/detail/range_window_bounds.hpp> #include <src/rolling/detail/rolling.hpp> #include <thrust/iterator/constant_iterator.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/iterator/transform_iterator.h> #include <vector> template <typename T, typename R = int32_t> using fwcw = cudf::test::fixed_width_column_wrapper<T>; using int_col = fwcw<int32_t>; using size_col = fwcw<cudf::size_type>; template <typename T, typename R = typename T::rep> using time_col = fwcw<T, R>; using lists_col = cudf::test::lists_column_wrapper<int32_t>; template <typename ScalarT> struct window_exec { public: window_exec(cudf::column_view gby, cudf::column_view oby, cudf::order ordering, cudf::column_view agg, ScalarT preceding_scalar, ScalarT following_scalar, cudf::size_type min_periods = 1) : gby_column(gby), oby_column(oby), order(ordering), agg_column(agg), preceding(preceding_scalar), following(following_scalar), min_periods(min_periods) { } cudf::size_type num_rows() { return gby_column.size(); } std::unique_ptr<cudf::column> operator()( std::unique_ptr<cudf::rolling_aggregation> const& agg) const { auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{gby_column}}; return cudf::grouped_range_rolling_window(grouping_keys, oby_column, order, agg_column, cudf::range_window_bounds::get(preceding), cudf::range_window_bounds::get(following), min_periods, *agg); } private: cudf::column_view gby_column; // Groupby column. cudf::column_view oby_column; // Orderby column. cudf::order order; // Ordering for `oby_column`. cudf::column_view agg_column; // Aggregation column. ScalarT preceding; // Preceding window scalar. ScalarT following; // Following window scalar. cudf::size_type min_periods = 1; }; // struct window_exec; struct RangeRollingTest : public cudf::test::BaseFixture {}; template <typename T> struct TypedTimeRangeRollingTest : RangeRollingTest {}; TYPED_TEST_SUITE(TypedTimeRangeRollingTest, cudf::test::TimestampTypes); template <typename WindowExecT> void verify_results_for_ascending(WindowExecT exec) { auto const n_rows = exec.num_rows(); auto const all_valid = thrust::make_constant_iterator<bool>(true); auto const all_invalid = thrust::make_constant_iterator<bool>(false); auto const last_invalid = thrust::make_transform_iterator( thrust::make_counting_iterator(0), [&n_rows](auto i) { return i != (n_rows - 1); }); CUDF_TEST_EXPECT_COLUMNS_EQUAL( exec(cudf::make_count_aggregation<cudf::rolling_aggregation>(cudf::null_policy::INCLUDE)) ->view(), size_col{{1, 2, 2, 3, 2, 3, 3, 4, 4, 1}, all_valid}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( exec(cudf::make_count_aggregation<cudf::rolling_aggregation>())->view(), size_col{{1, 2, 2, 3, 2, 3, 3, 4, 4, 0}, all_valid}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( exec(cudf::make_sum_aggregation<cudf::rolling_aggregation>())->view(), fwcw<int64_t>{{0, 12, 12, 12, 8, 17, 17, 18, 18, 1}, last_invalid}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( exec(cudf::make_min_aggregation<cudf::rolling_aggregation>())->view(), int_col{{0, 4, 4, 2, 2, 3, 3, 1, 1, 1}, last_invalid}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( exec(cudf::make_max_aggregation<cudf::rolling_aggregation>())->view(), int_col{{0, 8, 8, 6, 6, 9, 9, 9, 9, 1}, last_invalid}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( exec(cudf::make_mean_aggregation<cudf::rolling_aggregation>())->view(), fwcw<double>{{0.0, 6.0, 6.0, 4.0, 4.0, 17.0 / 3, 17.0 / 3, 4.5, 4.5, 1.0}, last_invalid}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( exec(cudf::make_collect_list_aggregation<cudf::rolling_aggregation>())->view(), lists_col{{{0}, {8, 4}, {8, 4}, {4, 6, 2}, {6, 2}, {9, 3, 5}, {9, 3, 5}, {9, 3, 5, 1}, {9, 3, 5, 1}, {{0}, all_invalid}}, all_valid}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( exec(cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)) ->view(), lists_col{{{0}, {8, 4}, {8, 4}, {4, 6, 2}, {6, 2}, {9, 3, 5}, {9, 3, 5}, {9, 3, 5, 1}, {9, 3, 5, 1}, {}}, all_valid}); } TYPED_TEST(TypedTimeRangeRollingTest, TimestampASC) { // Confirm that timestamp columns can be used in range queries // at all resolutions, given the right duration column type. using TimeT = TypeParam; using DurationT = cudf::detail::range_type<TimeT>; using time_col = fwcw<TimeT>; // clang-format off auto gby_column = int_col { 0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; auto agg_column = int_col {{0, 8, 4, 6, 2, 9, 3, 5, 1, 7}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 0}}; auto time_column = time_col{ 1, 5, 6, 8, 9, 2, 2, 3, 4, 9}; // clang-format on auto exec = window_exec(gby_column, time_column, cudf::order::ASCENDING, agg_column, cudf::duration_scalar<DurationT>{DurationT{2}, true}, // 2 "durations" preceding. cudf::duration_scalar<DurationT>{DurationT{1}, true}); // 1 "durations" following. verify_results_for_ascending(exec); } template <typename WindowExecT> void verify_results_for_descending(WindowExecT exec) { auto const all_valid = thrust::make_constant_iterator<bool>(true); auto const all_invalid = thrust::make_constant_iterator<bool>(false); auto const first_invalid = thrust::make_transform_iterator(thrust::make_counting_iterator(0), [](auto i) { return i != 0; }); CUDF_TEST_EXPECT_COLUMNS_EQUAL( exec(cudf::make_count_aggregation<cudf::rolling_aggregation>(cudf::null_policy::INCLUDE)) ->view(), size_col{{1, 4, 4, 3, 3, 2, 3, 2, 2, 1}, all_valid}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( exec(cudf::make_count_aggregation<cudf::rolling_aggregation>())->view(), size_col{{0, 4, 4, 3, 3, 2, 3, 2, 2, 1}, all_valid}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( exec(cudf::make_sum_aggregation<cudf::rolling_aggregation>())->view(), fwcw<int64_t>{{1, 18, 18, 17, 17, 8, 12, 12, 12, 0}, first_invalid}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( exec(cudf::make_min_aggregation<cudf::rolling_aggregation>())->view(), int_col{{1, 1, 1, 3, 3, 2, 2, 4, 4, 0}, first_invalid}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( exec(cudf::make_max_aggregation<cudf::rolling_aggregation>())->view(), int_col{{1, 9, 9, 9, 9, 6, 6, 8, 8, 0}, first_invalid}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( exec(cudf::make_mean_aggregation<cudf::rolling_aggregation>())->view(), fwcw<double>{{1.0, 4.5, 4.5, 17.0 / 3, 17.0 / 3, 4.0, 4.0, 6.0, 6.0, 0.0}, first_invalid}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( exec(cudf::make_collect_list_aggregation<cudf::rolling_aggregation>())->view(), lists_col{{{{0}, all_invalid}, {1, 5, 3, 9}, {1, 5, 3, 9}, {5, 3, 9}, {5, 3, 9}, {2, 6}, {2, 6, 4}, {4, 8}, {4, 8}, {0}}, all_valid}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( exec(cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)) ->view(), lists_col{{{}, {1, 5, 3, 9}, {1, 5, 3, 9}, {5, 3, 9}, {5, 3, 9}, {2, 6}, {2, 6, 4}, {4, 8}, {4, 8}, {0}}, all_valid}); } TYPED_TEST(TypedTimeRangeRollingTest, TimestampDESC) { // Confirm that timestamp columns can be used in range queries // at all resolutions, given the right duration column type. using TimeT = TypeParam; using DurationT = cudf::detail::range_type<TimeT>; using time_col = fwcw<TimeT>; // clang-format off auto gby_column = int_col { 5, 5, 5, 5, 5, 1, 1, 1, 1, 1}; auto agg_column = int_col {{7, 1, 5, 3, 9, 2, 6, 4, 8, 0}, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1}}; auto time_column = time_col{ 9, 4, 3, 2, 2, 9, 8, 6, 5, 1}; // clang-format on auto exec = window_exec(gby_column, time_column, cudf::order::DESCENDING, agg_column, cudf::duration_scalar<DurationT>{DurationT{1}, true}, // 1 "durations" preceding. cudf::duration_scalar<DurationT>{DurationT{2}, true}); // 2 "durations" following. verify_results_for_descending(exec); } template <typename T> struct TypedIntegralRangeRollingTest : RangeRollingTest {}; TYPED_TEST_SUITE(TypedIntegralRangeRollingTest, cudf::test::IntegralTypesNotBool); TYPED_TEST(TypedIntegralRangeRollingTest, OrderByASC) { // Confirm that integral ranges work with integral orderby columns, // in ascending order. using T = TypeParam; // clang-format off auto gby_column = int_col { 0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; auto agg_column = int_col {{0, 8, 4, 6, 2, 9, 3, 5, 1, 7}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 0}}; auto oby_column = fwcw<T>{ 1, 5, 6, 8, 9, 2, 2, 3, 4, 9}; // clang-format on auto exec = window_exec(gby_column, oby_column, cudf::order::ASCENDING, agg_column, cudf::numeric_scalar<T>(2), // 2 preceding. cudf::numeric_scalar<T>(1)); // 1 following. verify_results_for_ascending(exec); } TYPED_TEST(TypedIntegralRangeRollingTest, OrderByDesc) { // Confirm that integral ranges work with integral orderby columns, // in descending order. using T = TypeParam; // clang-format off auto gby_column = int_col { 5, 5, 5, 5, 5, 1, 1, 1, 1, 1}; auto agg_column = int_col {{7, 1, 5, 3, 9, 2, 6, 4, 8, 0}, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1}}; auto oby_column = fwcw<T>{ 9, 4, 3, 2, 2, 9, 8, 6, 5, 1}; // clang-format on auto exec = window_exec(gby_column, oby_column, cudf::order::DESCENDING, agg_column, cudf::numeric_scalar<T>(1), // 1 preceding. cudf::numeric_scalar<T>(2)); // 2 following. verify_results_for_descending(exec); } template <typename T> struct TypedRangeRollingNullsTest : public RangeRollingTest {}; using TypesUnderTest = cudf::test::IntegralTypesNotBool; TYPED_TEST_SUITE(TypedRangeRollingNullsTest, TypesUnderTest); template <typename T> auto do_count_over_window(cudf::column_view grouping_col, cudf::column_view order_by, cudf::order order, cudf::column_view aggregation_col, cudf::range_window_bounds&& preceding = cudf::range_window_bounds::get(cudf::numeric_scalar<T>{T{1}, true}), cudf::range_window_bounds&& following = cudf::range_window_bounds::get(cudf::numeric_scalar<T>{T{1}, true})) { auto const min_periods = cudf::size_type{1}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grouping_col}}; return cudf::grouped_range_rolling_window( grouping_keys, order_by, order, aggregation_col, std::move(preceding), std::move(following), min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); } TYPED_TEST(TypedRangeRollingNullsTest, CountSingleGroupOrderByASCNullsFirst) { using T = TypeParam; // Groupby column. auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Aggregation column. auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; // OrderBy column. auto const oby_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 0, 0, 0, 1, 1, 1, 1, 1, 1}}; auto const output = do_count_over_window<T>(grp_col, oby_col, cudf::order::ASCENDING, agg_col); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {4, 4, 4, 4, 1, 2, 2, 3, 3, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedRangeRollingNullsTest, CountSingleGroupOrderByASCNullsLast) { using T = TypeParam; // Groupby column. auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Aggregation column. auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; // OrderBy column. auto const oby_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 1, 0, 0, 0, 0}}; auto const output = do_count_over_window<T>(grp_col, oby_col, cudf::order::ASCENDING, agg_col); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {2, 3, 3, 3, 2, 1, 4, 4, 4, 4}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedRangeRollingNullsTest, CountMultiGroupOrderByASCNullsFirst) { using T = TypeParam; // Groupby column. auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; // Aggregation column. auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // OrderBy column. auto const oby_col = cudf::test::fixed_width_column_wrapper<T>{{1, 2, 2, 1, 2, 1, 2, 3, 4, 5}, {0, 0, 0, 1, 1, 0, 0, 1, 1, 1}}; auto const output = do_count_over_window<T>(grp_col, oby_col, cudf::order::ASCENDING, agg_col); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {3, 3, 3, 2, 2, 2, 2, 2, 3, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedRangeRollingNullsTest, CountMultiGroupOrderByASCNullsLast) { using T = int32_t; // Groupby column. auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; // Aggregation column. auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // OrderBy column. auto const oby_col = cudf::test::fixed_width_column_wrapper<T>{{1, 2, 2, 1, 3, 1, 2, 3, 4, 5}, {1, 1, 1, 0, 0, 1, 1, 1, 0, 0}}; auto const output = do_count_over_window<T>(grp_col, oby_col, cudf::order::ASCENDING, agg_col); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {3, 3, 3, 2, 2, 2, 3, 2, 2, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedRangeRollingNullsTest, CountSingleGroupOrderByDESCNullsFirst) { using T = TypeParam; // Groupby column. auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Aggregation column. auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; // OrderBy column. auto const oby_col = cudf::test::fixed_width_column_wrapper<T>{{9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, {0, 0, 0, 0, 1, 1, 1, 1, 1, 1}}; auto const output = do_count_over_window<T>(grp_col, oby_col, cudf::order::DESCENDING, agg_col); ; CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {4, 4, 4, 4, 1, 2, 2, 3, 3, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedRangeRollingNullsTest, CountSingleGroupOrderByDESCNullsLast) { using T = TypeParam; // Groupby column. auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Aggregation column. auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; // OrderBy column. auto const oby_col = cudf::test::fixed_width_column_wrapper<T>{{9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, {1, 1, 1, 1, 1, 1, 0, 0, 0, 0}}; auto const output = do_count_over_window<T>(grp_col, oby_col, cudf::order::DESCENDING, agg_col); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {2, 3, 3, 3, 2, 1, 4, 4, 4, 4}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedRangeRollingNullsTest, CountMultiGroupOrderByDESCNullsFirst) { using T = TypeParam; // Groupby column. auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; // Aggregation column. auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // OrderBy column. auto const oby_col = cudf::test::fixed_width_column_wrapper<T>{{4, 3, 2, 1, 0, 9, 8, 7, 6, 5}, {0, 0, 0, 1, 1, 0, 0, 1, 1, 1}}; auto const output = do_count_over_window<T>(grp_col, oby_col, cudf::order::DESCENDING, agg_col); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {3, 3, 3, 2, 2, 2, 2, 2, 3, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedRangeRollingNullsTest, CountMultiGroupOrderByDESCNullsLast) { using T = TypeParam; // Groupby column. auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; // Aggregation column. auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // OrderBy column. auto const oby_col = cudf::test::fixed_width_column_wrapper<T>{{4, 3, 2, 1, 0, 9, 8, 7, 6, 5}, {1, 1, 1, 0, 0, 1, 1, 1, 0, 0}}; auto const output = do_count_over_window<T>(grp_col, oby_col, cudf::order::DESCENDING, agg_col); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {2, 3, 2, 2, 2, 2, 3, 2, 2, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedRangeRollingNullsTest, CountSingleGroupAllNullOrderBys) { using T = TypeParam; // Groupby column. auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Aggregation column. auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; // OrderBy column. auto const oby_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}; auto const output = do_count_over_window<T>(grp_col, oby_col, cudf::order::ASCENDING, agg_col); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {9, 9, 9, 9, 9, 9, 9, 9, 9, 9}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedRangeRollingNullsTest, CountMultiGroupAllNullOrderBys) { using T = TypeParam; // Groupby column. auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; // Aggregation column. auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; // OrderBy column. auto const oby_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 0, 0, 0, 0}}; auto const output = do_count_over_window<T>(grp_col, oby_col, cudf::order::ASCENDING, agg_col); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {2, 3, 3, 3, 2, 4, 4, 4, 4, 4}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedRangeRollingNullsTest, UnboundedPrecedingWindowSingleGroupOrderByASCNullsFirst) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const oby_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 0, 0, 0, 1, 1, 1, 1, 1, 1}}; auto const output = do_count_over_window<T>( grp_col, oby_col, cudf::order::ASCENDING, agg_col, cudf::range_window_bounds::unbounded(cudf::data_type{cudf::type_to_id<T>()}), cudf::range_window_bounds::get(cudf::numeric_scalar<T>{1, true})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {4, 4, 4, 4, 5, 6, 7, 8, 9, 9}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedRangeRollingNullsTest, UnboundedFollowingWindowSingleGroupOrderByASCNullsFirst) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const oby_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 0, 0, 0, 1, 1, 1, 1, 1, 1}}; auto const output = do_count_over_window<T>( grp_col, oby_col, cudf::order::ASCENDING, agg_col, cudf::range_window_bounds::get(cudf::numeric_scalar<T>{1, true}), cudf::range_window_bounds::unbounded(cudf::data_type{cudf::type_to_id<T>()})); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {9, 9, 9, 9, 5, 5, 4, 4, 3, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/rolling/grouped_rolling_test.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 "rolling_test.hpp" #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/aggregation.hpp> #include <cudf/detail/aggregation/aggregation.hpp> #include <cudf/rolling.hpp> #include <cudf/table/table_view.hpp> #include <cudf/utilities/bit.hpp> #include <src/rolling/detail/rolling.hpp> #include <thrust/host_vector.h> #include <thrust/iterator/counting_iterator.h> const std::string cuda_func{ R"***( template <typename OutType, typename InType> __device__ void CUDA_GENERIC_AGGREGATOR(OutType *ret, InType *in_col, cudf::size_type start, cudf::size_type count) { OutType val = 0; for (cudf::size_type i = 0; i < count; i++) { val += in_col[start + i]; } *ret = val; } )***"}; const std::string ptx_func{ R"***( // // Generated by NVIDIA NVVM Compiler // // Compiler Build ID: CL-24817639 // Cuda compilation tools, release 10.0, V10.0.130 // Based on LLVM 3.4svn // .version 6.3 .target sm_70 .address_size 64 // .globl _ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE .common .global .align 8 .u64 _ZN08NumbaEnv8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE; .visible .func (.param .b32 func_retval0) _ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE( .param .b64 _ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_0, .param .b64 _ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_1, .param .b64 _ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_2, .param .b64 _ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_3, .param .b64 _ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_4, .param .b64 _ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_5, .param .b64 _ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_6, .param .b64 _ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_7 ) { .reg .pred %p<3>; .reg .b32 %r<6>; .reg .b64 %rd<18>; ld.param.u64 %rd6, [_ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_0]; ld.param.u64 %rd7, [_ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_5]; ld.param.u64 %rd8, [_ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_6]; ld.param.u64 %rd9, [_ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_7]; mov.u64 %rd15, 0; mov.u64 %rd16, %rd15; BB0_1: mov.u64 %rd2, %rd16; mov.u32 %r5, 0; setp.ge.s64 %p1, %rd15, %rd8; mov.u64 %rd17, %rd15; @%p1 bra BB0_3; mul.lo.s64 %rd12, %rd15, %rd9; add.s64 %rd13, %rd12, %rd7; ld.u32 %r5, [%rd13]; add.s64 %rd17, %rd15, 1; BB0_3: cvt.s64.s32 %rd14, %r5; add.s64 %rd16, %rd14, %rd2; setp.lt.s64 %p2, %rd15, %rd8; mov.u64 %rd15, %rd17; @%p2 bra BB0_1; st.u64 [%rd6], %rd2; mov.u32 %r4, 0; st.param.b32 [func_retval0+0], %r4; ret; } )***"}; template <typename T> class GroupedRollingTest : public cudf::test::BaseFixture { protected: // input as column_wrapper void run_test_col(cudf::table_view const& keys, cudf::column_view const& input, std::vector<cudf::size_type> const& expected_grouping, cudf::size_type const& preceding_window, cudf::size_type const& following_window, cudf::size_type min_periods, cudf::rolling_aggregation const& op) { std::unique_ptr<cudf::column> output; // wrap windows EXPECT_NO_THROW(output = cudf::grouped_rolling_window( keys, input, preceding_window, following_window, min_periods, op)); auto reference = create_reference_output( op, input, expected_grouping, preceding_window, following_window, min_periods); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*output, *reference); } void run_test_col_agg(cudf::table_view const& keys, cudf::column_view const& input, std::vector<cudf::size_type> const& expected_grouping, cudf::size_type preceding_window, cudf::size_type following_window, cudf::size_type min_periods) { // Skip grouping-tests on bool8 keys. sort_helper does not support this. if (keys.num_columns() > 0 && cudf::is_boolean(keys.column(0).type())) { return; } // test all supported aggregators run_test_col(keys, input, expected_grouping, preceding_window, following_window, min_periods, *cudf::make_min_aggregation<cudf::rolling_aggregation>()); run_test_col(keys, input, expected_grouping, preceding_window, following_window, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); run_test_col( keys, input, expected_grouping, preceding_window, following_window, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>(cudf::null_policy::INCLUDE)); run_test_col(keys, input, expected_grouping, preceding_window, following_window, min_periods, *cudf::make_max_aggregation<cudf::rolling_aggregation>()); if (!cudf::is_timestamp(input.type())) { run_test_col(keys, input, expected_grouping, preceding_window, following_window, min_periods, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()); run_test_col(keys, input, expected_grouping, preceding_window, following_window, min_periods, *cudf::make_mean_aggregation<cudf::rolling_aggregation>()); } run_test_col(keys, input, expected_grouping, preceding_window, following_window, min_periods, *cudf::make_row_number_aggregation<cudf::rolling_aggregation>()); // >>> test UDFs <<< if (input.type() == cudf::data_type{cudf::type_id::INT32} && !input.has_nulls()) { auto cuda_udf_agg = cudf::make_udf_aggregation<cudf::rolling_aggregation>( cudf::udf_type::CUDA, cuda_func, cudf::data_type{cudf::type_id::INT64}); run_test_col(keys, input, expected_grouping, preceding_window, following_window, min_periods, *cuda_udf_agg); auto ptx_udf_agg = cudf::make_udf_aggregation<cudf::rolling_aggregation>( cudf::udf_type::PTX, ptx_func, cudf::data_type{cudf::type_id::INT64}); run_test_col(keys, input, expected_grouping, preceding_window, following_window, min_periods, *ptx_udf_agg); } } private: // use SFINAE to only instantiate for supported combinations // specialization for COUNT_VALID, COUNT_ALL template <bool include_nulls> std::unique_ptr<cudf::column> create_count_reference_output( cudf::column_view const& input, std::vector<cudf::size_type> const& group_offsets, cudf::size_type const& preceding_window, cudf::size_type const& following_window, cudf::size_type min_periods) { cudf::size_type num_rows = input.size(); thrust::host_vector<cudf::size_type> ref_data(num_rows); thrust::host_vector<bool> ref_valid(num_rows); // input data and mask std::vector<cudf::bitmask_type> in_valid = cudf::test::bitmask_to_host(input); cudf::bitmask_type* valid_mask = in_valid.data(); for (cudf::size_type i = 0; i < num_rows; i++) { // load sizes min_periods = std::max(min_periods, 1); // at least one observation is required // compute bounds auto group_end_index = std::upper_bound(group_offsets.begin(), group_offsets.end(), i); auto group_start_index = group_end_index - 1; cudf::size_type start = std::min(num_rows, std::max(0, i - preceding_window + 1)); cudf::size_type end = std::min(num_rows, std::max(0, i + following_window + 1)); cudf::size_type start_index = std::max(*group_start_index, std::min(start, end)); cudf::size_type end_index = std::min(*group_end_index, std::max(start, end)); // aggregate cudf::size_type count = 0; for (cudf::size_type j = start_index; j < end_index; j++) { if (include_nulls || !input.nullable() || cudf::bit_is_set(valid_mask, j)) count++; } ref_valid[i] = ((end_index - start_index) >= min_periods); if (ref_valid[i]) ref_data[i] = count; } cudf::test::fixed_width_column_wrapper<cudf::size_type> col( ref_data.begin(), ref_data.end(), ref_valid.begin()); return col.release(); } std::unique_ptr<cudf::column> create_row_number_reference_output( cudf::column_view const& input, std::vector<cudf::size_type> const& group_offsets, cudf::size_type const& preceding_window, cudf::size_type const& following_window, cudf::size_type min_periods) { cudf::size_type num_rows = input.size(); thrust::host_vector<cudf::size_type> ref_data(num_rows); thrust::host_vector<bool> ref_valid(num_rows); // input data and mask std::vector<cudf::bitmask_type> in_valid = cudf::test::bitmask_to_host(input); for (cudf::size_type i = 0; i < num_rows; i++) { // load sizes min_periods = std::max(min_periods, 1); // at least one observation is required // compute bounds auto group_end_index = std::upper_bound(group_offsets.begin(), group_offsets.end(), i); auto group_start_index = group_end_index - 1; cudf::size_type start = std::min(num_rows, std::max(0, i - preceding_window + 1)); cudf::size_type end = std::min(num_rows, std::max(0, i + following_window + 1)); cudf::size_type start_index = std::max(*group_start_index, std::min(start, end)); cudf::size_type end_index = std::min(*group_end_index, std::max(start, end)); // aggregate cudf::size_type count{end_index - start_index}; cudf::size_type row_number{i - start_index + 1}; ref_valid[i] = (count >= min_periods); ref_data[i] = row_number; } cudf::test::fixed_width_column_wrapper<cudf::size_type> col( ref_data.begin(), ref_data.end(), ref_valid.begin()); return col.release(); } template <typename agg_op, cudf::aggregation::Kind k, typename OutputType, bool is_mean, std::enable_if_t<is_rolling_supported<T, k>()>* = nullptr> std::unique_ptr<cudf::column> create_reference_output( cudf::column_view const& input, std::vector<cudf::size_type> const& group_offsets, cudf::size_type const& preceding_window, cudf::size_type const& following_window, cudf::size_type min_periods) { cudf::size_type num_rows = input.size(); thrust::host_vector<OutputType> ref_data(num_rows); thrust::host_vector<bool> ref_valid(num_rows); // input data and mask auto [in_col, in_valid] = cudf::test::to_host<T>(input); cudf::bitmask_type* valid_mask = in_valid.data(); agg_op op; for (cudf::size_type i = 0; i < num_rows; i++) { OutputType val = agg_op::template identity<OutputType>(); // load sizes min_periods = std::max(min_periods, 1); // at least one observation is required // compute bounds auto group_end_index = std::upper_bound(group_offsets.begin(), group_offsets.end(), i); auto group_start_index = group_end_index - 1; cudf::size_type start = std::min( num_rows, std::max(0, i - preceding_window + 1)); // Preceding window includes current row. cudf::size_type end = std::min(num_rows, std::max(0, i + following_window + 1)); cudf::size_type start_index = std::max(*group_start_index, std::min(start, end)); cudf::size_type end_index = std::min(*group_end_index, std::max(start, end)); // aggregate cudf::size_type count = 0; for (cudf::size_type j = start_index; j < end_index; j++) { if (!input.nullable() || cudf::bit_is_set(valid_mask, j)) { val = op(static_cast<OutputType>(in_col[j]), val); count++; } } ref_valid[i] = (count >= min_periods); if (ref_valid[i]) { cudf::detail::rolling_store_output_functor<OutputType, is_mean>{}(ref_data[i], val, count); } } cudf::test::fixed_width_column_wrapper<OutputType> col( ref_data.begin(), ref_data.end(), ref_valid.begin()); return col.release(); } template <typename agg_op, cudf::aggregation::Kind k, typename OutputType, bool is_mean, std::enable_if_t<!is_rolling_supported<T, k>()>* = nullptr> std::unique_ptr<cudf::column> create_reference_output( cudf::column_view const& input, std::vector<cudf::size_type> const& group_offsets, cudf::size_type const& preceding_window_col, cudf::size_type const& following_window_col, cudf::size_type min_periods) { CUDF_FAIL("Unsupported combination of type and aggregation"); } std::unique_ptr<cudf::column> create_reference_output( cudf::rolling_aggregation const& op, cudf::column_view const& input, std::vector<cudf::size_type> const& group_offsets, cudf::size_type const& preceding_window, cudf::size_type const& following_window, cudf::size_type min_periods) { // unroll aggregation types switch (op.kind) { case cudf::aggregation::SUM: return create_reference_output<cudf::DeviceSum, cudf::aggregation::SUM, cudf::detail::target_type_t<T, cudf::aggregation::SUM>, false>( input, group_offsets, preceding_window, following_window, min_periods); case cudf::aggregation::MIN: return create_reference_output<cudf::DeviceMin, cudf::aggregation::MIN, cudf::detail::target_type_t<T, cudf::aggregation::MIN>, false>( input, group_offsets, preceding_window, following_window, min_periods); case cudf::aggregation::MAX: return create_reference_output<cudf::DeviceMax, cudf::aggregation::MAX, cudf::detail::target_type_t<T, cudf::aggregation::MAX>, false>( input, group_offsets, preceding_window, following_window, min_periods); case cudf::aggregation::COUNT_VALID: return create_count_reference_output<false>( input, group_offsets, preceding_window, following_window, min_periods); case cudf::aggregation::COUNT_ALL: return create_count_reference_output<true>( input, group_offsets, preceding_window, following_window, min_periods); case cudf::aggregation::ROW_NUMBER: return create_row_number_reference_output( input, group_offsets, preceding_window, following_window, min_periods); case cudf::aggregation::MEAN: return create_reference_output<cudf::DeviceSum, cudf::aggregation::MEAN, cudf::detail::target_type_t<T, cudf::aggregation::MEAN>, true>( input, group_offsets, preceding_window, following_window, min_periods); // >>> UDFs <<< case cudf::aggregation::CUDA: return create_reference_output<cudf::DeviceSum, cudf::aggregation::SUM, cudf::detail::target_type_t<T, cudf::aggregation::SUM>, false>( input, group_offsets, preceding_window, following_window, min_periods); case cudf::aggregation::PTX: return create_reference_output<cudf::DeviceSum, cudf::aggregation::SUM, cudf::detail::target_type_t<T, cudf::aggregation::SUM>, false>( input, group_offsets, preceding_window, following_window, min_periods); default: return cudf::test::fixed_width_column_wrapper<T>({}).release(); } } }; // // ------------- expected failures -------------------- class GroupedRollingErrorTest : public cudf::test::BaseFixture {}; // negative sizes TEST_F(GroupedRollingErrorTest, NegativeMinPeriods) { // Construct agg column. const std::vector<cudf::size_type> col_data{0, 1, 2, 0, 4}; const std::vector<bool> col_valid{1, 1, 1, 0, 1}; cudf::test::fixed_width_column_wrapper<cudf::size_type> input{ col_data.begin(), col_data.end(), col_valid.begin()}; // Construct Grouping keys table-view. auto const N_ELEMENTS{col_data.size()}; const std::vector<cudf::size_type> grouping_key_vec(N_ELEMENTS, 0); cudf::test::fixed_width_column_wrapper<cudf::size_type> grouping_keys_col( grouping_key_vec.begin(), grouping_key_vec.end(), col_valid.begin()); const cudf::table_view grouping_keys{std::vector<cudf::column_view>{grouping_keys_col}}; EXPECT_THROW( cudf::grouped_rolling_window( grouping_keys, input, 2, 2, -2, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); } TEST_F(GroupedRollingErrorTest, EmptyInput) { cudf::test::fixed_width_column_wrapper<int32_t> empty_col{}; std::unique_ptr<cudf::column> output; const cudf::table_view grouping_keys{std::vector<cudf::column_view>{}}; EXPECT_NO_THROW( output = cudf::grouped_rolling_window( grouping_keys, empty_col, 2, 0, 2, *cudf::make_sum_aggregation<cudf::rolling_aggregation>())); EXPECT_EQ(output->size(), 0); } // incorrect type/aggregation combo: sum of timestamps TEST_F(GroupedRollingErrorTest, SumTimestampNotSupported) { constexpr cudf::size_type size{10}; cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep> input_D( thrust::make_counting_iterator(0), thrust::make_counting_iterator(size)); cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep> input_s( thrust::make_counting_iterator(0), thrust::make_counting_iterator(size)); cudf::test::fixed_width_column_wrapper<cudf::timestamp_ms, cudf::timestamp_ms::rep> input_ms( thrust::make_counting_iterator(0), thrust::make_counting_iterator(size)); cudf::test::fixed_width_column_wrapper<cudf::timestamp_us, cudf::timestamp_us::rep> input_us( thrust::make_counting_iterator(0), thrust::make_counting_iterator(size)); cudf::test::fixed_width_column_wrapper<cudf::timestamp_ns, cudf::timestamp_ns::rep> input_ns( thrust::make_counting_iterator(0), thrust::make_counting_iterator(size)); // Construct table-view of grouping keys. std::vector<cudf::size_type> grouping_keys_vec(size, 0); // `size` elements, each == 0. const cudf::table_view grouping_keys{ std::vector<cudf::column_view>{cudf::test::fixed_width_column_wrapper<cudf::size_type>( grouping_keys_vec.begin(), grouping_keys_vec.end())}}; EXPECT_THROW( cudf::grouped_rolling_window( grouping_keys, input_D, 2, 2, 0, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); EXPECT_THROW( cudf::grouped_rolling_window( grouping_keys, input_s, 2, 2, 0, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); EXPECT_THROW( cudf::grouped_rolling_window( grouping_keys, input_ms, 2, 2, 0, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); EXPECT_THROW( cudf::grouped_rolling_window( grouping_keys, input_us, 2, 2, 0, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); EXPECT_THROW( cudf::grouped_rolling_window( grouping_keys, input_ns, 2, 2, 0, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); } TYPED_TEST_SUITE(GroupedRollingTest, cudf::test::FixedWidthTypesWithoutFixedPoint); TYPED_TEST(GroupedRollingTest, SimplePartitionedStaticWindowsWithGroupKeys) { auto const col_data = {0, 10, 20, 30, 40, 50, 60, 70, 80, 90}; const cudf::size_type DATA_SIZE{static_cast<cudf::size_type>(col_data.size())}; const std::vector<bool> col_mask(DATA_SIZE, true); cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> input( col_data.begin(), col_data.end(), col_mask.begin()); // 2 grouping keys, with effectively 3 groups of at most 4 rows each: // 1. key_0 {0, 0, 0, ...0} // 2. key_1 {0, 0, 0, 0, 1, 1, 1, 1, 2, 2} std::vector<int64_t> key_0_vec(DATA_SIZE, 0); std::vector<int64_t> key_1_vec; int i{0}; std::generate_n( std::back_inserter(key_1_vec), DATA_SIZE, [&i]() { return i++ / 4; }); // Groups of 4. const cudf::test::fixed_width_column_wrapper<TypeParam, int64_t> key_0(key_0_vec.begin(), key_0_vec.end()); const cudf::test::fixed_width_column_wrapper<TypeParam, int64_t> key_1(key_1_vec.begin(), key_1_vec.end()); const cudf::table_view grouping_keys{std::vector<cudf::column_view>{key_0, key_1}}; cudf::size_type preceding_window = 2; cudf::size_type following_window = 1; std::vector<cudf::size_type> expected_group_offsets{0, 4, 8, DATA_SIZE}; this->run_test_col_agg( grouping_keys, input, expected_group_offsets, preceding_window, following_window, 1); } TYPED_TEST(GroupedRollingTest, SimplePartitionedStaticWindowWithNoGroupKeys) { auto const col_data = cudf::test::make_type_param_vector<TypeParam>({0, 10, 20, 30, 40, 50, 60, 70, 80, 90}); const cudf::size_type DATA_SIZE{static_cast<cudf::size_type>(col_data.size())}; const std::vector<bool> col_mask(DATA_SIZE, true); cudf::test::fixed_width_column_wrapper<TypeParam> input( col_data.begin(), col_data.end(), col_mask.begin()); const cudf::table_view grouping_keys{std::vector<cudf::column_view>{}}; cudf::size_type preceding_window = 2; cudf::size_type following_window = 1; std::vector<cudf::size_type> expected_group_offsets{0, DATA_SIZE}; this->run_test_col_agg( grouping_keys, input, expected_group_offsets, preceding_window, following_window, 1); } // all rows are invalid TYPED_TEST(GroupedRollingTest, AllInvalid) { auto const col_data = cudf::test::make_type_param_vector<TypeParam>({0, 10, 20, 30, 40, 50, 60, 70, 80, 90}); const cudf::size_type DATA_SIZE{static_cast<cudf::size_type>(col_data.size())}; const std::vector<bool> col_mask(DATA_SIZE, false); cudf::test::fixed_width_column_wrapper<TypeParam> input( col_data.begin(), col_data.end(), col_mask.begin()); // 2 grouping keys, with effectively 3 groups of at most 4 rows each: // 1. key_0 {0, 0, 0, ...0} // 2. key_1 {0, 0, 0, 0, 1, 1, 1, 1, 2, 2} std::vector<int64_t> key_0_vec(DATA_SIZE, 0); std::vector<int64_t> key_1_vec; int i{0}; std::generate_n( std::back_inserter(key_1_vec), DATA_SIZE, [&i]() { return i++ / 4; }); // Groups of 4. const cudf::test::fixed_width_column_wrapper<TypeParam, int64_t> key_0(key_0_vec.begin(), key_0_vec.end()); const cudf::test::fixed_width_column_wrapper<TypeParam, int64_t> key_1(key_1_vec.begin(), key_1_vec.end()); const cudf::table_view grouping_keys{std::vector<cudf::column_view>{key_0, key_1}}; cudf::size_type preceding_window = 2; cudf::size_type following_window = 1; std::vector<cudf::size_type> expected_group_offsets{0, 4, 8, DATA_SIZE}; this->run_test_col_agg( grouping_keys, input, expected_group_offsets, preceding_window, following_window, 1); } // window = following_window = 0 TYPED_TEST(GroupedRollingTest, ZeroWindow) { auto const col_data = {0, 10, 20, 30, 40, 50, 60, 70, 80, 90}; const cudf::size_type DATA_SIZE{static_cast<cudf::size_type>(col_data.size())}; const std::vector<bool> col_mask(DATA_SIZE, true); cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> input( col_data.begin(), col_data.end(), col_mask.begin()); // 2 grouping keys, with effectively 3 groups of at most 4 rows each: // 1. key_0 {0, 0, 0, ...0} // 2. key_1 {0, 0, 0, 0, 1, 1, 1, 1, 2, 2} std::vector<int64_t> key_0_vec(DATA_SIZE, 0); std::vector<int64_t> key_1_vec; int i{0}; std::generate_n( std::back_inserter(key_1_vec), DATA_SIZE, [&i]() { return i++ / 4; }); // Groups of 4. const cudf::test::fixed_width_column_wrapper<TypeParam, int64_t> key_0(key_0_vec.begin(), key_0_vec.end()); const cudf::test::fixed_width_column_wrapper<TypeParam, int64_t> key_1(key_1_vec.begin(), key_1_vec.end()); const cudf::table_view grouping_keys{std::vector<cudf::column_view>{key_0, key_1}}; cudf::size_type preceding_window = 1; cudf::size_type following_window = 0; std::vector<cudf::size_type> expected_group_offsets{0, 4, 8, DATA_SIZE}; this->run_test_col_agg( grouping_keys, input, expected_group_offsets, preceding_window, following_window, 1); } using GroupedRollingTestInts = GroupedRollingTest<int32_t>; TEST_F(GroupedRollingTestInts, SumLargeWindow) { cudf::test::fixed_width_column_wrapper<int32_t, int32_t> input({1, 1, 1, 1, 1, 1, 1, 1, 1, 1}); cudf::size_type preceding_window = 2147483640; cudf::size_type following_window = 2147483642; cudf::table_view groupby_keys; auto result = cudf::grouped_rolling_window(groupby_keys, input, preceding_window, following_window, 1, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()); cudf::test::fixed_width_column_wrapper<int64_t, int32_t> expected( {10, 10, 10, 10, 10, 10, 10, 10, 10, 10}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } // ------------- non-fixed-width types -------------------- using GroupedRollingTestStrings = GroupedRollingTest<cudf::string_view>; TEST_F(GroupedRollingTestStrings, StringsUnsupportedOperators) { cudf::test::strings_column_wrapper input{{"This", "is", "not", "a", "string", "type"}, {1, 1, 1, 0, 1, 0}}; const cudf::size_type DATA_SIZE{static_cast<cudf::column_view>(input).size()}; const std::vector<cudf::size_type> key_col_vec(DATA_SIZE, 0); const cudf::table_view key_cols{ std::vector<cudf::column_view>{cudf::test::fixed_width_column_wrapper<cudf::size_type>( key_col_vec.begin(), key_col_vec.end())}}; EXPECT_THROW( cudf::grouped_rolling_window( key_cols, input, 2, 2, 0, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); EXPECT_THROW( cudf::grouped_rolling_window( key_cols, input, 2, 2, 0, *cudf::make_mean_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); } template <typename T> class GroupedTimeRangeRollingTest : public cudf::test::BaseFixture { protected: // input as column_wrapper void run_test_col(cudf::table_view const& keys, cudf::column_view const& timestamp_column, cudf::order const& timestamp_order, cudf::column_view const& input, std::vector<cudf::size_type> const& expected_grouping, cudf::size_type const& preceding_window_in_days, cudf::size_type const& following_window_in_days, cudf::size_type min_periods, cudf::rolling_aggregation const& op) { std::unique_ptr<cudf::column> output; // wrap windows EXPECT_NO_THROW(output = cudf::grouped_time_range_rolling_window(keys, timestamp_column, timestamp_order, input, preceding_window_in_days, following_window_in_days, min_periods, op)); auto reference = create_reference_output(op, timestamp_column, timestamp_order, input, expected_grouping, preceding_window_in_days, following_window_in_days, min_periods); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*output, *reference); } void run_test_col_agg(cudf::table_view const& keys, cudf::column_view const& timestamp_column, cudf::order const& timestamp_order, cudf::column_view const& input, std::vector<cudf::size_type> const& expected_grouping, cudf::size_type preceding_window_in_days, cudf::size_type following_window_in_days, cudf::size_type min_periods) { // Skip grouping-tests on bool8 keys. sort_helper does not support this. if (keys.num_columns() > 0 && cudf::is_boolean(keys.column(0).type())) { return; } // test all supported aggregators run_test_col(keys, timestamp_column, timestamp_order, input, expected_grouping, preceding_window_in_days, following_window_in_days, min_periods, *cudf::make_min_aggregation<cudf::rolling_aggregation>()); run_test_col(keys, timestamp_column, timestamp_order, input, expected_grouping, preceding_window_in_days, following_window_in_days, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); run_test_col( keys, timestamp_column, timestamp_order, input, expected_grouping, preceding_window_in_days, following_window_in_days, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>(cudf::null_policy::INCLUDE)); run_test_col(keys, timestamp_column, timestamp_order, input, expected_grouping, preceding_window_in_days, following_window_in_days, min_periods, *cudf::make_max_aggregation<cudf::rolling_aggregation>()); if (!cudf::is_timestamp(input.type())) { run_test_col(keys, timestamp_column, timestamp_order, input, expected_grouping, preceding_window_in_days, following_window_in_days, min_periods, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()); run_test_col(keys, timestamp_column, timestamp_order, input, expected_grouping, preceding_window_in_days, following_window_in_days, min_periods, *cudf::make_mean_aggregation<cudf::rolling_aggregation>()); } run_test_col(keys, timestamp_column, timestamp_order, input, expected_grouping, preceding_window_in_days, following_window_in_days, min_periods, *cudf::make_row_number_aggregation<cudf::rolling_aggregation>()); } private: // use SFINAE to only instantiate for supported combinations // specialization for COUNT_VALID, COUNT_ALL template <bool include_nulls> std::unique_ptr<cudf::column> create_count_reference_output( cudf::column_view const& timestamp_column, cudf::order const& timestamp_order, cudf::column_view const& input, std::vector<cudf::size_type> const& group_offsets, cudf::size_type const& preceding_window_in_days, cudf::size_type const& following_window_in_days, cudf::size_type min_periods) { assert(timestamp_column.type().id() == cudf::type_id::TIMESTAMP_DAYS); // Testing with DAYS. auto timestamp_vec = cudf::test::to_host<int32_t>(timestamp_column).first; cudf::size_type num_rows = input.size(); thrust::host_vector<cudf::size_type> ref_data(num_rows); thrust::host_vector<bool> ref_valid(num_rows); // input data and mask std::vector<cudf::bitmask_type> in_valid = cudf::test::bitmask_to_host(input); cudf::bitmask_type* valid_mask = in_valid.data(); for (cudf::size_type i = 0; i < num_rows; i++) { // load sizes min_periods = std::max(min_periods, 1); // at least one observation is required // compute bounds auto group_end_index = std::upper_bound(group_offsets.begin(), group_offsets.end(), i); auto group_start_index = group_end_index - 1; cudf::size_type start_index = i; cudf::size_type end_index = i; if (timestamp_order == cudf::order::ASCENDING) { while ((start_index - 1) >= *group_start_index && timestamp_vec[start_index - 1] >= (timestamp_vec[i] - preceding_window_in_days)) { --start_index; } while ((end_index + 1) < *group_end_index && timestamp_vec[end_index + 1] <= (timestamp_vec[i] + following_window_in_days)) { ++end_index; } ++end_index; // One past the last. } else { while ((start_index - 1) >= *group_start_index && timestamp_vec[start_index - 1] <= (timestamp_vec[i] + preceding_window_in_days)) { --start_index; } while ((end_index + 1) < *group_end_index && timestamp_vec[end_index + 1] >= (timestamp_vec[i] - following_window_in_days)) { ++end_index; } ++end_index; // One past the last. } // aggregate cudf::size_type count = 0; for (cudf::size_type j = start_index; j < end_index; j++) { if (include_nulls || !input.nullable() || cudf::bit_is_set(valid_mask, j)) count++; } ref_valid[i] = ((end_index - start_index) >= min_periods); if (ref_valid[i]) ref_data[i] = count; } cudf::test::fixed_width_column_wrapper<cudf::size_type> col( ref_data.begin(), ref_data.end(), ref_valid.begin()); return col.release(); } std::unique_ptr<cudf::column> create_row_number_reference_output( cudf::column_view const& timestamp_column, cudf::order const& timestamp_order, cudf::column_view const& input, std::vector<cudf::size_type> const& group_offsets, cudf::size_type const& preceding_window_in_days, cudf::size_type const& following_window_in_days, cudf::size_type min_periods) { assert(timestamp_column.type().id() == cudf::type_id::TIMESTAMP_DAYS); // Testing with DAYS. auto timestamp_vec = cudf::test::to_host<int32_t>(timestamp_column).first; cudf::size_type num_rows = input.size(); thrust::host_vector<cudf::size_type> ref_data(num_rows); thrust::host_vector<bool> ref_valid(num_rows); // input data and mask std::vector<cudf::bitmask_type> in_valid = cudf::test::bitmask_to_host(input); for (cudf::size_type i = 0; i < num_rows; i++) { // load sizes min_periods = std::max(min_periods, 1); // at least one observation is required // compute bounds auto group_end_index = std::upper_bound(group_offsets.begin(), group_offsets.end(), i); auto group_start_index = group_end_index - 1; cudf::size_type start_index = i; cudf::size_type end_index = i; if (timestamp_order == cudf::order::ASCENDING) { while ((start_index - 1) >= *group_start_index && timestamp_vec[start_index - 1] >= (timestamp_vec[i] - preceding_window_in_days)) { --start_index; } while ((end_index + 1) < *group_end_index && timestamp_vec[end_index + 1] <= (timestamp_vec[i] + following_window_in_days)) { ++end_index; } ++end_index; // One past the last. } else { while ((start_index - 1) >= *group_start_index && timestamp_vec[start_index - 1] <= (timestamp_vec[i] + preceding_window_in_days)) { --start_index; } while ((end_index + 1) < *group_end_index && timestamp_vec[end_index + 1] >= (timestamp_vec[i] - following_window_in_days)) { ++end_index; } ++end_index; // One past the last. } // aggregate cudf::size_type count{end_index - start_index}; cudf::size_type row_number{i - start_index + 1}; ref_valid[i] = (count >= min_periods); ref_data[i] = row_number; } cudf::test::fixed_width_column_wrapper<cudf::size_type> col( ref_data.begin(), ref_data.end(), ref_valid.begin()); return col.release(); } template <typename agg_op, cudf::aggregation::Kind k, typename OutputType, bool is_mean, std::enable_if_t<is_rolling_supported<T, k>()>* = nullptr> std::unique_ptr<cudf::column> create_reference_output( cudf::column_view const& timestamp_column, cudf::order const& timestamp_order, cudf::column_view const& input, std::vector<cudf::size_type> const& group_offsets, cudf::size_type const& preceding_window_in_days, cudf::size_type const& following_window_in_days, cudf::size_type min_periods) { assert(timestamp_column.type().id() == cudf::type_id::TIMESTAMP_DAYS); // Testing with DAYS. auto timestamp_vec = cudf::test::to_host<int32_t>(timestamp_column).first; cudf::size_type num_rows = input.size(); thrust::host_vector<OutputType> ref_data(num_rows); thrust::host_vector<bool> ref_valid(num_rows); // input data and mask auto [in_col, in_valid] = cudf::test::to_host<T>(input); cudf::bitmask_type* valid_mask = in_valid.data(); agg_op op; for (cudf::size_type i = 0; i < num_rows; i++) { OutputType val = agg_op::template identity<OutputType>(); // load sizes min_periods = std::max(min_periods, 1); // at least one observation is required // compute bounds auto group_end_index = std::upper_bound(group_offsets.begin(), group_offsets.end(), i); auto group_start_index = group_end_index - 1; cudf::size_type start_index = i; cudf::size_type end_index = i; if (timestamp_order == cudf::order::ASCENDING) { while ((start_index - 1) >= *group_start_index && timestamp_vec[start_index - 1] >= (timestamp_vec[i] - preceding_window_in_days)) { --start_index; } while ((end_index + 1) < *group_end_index && timestamp_vec[end_index + 1] <= (timestamp_vec[i] + following_window_in_days)) { ++end_index; } ++end_index; // One past the last. } else { while ((start_index - 1) >= *group_start_index && timestamp_vec[start_index - 1] <= (timestamp_vec[i] + preceding_window_in_days)) { --start_index; } while ((end_index + 1) < *group_end_index && timestamp_vec[end_index + 1] >= (timestamp_vec[i] - following_window_in_days)) { ++end_index; } ++end_index; } // aggregate cudf::size_type count = 0; for (cudf::size_type j = start_index; j < end_index; j++) { if (!input.nullable() || cudf::bit_is_set(valid_mask, j)) { val = op(static_cast<OutputType>(in_col[j]), val); count++; } } ref_valid[i] = (count >= min_periods); if (ref_valid[i]) { cudf::detail::rolling_store_output_functor<OutputType, is_mean>{}(ref_data[i], val, count); } } cudf::test::fixed_width_column_wrapper<OutputType> col( ref_data.begin(), ref_data.end(), ref_valid.begin()); return col.release(); } template <typename agg_op, cudf::aggregation::Kind k, typename OutputType, bool is_mean, std::enable_if_t<!is_rolling_supported<T, k>()>* = nullptr> std::unique_ptr<cudf::column> create_reference_output( cudf::column_view const& timestamp_column, cudf::order const& timestamp_order, cudf::column_view const& input, std::vector<cudf::size_type> const& group_offsets, cudf::size_type const& preceding_window_col, cudf::size_type const& following_window_col, cudf::size_type min_periods) { CUDF_FAIL("Unsupported combination of type and aggregation"); } std::unique_ptr<cudf::column> create_reference_output( cudf::rolling_aggregation const& op, cudf::column_view const& timestamp_column, cudf::order const& timestamp_order, cudf::column_view const& input, std::vector<cudf::size_type> const& group_offsets, cudf::size_type const& preceding_window, cudf::size_type const& following_window, cudf::size_type min_periods) { // unroll aggregation types switch (op.kind) { case cudf::aggregation::SUM: return create_reference_output<cudf::DeviceSum, cudf::aggregation::SUM, cudf::detail::target_type_t<T, cudf::aggregation::SUM>, false>(timestamp_column, timestamp_order, input, group_offsets, preceding_window, following_window, min_periods); case cudf::aggregation::MIN: return create_reference_output<cudf::DeviceMin, cudf::aggregation::MIN, cudf::detail::target_type_t<T, cudf::aggregation::MIN>, false>(timestamp_column, timestamp_order, input, group_offsets, preceding_window, following_window, min_periods); case cudf::aggregation::MAX: return create_reference_output<cudf::DeviceMax, cudf::aggregation::MAX, cudf::detail::target_type_t<T, cudf::aggregation::MAX>, false>(timestamp_column, timestamp_order, input, group_offsets, preceding_window, following_window, min_periods); case cudf::aggregation::COUNT_VALID: return create_count_reference_output<false>(timestamp_column, timestamp_order, input, group_offsets, preceding_window, following_window, min_periods); case cudf::aggregation::COUNT_ALL: return create_count_reference_output<true>(timestamp_column, timestamp_order, input, group_offsets, preceding_window, following_window, min_periods); case cudf::aggregation::ROW_NUMBER: return create_row_number_reference_output(timestamp_column, timestamp_order, input, group_offsets, preceding_window, following_window, min_periods); case cudf::aggregation::MEAN: return create_reference_output<cudf::DeviceSum, cudf::aggregation::MEAN, cudf::detail::target_type_t<T, cudf::aggregation::MEAN>, true>(timestamp_column, timestamp_order, input, group_offsets, preceding_window, following_window, min_periods); default: return cudf::test::fixed_width_column_wrapper<T>({}).release(); } } }; TYPED_TEST_SUITE(GroupedTimeRangeRollingTest, cudf::test::FixedWidthTypesWithoutFixedPoint); TYPED_TEST(GroupedTimeRangeRollingTest, SimplePartitionedStaticWindowsWithGroupKeysAndTimeRangesAscending) { const cudf::size_type DATA_SIZE{static_cast<cudf::size_type>(18)}; const std::vector<int> col_data(DATA_SIZE, 1); const std::vector<bool> col_mask(DATA_SIZE, true); cudf::test::fixed_width_column_wrapper<TypeParam, int> input( col_data.begin(), col_data.end(), col_mask.begin()); // 2 grouping keys, with effectively 3 groups of at most 6 rows each: // 1. key_0 {0, 0, 0, ...0} // 2. key_1 {0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2} std::vector<int64_t> key_0_vec(DATA_SIZE, 0); std::vector<int64_t> key_1_vec; int i{0}; std::generate_n( std::back_inserter(key_1_vec), DATA_SIZE, [&i]() { return i++ / 6; }); // Groups of 6. const cudf::test::fixed_width_column_wrapper<TypeParam, int64_t> key_0(key_0_vec.begin(), key_0_vec.end()); const cudf::test::fixed_width_column_wrapper<TypeParam, int64_t> key_1(key_1_vec.begin(), key_1_vec.end()); const cudf::table_view grouping_keys{std::vector<cudf::column_view>{key_0, key_1}}; cudf::size_type preceding_window_in_days = 1; cudf::size_type following_window_in_days = 1; std::vector<cudf::size_type> expected_group_offsets{0, 6, 12, DATA_SIZE}; // Timestamp column. std::vector<int32_t> timestamp_days_vec{0, 2, 3, 4, 5, 7, 0, 0, 1, 2, 3, 3, 0, 1, 2, 3, 3, 3}; cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep> timestamp_days_ascending(timestamp_days_vec.begin(), timestamp_days_vec.end()); this->run_test_col_agg(grouping_keys, timestamp_days_ascending, cudf::order::ASCENDING, input, expected_group_offsets, preceding_window_in_days, following_window_in_days, 1); } TYPED_TEST(GroupedTimeRangeRollingTest, SimplePartitionedStaticWindowsWithGroupKeysAndTimeRangesDescending) { const cudf::size_type DATA_SIZE{static_cast<cudf::size_type>(18)}; const std::vector<int> col_data(DATA_SIZE, 1); const std::vector<bool> col_mask(DATA_SIZE, true); cudf::test::fixed_width_column_wrapper<TypeParam, int> input( col_data.begin(), col_data.end(), col_mask.begin()); // 2 grouping keys, with effectively 3 groups of at most 6 rows each: // 1. key_0 {0, 0, 0, ...0} // 2. key_1 {0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2} std::vector<int64_t> key_0_vec(DATA_SIZE, 0); std::vector<int64_t> key_1_vec; int i{0}; std::generate_n( std::back_inserter(key_1_vec), DATA_SIZE, [&i]() { return i++ / 6; }); // Groups of 6. const cudf::test::fixed_width_column_wrapper<TypeParam, int64_t> key_0(key_0_vec.begin(), key_0_vec.end()); const cudf::test::fixed_width_column_wrapper<TypeParam, int64_t> key_1(key_1_vec.begin(), key_1_vec.end()); const cudf::table_view grouping_keys{std::vector<cudf::column_view>{key_0, key_1}}; cudf::size_type preceding_window_in_days = 1; cudf::size_type following_window_in_days = 2; std::vector<cudf::size_type> expected_group_offsets{0, 6, 12, DATA_SIZE}; // Timestamp column. std::vector<int32_t> timestamp_days_vec{0, 2, 3, 4, 5, 7, 0, 0, 1, 2, 3, 3, 0, 1, 2, 3, 3, 3}; cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep> timestamp_days_descending(timestamp_days_vec.rbegin(), timestamp_days_vec.rend()); this->run_test_col_agg(grouping_keys, timestamp_days_descending, cudf::order::DESCENDING, input, expected_group_offsets, preceding_window_in_days, following_window_in_days, 1); } TYPED_TEST(GroupedTimeRangeRollingTest, SimplePartitionedStaticWindowsWithNoGroupingKeys) { const cudf::size_type DATA_SIZE{static_cast<cudf::size_type>(6)}; const std::vector<int> col_data(DATA_SIZE, 1); const std::vector<bool> col_mask(DATA_SIZE, true); cudf::test::fixed_width_column_wrapper<TypeParam, int> input( col_data.begin(), col_data.end(), col_mask.begin()); const cudf::table_view grouping_keys{std::vector<cudf::column_view>{}}; cudf::size_type preceding_window_in_days = 1; cudf::size_type following_window_in_days = 1; std::vector<cudf::size_type> expected_group_offsets{0, DATA_SIZE}; // Timestamp column. std::vector<int32_t> timestamp_days_vec{0, 2, 3, 4, 5, 7}; cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep> timestamp_days_ascending(timestamp_days_vec.begin(), timestamp_days_vec.end()); this->run_test_col_agg(grouping_keys, timestamp_days_ascending, cudf::order::ASCENDING, input, expected_group_offsets, preceding_window_in_days, following_window_in_days, 1); } template <typename T> struct TypedNullTimestampTestForRangeQueries : public cudf::test::BaseFixture {}; struct NullTimestampTestForRangeQueries : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(TypedNullTimestampTestForRangeQueries, cudf::test::IntegralTypes); TYPED_TEST(TypedNullTimestampTestForRangeQueries, CountSingleGroupTimestampASCNullsFirst) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 0, 0, 0, 1, 1, 1, 1, 1, 1}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const preceding = 1L; auto const following = 1L; auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::ASCENDING, agg_col, preceding, following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {4, 4, 4, 4, 1, 2, 2, 3, 3, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedNullTimestampTestForRangeQueries, CountSingleGroupTimestampASCNullsLast) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 1, 0, 0, 0, 0}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const preceding = 1L; auto const following = 1L; auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::ASCENDING, agg_col, preceding, following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {2, 3, 3, 3, 2, 1, 4, 4, 4, 4}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedNullTimestampTestForRangeQueries, CountMultiGroupTimestampASCNullsFirst) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {1, 2, 2, 1, 2, 1, 2, 3, 4, 5}, {0, 0, 0, 1, 1, 0, 0, 1, 1, 1}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const preceding = 1L; auto const following = 1L; auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::ASCENDING, agg_col, preceding, following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {3, 3, 3, 2, 2, 2, 2, 2, 3, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedNullTimestampTestForRangeQueries, CountMultiGroupTimestampASCNullsLast) { using T = int32_t; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {1, 2, 2, 1, 3, 1, 2, 3, 4, 5}, {1, 1, 1, 0, 0, 1, 1, 1, 0, 0}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const preceding = 1L; auto const following = 1L; auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::ASCENDING, agg_col, preceding, following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {3, 3, 3, 2, 2, 2, 3, 2, 2, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedNullTimestampTestForRangeQueries, CountSingleGroupTimestampDESCNullsFirst) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, {0, 0, 0, 0, 1, 1, 1, 1, 1, 1}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const preceding = 1L; auto const following = 1L; auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::DESCENDING, agg_col, preceding, following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {4, 4, 4, 4, 1, 2, 2, 3, 3, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedNullTimestampTestForRangeQueries, CountSingleGroupTimestampDESCNullsLast) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, {1, 1, 1, 1, 1, 1, 0, 0, 0, 0}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const preceding = 1L; auto const following = 1L; auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::DESCENDING, agg_col, preceding, following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {2, 3, 3, 3, 2, 1, 4, 4, 4, 4}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedNullTimestampTestForRangeQueries, CountMultiGroupTimestampDESCNullsFirst) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {4, 3, 2, 1, 0, 9, 8, 7, 6, 5}, {0, 0, 0, 1, 1, 0, 0, 1, 1, 1}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const preceding = 1L; auto const following = 1L; auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::DESCENDING, agg_col, preceding, following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {3, 3, 3, 2, 2, 2, 2, 2, 3, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedNullTimestampTestForRangeQueries, CountMultiGroupTimestampDESCNullsLast) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {4, 3, 2, 1, 0, 9, 8, 7, 6, 5}, {1, 1, 1, 0, 0, 1, 1, 1, 0, 0}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const preceding = 1L; auto const following = 1L; auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::DESCENDING, agg_col, preceding, following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {2, 3, 2, 2, 2, 2, 3, 2, 2, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedNullTimestampTestForRangeQueries, CountSingleGroupAllNullTimestamps) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const preceding = 1L; auto const following = 1L; auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::ASCENDING, agg_col, preceding, following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {9, 9, 9, 9, 9, 9, 9, 9, 9, 9}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedNullTimestampTestForRangeQueries, CountMultiGroupAllNullTimestamps) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 0, 0, 0, 0}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const preceding = 1L; auto const following = 1L; auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::ASCENDING, agg_col, preceding, following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {2, 3, 3, 3, 2, 4, 4, 4, 4, 4}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } template <typename T> struct TypedUnboundedWindowTest : public cudf::test::BaseFixture {}; struct UnboundedWindowTest : public cudf::test::BaseFixture {}; using FixedWidthTypes = cudf::test::Concat<cudf::test::IntegralTypes, cudf::test::FloatingPointTypes, cudf::test::DurationTypes, cudf::test::TimestampTypes>; TYPED_TEST_SUITE(TypedUnboundedWindowTest, FixedWidthTypes); TYPED_TEST(TypedUnboundedWindowTest, UnboundedPrecedingWindowSingleGroupTimestampASCNullsFirst) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 0, 0, 0, 1, 1, 1, 1, 1, 1}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const unbounded_preceding = cudf::window_bounds::unbounded(); auto const one_day_following = cudf::window_bounds::get(1L); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::ASCENDING, agg_col, unbounded_preceding, one_day_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {4, 4, 4, 4, 5, 6, 7, 8, 9, 9}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedFollowingWindowSingleGroupTimestampASCNullsFirst) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 0, 0, 0, 1, 1, 1, 1, 1, 1}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const one_day_preceding = cudf::window_bounds::get(1L); auto const unbounded_following = cudf::window_bounds::unbounded(); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::ASCENDING, agg_col, one_day_preceding, unbounded_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {9, 9, 9, 9, 5, 5, 4, 4, 3, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedPrecedingAndFollowingWindowSingleGroupTimestampASCNullsFirst) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 0, 0, 0, 1, 1, 1, 1, 1, 1}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const unbounded_preceding = cudf::window_bounds::unbounded(); auto const unbounded_following = cudf::window_bounds::unbounded(); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::ASCENDING, agg_col, unbounded_preceding, unbounded_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL( output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{9, 9, 9, 9, 9, 9, 9, 9, 9, 9}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedPrecedingWindowSingleGroupTimestampASCNullsLast) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 1, 0, 0, 0, 0}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const unbounded_preceding = cudf::window_bounds::unbounded(); auto const one_day_following = cudf::window_bounds::get(1L); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::ASCENDING, agg_col, unbounded_preceding, one_day_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {2, 3, 4, 5, 5, 5, 9, 9, 9, 9}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedFollowingWindowSingleGroupTimestampASCNullsLast) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 1, 0, 0, 0, 0}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const one_day_preceding = cudf::window_bounds::get(1L); auto const unbounded_following = cudf::window_bounds::unbounded(); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::ASCENDING, agg_col, one_day_preceding, unbounded_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {9, 9, 8, 7, 6, 5, 4, 4, 4, 4}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedPrecedingAndFollowingWindowSingleGroupTimestampASCNullsLast) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 1, 0, 0, 0, 0}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const unbounded_preceding = cudf::window_bounds::unbounded(); auto const unbounded_following = cudf::window_bounds::unbounded(); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::ASCENDING, agg_col, unbounded_preceding, unbounded_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL( output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{9, 9, 9, 9, 9, 9, 9, 9, 9, 9}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedPrecedingWindowSingleGroupTimestampDESCNullsFirst) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, {0, 0, 0, 0, 1, 1, 1, 1, 1, 1}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const unbounded_preceding = cudf::window_bounds::unbounded(); auto const one_day_following = cudf::window_bounds::get(1L); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::DESCENDING, agg_col, unbounded_preceding, one_day_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {4, 4, 4, 4, 5, 6, 7, 8, 9, 9}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedFollowingWindowSingleGroupTimestampDESCNullsFirst) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, {0, 0, 0, 0, 1, 1, 1, 1, 1, 1}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const one_day_preceding = cudf::window_bounds::get(1L); auto const unbounded_following = cudf::window_bounds::unbounded(); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::DESCENDING, agg_col, one_day_preceding, unbounded_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {9, 9, 9, 9, 5, 5, 4, 4, 3, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedPrecedingAndFollowingWindowSingleGroupTimestampDESCNullsFirst) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, {0, 0, 0, 0, 1, 1, 1, 1, 1, 1}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const unbounded_preceding = cudf::window_bounds::unbounded(); auto const unbounded_following = cudf::window_bounds::unbounded(); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::DESCENDING, agg_col, unbounded_preceding, unbounded_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL( output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{9, 9, 9, 9, 9, 9, 9, 9, 9, 9}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedPrecedingWindowSingleGroupTimestampDESCNullsLast) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, {1, 1, 1, 1, 1, 1, 0, 0, 0, 0}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const unbounded_preceding = cudf::window_bounds::unbounded(); auto const one_day_following = cudf::window_bounds::get(1L); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::DESCENDING, agg_col, unbounded_preceding, one_day_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {2, 3, 4, 5, 5, 5, 9, 9, 9, 9}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedFollowingWindowSingleGroupTimestampDESCNullsLast) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, {1, 1, 1, 1, 1, 1, 0, 0, 0, 0}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const one_day_preceding = cudf::window_bounds::get(1L); auto const unbounded_following = cudf::window_bounds::unbounded(); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::DESCENDING, agg_col, one_day_preceding, unbounded_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {9, 9, 8, 7, 6, 5, 4, 4, 4, 4}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedPrecedingAndFollowingWindowSingleGroupTimestampDESCNullsLast) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, {1, 1, 1, 1, 1, 1, 0, 0, 0, 0}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const unbounded_preceding = cudf::window_bounds::unbounded(); auto const unbounded_following = cudf::window_bounds::unbounded(); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::DESCENDING, agg_col, unbounded_preceding, unbounded_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL( output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{9, 9, 9, 9, 9, 9, 9, 9, 9, 9}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedPrecedingCountMultiGroupTimestampASCNullsFirst) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {1, 2, 2, 1, 2, 1, 2, 3, 4, 5}, {0, 0, 0, 1, 1, 0, 0, 1, 1, 1}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const unbounded_preceding = cudf::window_bounds::unbounded(); auto const one_day_following = cudf::window_bounds::get(1L); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::ASCENDING, agg_col, unbounded_preceding, one_day_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {3, 3, 3, 5, 5, 2, 2, 4, 5, 5}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedFollowingCountMultiGroupTimestampASCNullsFirst) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {1, 2, 2, 1, 2, 1, 2, 3, 4, 5}, {0, 0, 0, 1, 1, 0, 0, 1, 1, 1}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const one_day_preceding = cudf::window_bounds::get(1L); auto const unbounded_following = cudf::window_bounds::unbounded(); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::ASCENDING, agg_col, one_day_preceding, unbounded_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {5, 5, 5, 2, 2, 5, 5, 3, 3, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedPrecedingAndFollowingCountMultiGroupTimestampASCNullsFirst) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {1, 2, 2, 1, 2, 1, 2, 3, 4, 5}, {0, 0, 0, 1, 1, 0, 0, 1, 1, 1}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const unbounded_preceding = cudf::window_bounds::unbounded(); auto const unbounded_following = cudf::window_bounds::unbounded(); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::ASCENDING, agg_col, unbounded_preceding, unbounded_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL( output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{5, 5, 5, 5, 5, 5, 5, 5, 5, 5}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedPrecedingCountMultiGroupTimestampASCNullsLast) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {1, 2, 2, 1, 3, 1, 2, 3, 4, 5}, {1, 1, 1, 0, 0, 1, 1, 1, 0, 0}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const unbounded_preceding = cudf::window_bounds::unbounded(); auto const one_day_following = cudf::window_bounds::get(1L); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::ASCENDING, agg_col, unbounded_preceding, one_day_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {3, 3, 3, 5, 5, 2, 3, 3, 5, 5}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedFollowingCountMultiGroupTimestampASCNullsLast) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {1, 2, 2, 1, 3, 1, 2, 3, 4, 5}, {1, 1, 1, 0, 0, 1, 1, 1, 0, 0}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const one_day_preceding = cudf::window_bounds::get(1L); auto const unbounded_following = cudf::window_bounds::unbounded(); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::ASCENDING, agg_col, one_day_preceding, unbounded_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {5, 5, 5, 2, 2, 5, 5, 4, 2, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedPrecedingAndFollowingCountMultiGroupTimestampASCNullsLast) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {1, 2, 2, 1, 3, 1, 2, 3, 4, 5}, {1, 1, 1, 0, 0, 1, 1, 1, 0, 0}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const unbounded_preceding = cudf::window_bounds::unbounded(); auto const unbounded_following = cudf::window_bounds::unbounded(); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::ASCENDING, agg_col, unbounded_preceding, unbounded_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL( output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{5, 5, 5, 5, 5, 5, 5, 5, 5, 5}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedPrecedingCountMultiGroupTimestampDESCNullsFirst) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {4, 3, 2, 1, 0, 9, 8, 7, 6, 5}, {0, 0, 0, 1, 1, 0, 0, 1, 1, 1}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const unbounded_preceding = cudf::window_bounds::unbounded(); auto const one_day_following = cudf::window_bounds::get(1L); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::DESCENDING, agg_col, unbounded_preceding, one_day_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {3, 3, 3, 5, 5, 2, 2, 4, 5, 5}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedFollowingCountMultiGroupTimestampDESCNullsFirst) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {4, 3, 2, 1, 0, 9, 8, 7, 6, 5}, {0, 0, 0, 1, 1, 0, 0, 1, 1, 1}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const one_day_preceding = cudf::window_bounds::get(1L); auto const unbounded_following = cudf::window_bounds::unbounded(); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::DESCENDING, agg_col, one_day_preceding, unbounded_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {5, 5, 5, 2, 2, 5, 5, 3, 3, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedPrecedingAndFollowingCountMultiGroupTimestampDESCNullsFirst) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {4, 3, 2, 1, 0, 9, 8, 7, 6, 5}, {0, 0, 0, 1, 1, 0, 0, 1, 1, 1}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const unbounded_preceding = cudf::window_bounds::unbounded(); auto const unbounded_following = cudf::window_bounds::unbounded(); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::DESCENDING, agg_col, unbounded_preceding, unbounded_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL( output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{5, 5, 5, 5, 5, 5, 5, 5, 5, 5}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedPrecedingCountMultiGroupTimestampDESCNullsLast) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {4, 3, 2, 1, 0, 9, 8, 7, 6, 5}, {1, 1, 1, 0, 0, 1, 1, 1, 0, 0}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const unbounded_preceding = cudf::window_bounds::unbounded(); auto const one_day_following = cudf::window_bounds::get(1L); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::DESCENDING, agg_col, unbounded_preceding, one_day_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {2, 3, 3, 5, 5, 2, 3, 3, 5, 5}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedFollowingCountMultiGroupTimestampDESCNullsLast) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {4, 3, 2, 1, 0, 9, 8, 7, 6, 5}, {1, 1, 1, 0, 0, 1, 1, 1, 0, 0}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const one_day_preceding = cudf::window_bounds::get(1L); auto const unbounded_following = cudf::window_bounds::unbounded(); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::DESCENDING, agg_col, one_day_preceding, unbounded_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {5, 5, 4, 2, 2, 5, 5, 4, 2, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedPrecedingAndFollowingCountMultiGroupTimestampDESCNullsLast) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto const time_col = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ {4, 3, 2, 1, 0, 9, 8, 7, 6, 5}, {1, 1, 1, 0, 0, 1, 1, 1, 0, 0}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const unbounded_preceding = cudf::window_bounds::unbounded(); auto const unbounded_following = cudf::window_bounds::unbounded(); auto const min_periods = 1L; auto const output = cudf::grouped_time_range_rolling_window( grouping_keys, time_col, cudf::order::DESCENDING, agg_col, unbounded_preceding, unbounded_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL( output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{5, 5, 5, 5, 5, 5, 5, 5, 5, 5}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedPrecedingWindowSingleGroup) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const unbounded_preceding = cudf::window_bounds::unbounded(); auto const one_row_following = cudf::window_bounds::get(1L); auto const min_periods = 1L; auto const output = cudf::grouped_rolling_window(grouping_keys, agg_col, unbounded_preceding, one_row_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {2, 3, 4, 5, 5, 6, 7, 8, 9, 9}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedFollowingWindowSingleGroup) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const one_row_preceding = cudf::window_bounds::get(1L); auto const unbounded_following = cudf::window_bounds::unbounded(); auto const min_periods = 1L; auto const output = cudf::grouped_rolling_window(grouping_keys, agg_col, one_row_preceding, unbounded_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {9, 8, 7, 6, 5, 4, 4, 3, 2, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedPrecedingAndFollowingWindowSingleGroup) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const unbounded_preceding = cudf::window_bounds::unbounded(); auto const unbounded_following = cudf::window_bounds::unbounded(); auto const min_periods = 1L; auto const output = cudf::grouped_rolling_window(grouping_keys, agg_col, unbounded_preceding, unbounded_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL( output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{9, 9, 9, 9, 9, 9, 9, 9, 9, 9}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedPrecedingWindowMultiGroup) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 1, 1, 0, 1, 0, 1, 1, 1, 1}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const unbounded_preceding = cudf::window_bounds::unbounded(); auto const one_row_following = cudf::window_bounds::get(1L); auto const min_periods = 1L; auto const output = cudf::grouped_rolling_window(grouping_keys, agg_col, unbounded_preceding, one_row_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {1, 2, 2, 3, 3, 1, 2, 3, 4, 4}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedFollowingWindowMultiGroup) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 1, 1, 0, 1, 0, 1, 1, 1, 1}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const one_row_preceding = cudf::window_bounds::get(1L); auto const unbounded_following = cudf::window_bounds::unbounded(); auto const min_periods = 1L; auto const output = cudf::grouped_rolling_window(grouping_keys, agg_col, one_row_preceding, unbounded_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{ {3, 3, 2, 1, 1, 4, 4, 3, 2, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedPrecedingAndFollowingWindowMultiGroup) { using T = TypeParam; auto const grp_col = cudf::test::fixed_width_column_wrapper<T>{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; auto const agg_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 1, 1, 0, 1, 0, 1, 1, 1, 1}}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grp_col}}; auto const unbounded_preceding = cudf::window_bounds::unbounded(); auto const unbounded_following = cudf::window_bounds::unbounded(); auto const min_periods = 1L; auto const output = cudf::grouped_rolling_window(grouping_keys, agg_col, unbounded_preceding, unbounded_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL( output->view(), cudf::test::fixed_width_column_wrapper<cudf::size_type>{3, 3, 3, 3, 3, 4, 4, 4, 4, 4}); } TYPED_TEST(TypedUnboundedWindowTest, UnboundedPrecedingAndFollowingStructGroup) { // Test that grouping on STRUCT keys produces is possible. using T = TypeParam; using numerics = cudf::test::fixed_width_column_wrapper<T>; using result_t = cudf::test::fixed_width_column_wrapper<cudf::size_type>; auto const grp_col = [] { auto grp_col_inner = numerics{0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; return cudf::test::structs_column_wrapper{{grp_col_inner}}; }(); auto const agg_col = numerics{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, cudf::test::iterators::nulls_at({0, 3, 5})}; auto const grouping_keys = cudf::table_view{{grp_col}}; auto const unbounded_preceding = cudf::window_bounds::unbounded(); auto const unbounded_following = cudf::window_bounds::unbounded(); auto const min_periods = 1L; auto const output = cudf::grouped_rolling_window(grouping_keys, agg_col, unbounded_preceding, unbounded_following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output->view(), result_t{3, 3, 3, 3, 3, 4, 4, 4, 4, 4}); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/rolling/rolling_test.hpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed 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. */ #pragma once #include <cudf/aggregation.hpp> #include <cudf/detail/aggregation/aggregation.hpp> #include <cudf/utilities/traits.hpp> // return true if the aggregation is valid for the specified ColumnType // valid aggregations may still be further specialized (eg, is_string_specialized) template <typename ColumnType, cudf::aggregation::Kind op> static constexpr bool is_rolling_supported() { if (!cudf::detail::is_valid_aggregation<ColumnType, op>()) { return false; } else if (cudf::is_numeric<ColumnType>() or cudf::is_duration<ColumnType>()) { return (op == cudf::aggregation::SUM) or (op == cudf::aggregation::MIN) or (op == cudf::aggregation::MAX) or (op == cudf::aggregation::COUNT_VALID) or (op == cudf::aggregation::COUNT_ALL) or (op == cudf::aggregation::MEAN) or (op == cudf::aggregation::ROW_NUMBER) or (op == cudf::aggregation::LEAD) or (op == cudf::aggregation::LAG) or (op == cudf::aggregation::COLLECT_LIST); } else if (cudf::is_timestamp<ColumnType>()) { return (op == cudf::aggregation::MIN) or (op == cudf::aggregation::MAX) or (op == cudf::aggregation::COUNT_VALID) or (op == cudf::aggregation::COUNT_ALL) or (op == cudf::aggregation::ROW_NUMBER) or (op == cudf::aggregation::LEAD) or (op == cudf::aggregation::LAG) or (op == cudf::aggregation::COLLECT_LIST); } else if (cudf::is_fixed_point<ColumnType>()) { return (op == cudf::aggregation::SUM) or (op == cudf::aggregation::MIN) or (op == cudf::aggregation::MAX) or (op == cudf::aggregation::COUNT_VALID) or (op == cudf::aggregation::COUNT_ALL) or (op == cudf::aggregation::ROW_NUMBER) or (op == cudf::aggregation::LEAD) or (op == cudf::aggregation::LAG) or (op == cudf::aggregation::COLLECT_LIST); } else if (std::is_same<ColumnType, cudf::string_view>()) { return (op == cudf::aggregation::MIN) or (op == cudf::aggregation::MAX) or (op == cudf::aggregation::COUNT_VALID) or (op == cudf::aggregation::COUNT_ALL) or (op == cudf::aggregation::ROW_NUMBER) or (op == cudf::aggregation::COLLECT_LIST); } else if (std::is_same<ColumnType, cudf::list_view>()) { return (op == cudf::aggregation::COUNT_VALID) or (op == cudf::aggregation::COUNT_ALL) or (op == cudf::aggregation::ROW_NUMBER) or (op == cudf::aggregation::COLLECT_LIST); } else if (std::is_same<ColumnType, cudf::struct_view>()) { // TODO: Add support for COUNT_VALID, COUNT_ALL, ROW_NUMBER. return op == cudf::aggregation::COLLECT_LIST; } else { return false; } }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/rolling/range_window_bounds_test.cpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/rolling/range_window_bounds.hpp> #include <cudf/utilities/default_stream.hpp> #include <src/rolling/detail/range_window_bounds.hpp> #include <vector> struct RangeWindowBoundsTest : public cudf::test::BaseFixture {}; template <typename Timestamp> struct TimestampRangeWindowBoundsTest : RangeWindowBoundsTest {}; TYPED_TEST_SUITE(TimestampRangeWindowBoundsTest, cudf::test::TimestampTypes); TEST_F(RangeWindowBoundsTest, TestBasicTimestampRangeTypeMapping) { // Explicitly check that the programmatic mapping of orderby column types // to their respective range and range_rep types is accurate. static_assert(std::is_same_v<cudf::detail::range_type<cudf::timestamp_D>, cudf::duration_D>); static_assert(std::is_same_v<cudf::detail::range_type<cudf::timestamp_s>, cudf::duration_s>); static_assert(std::is_same_v<cudf::detail::range_type<cudf::timestamp_ms>, cudf::duration_ms>); static_assert(std::is_same_v<cudf::detail::range_type<cudf::timestamp_us>, cudf::duration_us>); static_assert(std::is_same_v<cudf::detail::range_type<cudf::timestamp_ns>, cudf::duration_ns>); static_assert(std::is_same_v<cudf::detail::range_rep_type<cudf::timestamp_D>, int32_t>); static_assert(std::is_same_v<cudf::detail::range_rep_type<cudf::timestamp_s>, int64_t>); static_assert(std::is_same_v<cudf::detail::range_rep_type<cudf::timestamp_ms>, int64_t>); static_assert(std::is_same_v<cudf::detail::range_rep_type<cudf::timestamp_us>, int64_t>); static_assert(std::is_same_v<cudf::detail::range_rep_type<cudf::timestamp_ns>, int64_t>); } TYPED_TEST(TimestampRangeWindowBoundsTest, BoundsConstruction) { using OrderByType = TypeParam; using range_type = cudf::detail::range_type<OrderByType>; using rep_type = cudf::detail::range_rep_type<OrderByType>; auto const dtype = cudf::data_type{cudf::type_to_id<OrderByType>()}; static_assert(cudf::is_duration<range_type>()); auto range_3 = cudf::range_window_bounds::get(cudf::duration_scalar<range_type>{3, true}); EXPECT_FALSE(range_3.is_unbounded() && "range_window_bounds constructed from scalar cannot be unbounded."); EXPECT_EQ( cudf::detail::range_comparable_value<OrderByType>(range_3, dtype, cudf::get_default_stream()), rep_type{3}); auto range_unbounded = cudf::range_window_bounds::unbounded(cudf::data_type{cudf::type_to_id<range_type>()}); EXPECT_TRUE(range_unbounded.is_unbounded() && "range_window_bounds::unbounded() must return an unbounded range."); EXPECT_EQ(cudf::detail::range_comparable_value<OrderByType>( range_unbounded, dtype, cudf::get_default_stream()), rep_type{}); } TYPED_TEST(TimestampRangeWindowBoundsTest, WrongRangeType) { using OrderByType = TypeParam; auto const dtype = cudf::data_type{cudf::type_to_id<OrderByType>()}; using wrong_range_type = std::conditional_t<std::is_same_v<OrderByType, cudf::timestamp_D>, cudf::duration_ns, cudf::duration_D>; auto range_3 = cudf::range_window_bounds::get(cudf::duration_scalar<wrong_range_type>{3, true}); EXPECT_THROW( cudf::detail::range_comparable_value<OrderByType>(range_3, dtype, cudf::get_default_stream()), cudf::logic_error); auto range_unbounded = cudf::range_window_bounds::unbounded(cudf::data_type{cudf::type_to_id<wrong_range_type>()}); EXPECT_THROW(cudf::detail::range_comparable_value<OrderByType>( range_unbounded, dtype, cudf::get_default_stream()), cudf::logic_error); } template <typename T> struct NumericRangeWindowBoundsTest : RangeWindowBoundsTest {}; using TypesForTest = cudf::test::IntegralTypesNotBool; TYPED_TEST_SUITE(NumericRangeWindowBoundsTest, TypesForTest); TYPED_TEST(NumericRangeWindowBoundsTest, BasicNumericRangeTypeMapping) { using T = TypeParam; using range_type = cudf::detail::range_type<T>; using range_rep_type = cudf::detail::range_rep_type<T>; static_assert(std::is_same_v<T, range_type>); static_assert(std::is_same_v<T, range_rep_type>); } TYPED_TEST(NumericRangeWindowBoundsTest, BoundsConstruction) { using OrderByType = TypeParam; using range_type = cudf::detail::range_type<OrderByType>; using rep_type = cudf::detail::range_rep_type<OrderByType>; auto const dtype = cudf::data_type{cudf::type_to_id<OrderByType>()}; static_assert(std::is_integral_v<range_type>); auto range_3 = cudf::range_window_bounds::get(cudf::numeric_scalar<range_type>{3, true}); EXPECT_FALSE(range_3.is_unbounded() && "range_window_bounds constructed from scalar cannot be unbounded."); EXPECT_EQ( cudf::detail::range_comparable_value<OrderByType>(range_3, dtype, cudf::get_default_stream()), rep_type{3}); auto range_unbounded = cudf::range_window_bounds::unbounded(cudf::data_type{cudf::type_to_id<range_type>()}); EXPECT_TRUE(range_unbounded.is_unbounded() && "range_window_bounds::unbounded() must return an unbounded range."); EXPECT_EQ(cudf::detail::range_comparable_value<OrderByType>( range_unbounded, dtype, cudf::get_default_stream()), rep_type{}); } TYPED_TEST(NumericRangeWindowBoundsTest, WrongRangeType) { using OrderByType = TypeParam; auto const dtype = cudf::data_type{cudf::type_to_id<OrderByType>()}; using wrong_range_type = std::conditional_t<std::is_same_v<OrderByType, int32_t>, int16_t, int32_t>; auto range_3 = cudf::range_window_bounds::get(cudf::numeric_scalar<wrong_range_type>{3, true}); EXPECT_THROW( cudf::detail::range_comparable_value<OrderByType>(range_3, dtype, cudf::get_default_stream()), cudf::logic_error); auto range_unbounded = cudf::range_window_bounds::unbounded(cudf::data_type{cudf::type_to_id<wrong_range_type>()}); EXPECT_THROW(cudf::detail::range_comparable_value<OrderByType>( range_unbounded, dtype, cudf::get_default_stream()), cudf::logic_error); } template <typename T> struct DecimalRangeBoundsTest : RangeWindowBoundsTest {}; TYPED_TEST_SUITE(DecimalRangeBoundsTest, cudf::test::FixedPointTypes); TYPED_TEST(DecimalRangeBoundsTest, BoundsConstruction) { using DecimalT = TypeParam; using Rep = cudf::detail::range_rep_type<DecimalT>; auto const dtype = cudf::data_type{cudf::type_to_id<DecimalT>()}; // Interval type must match the decimal type. static_assert(std::is_same_v<cudf::detail::range_type<DecimalT>, DecimalT>); auto const range_3 = cudf::range_window_bounds::get( cudf::fixed_point_scalar<DecimalT>{Rep{3}, numeric::scale_type{0}}); EXPECT_FALSE(range_3.is_unbounded() && "range_window_bounds constructed from scalar cannot be unbounded."); EXPECT_EQ( cudf::detail::range_comparable_value<DecimalT>(range_3, dtype, cudf::get_default_stream()), Rep{3}); auto const range_unbounded = cudf::range_window_bounds::unbounded(cudf::data_type{cudf::type_to_id<DecimalT>()}); EXPECT_TRUE(range_unbounded.is_unbounded() && "range_window_bounds::unbounded() must return an unbounded range."); } TYPED_TEST(DecimalRangeBoundsTest, Rescale) { using DecimalT = TypeParam; using RepT = typename DecimalT::rep; // Powers of 10. auto constexpr pow10 = std::array{1, 10, 100, 1000, 10000, 100000}; // Check that the rep has expected values at different range scales. auto const order_by_scale = -2; auto const order_by_data_type = cudf::data_type{cudf::type_to_id<DecimalT>(), order_by_scale}; for (auto const range_scale : {-2, -1, 0, 1, 2}) { auto const decimal_range_bounds = cudf::range_window_bounds::get( cudf::fixed_point_scalar<DecimalT>{RepT{20}, numeric::scale_type{range_scale}}); auto const rescaled_range_rep = cudf::detail::range_comparable_value<DecimalT>( decimal_range_bounds, order_by_data_type, cudf::get_default_stream()); EXPECT_EQ(rescaled_range_rep, RepT{20} * pow10[range_scale - order_by_scale]); } // Order By column scale cannot exceed range scale: { auto const decimal_range_bounds = cudf::range_window_bounds::get( cudf::fixed_point_scalar<DecimalT>{RepT{200}, numeric::scale_type{-3}}); EXPECT_THROW(cudf::detail::range_comparable_value<DecimalT>( decimal_range_bounds, order_by_data_type, cudf::get_default_stream()), cudf::logic_error); } }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/rolling/rolling_test.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 "rolling_test.hpp" #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/aggregation.hpp> #include <cudf/detail/aggregation/aggregation.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/dictionary/encode.hpp> #include <cudf/rolling.hpp> #include <cudf/unary.hpp> #include <cudf/utilities/bit.hpp> #include <cudf/utilities/traits.hpp> #include <src/rolling/detail/rolling.hpp> #include <thrust/host_vector.h> #include <thrust/iterator/constant_iterator.h> #include <thrust/iterator/counting_iterator.h> #include <limits> #include <type_traits> #include <vector> class RollingStringTest : public cudf::test::BaseFixture {}; TEST_F(RollingStringTest, NoNullStringMinMaxCount) { cudf::test::strings_column_wrapper input( {"This", "is", "rolling", "test", "being", "operated", "on", "string", "column"}); std::vector<cudf::size_type> window{2}; cudf::test::strings_column_wrapper expected_min( {"This", "This", "being", "being", "being", "being", "column", "column", "column"}, {1, 1, 1, 1, 1, 1, 1, 1, 1}); cudf::test::strings_column_wrapper expected_max( {"rolling", "test", "test", "test", "test", "string", "string", "string", "string"}, {1, 1, 1, 1, 1, 1, 1, 1, 1}); cudf::test::fixed_width_column_wrapper<cudf::size_type> expected_count( {3, 4, 4, 4, 4, 4, 4, 3, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1}); auto got_min = cudf::rolling_window( input, window[0], window[0], 1, *cudf::make_min_aggregation<cudf::rolling_aggregation>()); auto got_max = cudf::rolling_window( input, window[0], window[0], 1, *cudf::make_max_aggregation<cudf::rolling_aggregation>()); auto got_count_valid = cudf::rolling_window( input, window[0], window[0], 1, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); auto got_count_all = cudf::rolling_window( input, window[0], window[0], 1, *cudf::make_count_aggregation<cudf::rolling_aggregation>(cudf::null_policy::INCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_min, got_min->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_max, got_max->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_count, got_count_valid->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_count, got_count_all->view()); } TEST_F(RollingStringTest, NullStringMinMaxCount) { cudf::test::strings_column_wrapper input( {"This", "is", "rolling", "test", "being", "operated", "on", "string", "column"}, {1, 0, 0, 1, 0, 1, 1, 1, 0}); std::vector<cudf::size_type> window{2}; cudf::test::strings_column_wrapper expected_min( {"This", "This", "test", "operated", "on", "on", "on", "on", "string"}, {1, 1, 1, 1, 1, 1, 1, 1, 1}); cudf::test::strings_column_wrapper expected_max( {"This", "test", "test", "test", "test", "string", "string", "string", "string"}, {1, 1, 1, 1, 1, 1, 1, 1, 1}); cudf::test::fixed_width_column_wrapper<cudf::size_type> expected_count_val( {1, 2, 1, 2, 3, 3, 3, 2, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1}); cudf::test::fixed_width_column_wrapper<cudf::size_type> expected_count_all( {3, 4, 4, 4, 4, 4, 4, 3, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1}); auto got_min = cudf::rolling_window( input, window[0], window[0], 1, *cudf::make_min_aggregation<cudf::rolling_aggregation>()); auto got_max = cudf::rolling_window( input, window[0], window[0], 1, *cudf::make_max_aggregation<cudf::rolling_aggregation>()); auto got_count_valid = cudf::rolling_window( input, window[0], window[0], 1, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); auto got_count_all = cudf::rolling_window( input, window[0], window[0], 1, *cudf::make_count_aggregation<cudf::rolling_aggregation>(cudf::null_policy::INCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_min, got_min->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_max, got_max->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_count_val, got_count_valid->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_count_all, got_count_all->view()); } TEST_F(RollingStringTest, MinPeriods) { cudf::test::strings_column_wrapper input( {"This", "is", "rolling", "test", "being", "operated", "on", "string", "column"}, {1, 0, 0, 1, 0, 1, 1, 1, 0}); std::vector<cudf::size_type> window{2}; cudf::test::strings_column_wrapper expected_min( {"This", "This", "This", "operated", "on", "on", "on", "on", "on"}, {0, 0, 0, 0, 1, 1, 1, 0, 0}); cudf::test::strings_column_wrapper expected_max( {"This", "test", "test", "test", "test", "string", "string", "string", "string"}, {0, 0, 0, 0, 1, 1, 1, 0, 0}); cudf::test::fixed_width_column_wrapper<cudf::size_type> expected_count_val( {1, 2, 1, 2, 3, 3, 3, 2, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 0}); cudf::test::fixed_width_column_wrapper<cudf::size_type> expected_count_all( {3, 4, 4, 4, 4, 4, 4, 3, 2}, {0, 1, 1, 1, 1, 1, 1, 0, 0}); auto got_min = cudf::rolling_window( input, window[0], window[0], 3, *cudf::make_min_aggregation<cudf::rolling_aggregation>()); auto got_max = cudf::rolling_window( input, window[0], window[0], 3, *cudf::make_max_aggregation<cudf::rolling_aggregation>()); auto got_count_valid = cudf::rolling_window( input, window[0], window[0], 3, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); auto got_count_all = cudf::rolling_window( input, window[0], window[0], 4, *cudf::make_count_aggregation<cudf::rolling_aggregation>(cudf::null_policy::INCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_min, got_min->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_max, got_max->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_count_val, got_count_valid->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_count_all, got_count_all->view()); } // ========================================================================================= class RollingStructTest : public cudf::test::BaseFixture {}; TEST_F(RollingStructTest, NoNullStructsMinMaxCount) { using strings_col = cudf::test::strings_column_wrapper; using ints_col = cudf::test::fixed_width_column_wrapper<int32_t>; using structs_col = cudf::test::structs_column_wrapper; auto const do_test = [](auto const& input) { auto const expected_min = [] { auto child1 = strings_col{ "This", "This", "being", "being", "being", "being", "column", "column", "column"}; auto child2 = ints_col{1, 1, 5, 5, 5, 5, 9, 9, 9}; return structs_col{{child1, child2}, cudf::test::iterators::no_nulls()}; }(); auto const expected_max = [] { auto child1 = strings_col{ "rolling", "test", "test", "test", "test", "string", "string", "string", "string"}; auto child2 = ints_col{3, 4, 4, 4, 4, 8, 8, 8, 8}; return structs_col{{child1, child2}, cudf::test::iterators::no_nulls()}; }(); auto const expected_count = ints_col{{3, 4, 4, 4, 4, 4, 4, 3, 2}, cudf::test::iterators::no_nulls()}; auto constexpr preceding = 2; auto constexpr following = 2; auto constexpr min_period = 1; auto const result_min = cudf::rolling_window(input, preceding, following, min_period, *cudf::make_min_aggregation<cudf::rolling_aggregation>()); auto const result_max = cudf::rolling_window(input, preceding, following, min_period, *cudf::make_max_aggregation<cudf::rolling_aggregation>()); auto const result_count_valid = cudf::rolling_window(input, preceding, following, min_period, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); auto const result_count_all = cudf::rolling_window( input, preceding, following, min_period, *cudf::make_count_aggregation<cudf::rolling_aggregation>(cudf::null_policy::INCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_min, result_min->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_max, result_max->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_count, result_count_valid->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_count, result_count_all->view()); }; auto const input_no_sliced = [] { auto child1 = strings_col{"This", "is", "rolling", "test", "being", "operated", "on", "string", "column"}; auto child2 = ints_col{1, 2, 3, 4, 5, 6, 7, 8, 9}; return structs_col{{child1, child2}}; }(); auto const input_before_sliced = [] { auto constexpr dont_care{0}; auto child1 = strings_col{"1dont_care", "1dont_care", "@dont_care", "This", "is", "rolling", "test", "being", "operated", "on", "string", "column", "1dont_care", "1dont_care", "@dont_care"}; auto child2 = ints_col{ dont_care, dont_care, dont_care, 1, 2, 3, 4, 5, 6, 7, 8, 9, dont_care, dont_care, dont_care}; return structs_col{{child1, child2}}; }(); auto const input_sliced = cudf::slice(input_before_sliced, {3, 12})[0]; do_test(input_no_sliced); do_test(input_sliced); } TEST_F(RollingStructTest, NullChildrenMinMaxCount) { using strings_col = cudf::test::strings_column_wrapper; using ints_col = cudf::test::fixed_width_column_wrapper<int32_t>; using structs_col = cudf::test::structs_column_wrapper; auto const input = [] { auto child1 = strings_col{ {"This", "" /*NULL*/, "" /*NULL*/, "test", "" /*NULL*/, "operated", "on", "string", "column"}, cudf::test::iterators::nulls_at({1, 2, 4})}; auto child2 = ints_col{1, 2, 3, 4, 5, 6, 7, 8, 9}; return structs_col{{child1, child2}}; }(); auto const expected_min = [] { auto child1 = strings_col{{"" /*NULL*/, "" /*NULL*/, "" /*NULL*/, "" /*NULL*/, "" /*NULL*/, "" /*NULL*/, "column", "column", "column"}, cudf::test::iterators::nulls_at({0, 1, 2, 3, 4, 5})}; auto child2 = ints_col{2, 2, 2, 3, 5, 5, 9, 9, 9}; return structs_col{{child1, child2}, cudf::test::iterators::no_nulls()}; }(); auto const expected_max = [] { auto child1 = strings_col{"This", "test", "test", "test", "test", "string", "string", "string", "string"}; auto child2 = ints_col{1, 4, 4, 4, 4, 8, 8, 8, 8}; return structs_col{{child1, child2}, cudf::test::iterators::no_nulls()}; }(); auto const expected_count = ints_col{{3, 4, 4, 4, 4, 4, 4, 3, 2}, cudf::test::iterators::no_nulls()}; auto constexpr preceding = 2; auto constexpr following = 2; auto constexpr min_period = 1; auto const result_min = cudf::rolling_window(input, preceding, following, min_period, *cudf::make_min_aggregation<cudf::rolling_aggregation>()); auto const result_max = cudf::rolling_window(input, preceding, following, min_period, *cudf::make_max_aggregation<cudf::rolling_aggregation>()); auto const result_count_valid = cudf::rolling_window(input, preceding, following, min_period, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); auto const result_count_all = cudf::rolling_window( input, preceding, following, min_period, *cudf::make_count_aggregation<cudf::rolling_aggregation>(cudf::null_policy::INCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_min, result_min->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_max, result_max->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_count, result_count_valid->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_count, result_count_all->view()); } TEST_F(RollingStructTest, NullParentMinMaxCount) { using strings_col = cudf::test::strings_column_wrapper; using ints_col = cudf::test::fixed_width_column_wrapper<int32_t>; using structs_col = cudf::test::structs_column_wrapper; auto constexpr null{0}; auto const input = [] { auto child1 = strings_col{"This", "" /*NULL*/, "" /*NULL*/, "test", "" /*NULL*/, "operated", "on", "string", "" /*NULL*/}; auto child2 = ints_col{1, null, null, 4, null, 6, 7, 8, null}; return structs_col{{child1, child2}, cudf::test::iterators::nulls_at({1, 2, 4, 8})}; }(); auto const expected_min = [] { auto child1 = strings_col{"This", "This", "test", "operated", "on", "on", "on", "on", "string"}; auto child2 = ints_col{1, 1, 4, 6, 7, 7, 7, 7, 8}; return structs_col{{child1, child2}, cudf::test::iterators::no_nulls()}; }(); auto const expected_max = [] { auto child1 = strings_col{"This", "test", "test", "test", "test", "string", "string", "string", "string"}; auto child2 = ints_col{1, 4, 4, 4, 4, 8, 8, 8, 8}; return structs_col{{child1, child2}, cudf::test::iterators::no_nulls()}; }(); auto const expected_count_valid = ints_col{{1, 2, 1, 2, 3, 3, 3, 2, 1}, cudf::test::iterators::no_nulls()}; auto const expected_count_all = ints_col{{3, 4, 4, 4, 4, 4, 4, 3, 2}, cudf::test::iterators::no_nulls()}; auto constexpr preceding = 2; auto constexpr following = 2; auto constexpr min_period = 1; auto const result_min = cudf::rolling_window(input, preceding, following, min_period, *cudf::make_min_aggregation<cudf::rolling_aggregation>()); auto const result_max = cudf::rolling_window(input, preceding, following, min_period, *cudf::make_max_aggregation<cudf::rolling_aggregation>()); auto const result_count_valid = cudf::rolling_window(input, preceding, following, min_period, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); auto const result_count_all = cudf::rolling_window( input, preceding, following, min_period, *cudf::make_count_aggregation<cudf::rolling_aggregation>(cudf::null_policy::INCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_min, result_min->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_max, result_max->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_count_valid, result_count_valid->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_count_all, result_count_all->view()); } // ========================================================================================= template <typename T> class RollingTest : public cudf::test::BaseFixture { protected: // input as column_wrapper void run_test_col(cudf::column_view const& input, std::vector<cudf::size_type> const& preceding_window, std::vector<cudf::size_type> const& following_window, cudf::size_type min_periods, cudf::rolling_aggregation const& op) { std::unique_ptr<cudf::column> output; // wrap windows if (preceding_window.size() > 1) { cudf::test::fixed_width_column_wrapper<cudf::size_type> preceding_window_wrapper( preceding_window.begin(), preceding_window.end()); cudf::test::fixed_width_column_wrapper<cudf::size_type> following_window_wrapper( following_window.begin(), following_window.end()); EXPECT_NO_THROW( output = cudf::rolling_window( input, preceding_window_wrapper, following_window_wrapper, min_periods, op)); } else { EXPECT_NO_THROW(output = cudf::rolling_window( input, preceding_window[0], following_window[0], min_periods, op)); } auto reference = create_reference_output(op, input, preceding_window, following_window, min_periods); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*output, *reference); } // helper function to test all aggregators void run_test_col_agg(cudf::column_view const& input, std::vector<cudf::size_type> const& preceding_window, std::vector<cudf::size_type> const& following_window, cudf::size_type min_periods) { // test all supported aggregators run_test_col(input, preceding_window, following_window, min_periods, *cudf::make_min_aggregation<cudf::rolling_aggregation>()); run_test_col(input, preceding_window, following_window, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); run_test_col( input, preceding_window, following_window, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>(cudf::null_policy::INCLUDE)); run_test_col(input, preceding_window, following_window, min_periods, *cudf::make_max_aggregation<cudf::rolling_aggregation>()); if (not cudf::is_timestamp(input.type())) { run_test_col(input, preceding_window, following_window, min_periods, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()); run_test_col(input, preceding_window, following_window, min_periods, *cudf::make_mean_aggregation<cudf::rolling_aggregation>()); } } private: // use SFINAE to only instantiate for supported combinations // specialization for COUNT_VALID, COUNT_ALL template <bool include_nulls> std::unique_ptr<cudf::column> create_count_reference_output( cudf::column_view const& input, std::vector<cudf::size_type> const& preceding_window_col, std::vector<cudf::size_type> const& following_window_col, cudf::size_type min_periods) { cudf::size_type num_rows = input.size(); std::vector<cudf::size_type> ref_data(num_rows); std::vector<bool> ref_valid(num_rows); // input data and mask std::vector<cudf::bitmask_type> in_valid = cudf::test::bitmask_to_host(input); cudf::bitmask_type* valid_mask = in_valid.data(); for (cudf::size_type i = 0; i < num_rows; i++) { // load sizes min_periods = std::max(min_periods, 1); // at least one observation is required // compute bounds auto preceding_window = preceding_window_col[i % preceding_window_col.size()]; auto following_window = following_window_col[i % following_window_col.size()]; cudf::size_type start = std::min(num_rows, std::max(0, i - preceding_window + 1)); cudf::size_type end = std::min(num_rows, std::max(0, i + following_window + 1)); cudf::size_type start_index = std::min(start, end); cudf::size_type end_index = std::max(start, end); // aggregate cudf::size_type count = 0; for (cudf::size_type j = start_index; j < end_index; j++) { if (include_nulls || !input.nullable() || cudf::bit_is_set(valid_mask, j)) count++; } ref_valid[i] = ((end_index - start_index) >= min_periods); if (ref_valid[i]) ref_data[i] = count; } cudf::test::fixed_width_column_wrapper<cudf::size_type> col( ref_data.begin(), ref_data.end(), ref_valid.begin()); return col.release(); } template <typename agg_op, cudf::aggregation::Kind k, typename OutputType, bool is_mean, std::enable_if_t<is_rolling_supported<T, k>()>* = nullptr> std::unique_ptr<cudf::column> create_reference_output( cudf::column_view const& input, std::vector<cudf::size_type> const& preceding_window_col, std::vector<cudf::size_type> const& following_window_col, cudf::size_type min_periods) { cudf::size_type num_rows = input.size(); thrust::host_vector<OutputType> ref_data(num_rows); thrust::host_vector<bool> ref_valid(num_rows); // input data and mask auto [in_col, in_valid] = cudf::test::to_host<T>(input); cudf::bitmask_type* valid_mask = in_valid.data(); agg_op op; for (cudf::size_type i = 0; i < num_rows; i++) { OutputType val = agg_op::template identity<OutputType>(); // load sizes min_periods = std::max(min_periods, 1); // at least one observation is required // compute bounds auto preceding_window = preceding_window_col[i % preceding_window_col.size()]; auto following_window = following_window_col[i % following_window_col.size()]; cudf::size_type start = std::min(num_rows, std::max(0, i - preceding_window + 1)); cudf::size_type end = std::min(num_rows, std::max(0, i + following_window + 1)); cudf::size_type start_index = std::min(start, end); cudf::size_type end_index = std::max(start, end); // aggregate cudf::size_type count = 0; for (cudf::size_type j = start_index; j < end_index; j++) { if (!input.nullable() || cudf::bit_is_set(valid_mask, j)) { val = op(static_cast<OutputType>(in_col[j]), val); count++; } } ref_valid[i] = (count >= min_periods); if (ref_valid[i]) { cudf::detail::rolling_store_output_functor<OutputType, is_mean>{}(ref_data[i], val, count); } } cudf::test::fixed_width_column_wrapper<OutputType> col( ref_data.begin(), ref_data.end(), ref_valid.begin()); return col.release(); } template <typename agg_op, cudf::aggregation::Kind k, typename OutputType, bool is_mean, std::enable_if_t<!is_rolling_supported<T, k>()>* = nullptr> std::unique_ptr<cudf::column> create_reference_output( cudf::column_view const& input, std::vector<cudf::size_type> const& preceding_window_col, std::vector<cudf::size_type> const& following_window_col, cudf::size_type min_periods) { CUDF_FAIL("Unsupported combination of type and aggregation"); } std::unique_ptr<cudf::column> create_reference_output( cudf::rolling_aggregation const& op, cudf::column_view const& input, std::vector<cudf::size_type> const& preceding_window, std::vector<cudf::size_type> const& following_window, cudf::size_type min_periods) { // unroll aggregation types switch (op.kind) { case cudf::aggregation::SUM: return create_reference_output<cudf::DeviceSum, cudf::aggregation::SUM, cudf::detail::target_type_t<T, cudf::aggregation::SUM>, false>( input, preceding_window, following_window, min_periods); case cudf::aggregation::MIN: return create_reference_output<cudf::DeviceMin, cudf::aggregation::MIN, cudf::detail::target_type_t<T, cudf::aggregation::MIN>, false>( input, preceding_window, following_window, min_periods); case cudf::aggregation::MAX: return create_reference_output<cudf::DeviceMax, cudf::aggregation::MAX, cudf::detail::target_type_t<T, cudf::aggregation::MAX>, false>( input, preceding_window, following_window, min_periods); case cudf::aggregation::COUNT_VALID: return create_count_reference_output<false>( input, preceding_window, following_window, min_periods); case cudf::aggregation::COUNT_ALL: return create_count_reference_output<true>( input, preceding_window, following_window, min_periods); case cudf::aggregation::MEAN: return create_reference_output<cudf::DeviceSum, cudf::aggregation::MEAN, cudf::detail::target_type_t<T, cudf::aggregation::MEAN>, true>( input, preceding_window, following_window, min_periods); default: return cudf::test::fixed_width_column_wrapper<T>({}).release(); } } }; template <typename T> class RollingVarStdTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(RollingVarStdTest, cudf::test::FixedWidthTypesWithoutChrono); class RollingtVarStdTestUntyped : public cudf::test::BaseFixture {}; class RollingErrorTest : public cudf::test::BaseFixture {}; // negative sizes TEST_F(RollingErrorTest, NegativeMinPeriods) { const std::vector<cudf::size_type> col_data = {0, 1, 2, 0, 4}; const std::vector<bool> col_valid = {1, 1, 1, 0, 1}; cudf::test::fixed_width_column_wrapper<cudf::size_type> input( col_data.begin(), col_data.end(), col_valid.begin()); EXPECT_THROW( cudf::rolling_window(input, 2, 2, -2, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); } // window array size mismatch TEST_F(RollingErrorTest, WindowArraySizeMismatch) { const std::vector<cudf::size_type> col_data = {0, 1, 2, 0, 4}; const std::vector<bool> col_valid = {1, 1, 1, 0, 1}; cudf::test::fixed_width_column_wrapper<cudf::size_type> input( col_data.begin(), col_data.end(), col_valid.begin()); std::vector<cudf::size_type> five({2, 1, 2, 1, 4}); std::vector<cudf::size_type> four({1, 2, 3, 4}); cudf::test::fixed_width_column_wrapper<cudf::size_type> five_elements(five.begin(), five.end()); cudf::test::fixed_width_column_wrapper<cudf::size_type> four_elements(four.begin(), four.end()); // this runs ok EXPECT_NO_THROW(cudf::rolling_window(input, five_elements, five_elements, 1, *cudf::make_sum_aggregation<cudf::rolling_aggregation>())); // mismatch for the window array EXPECT_THROW(cudf::rolling_window(input, four_elements, five_elements, 1, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); // mismatch for the forward window array EXPECT_THROW(cudf::rolling_window(input, five_elements, four_elements, 1, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); } TEST_F(RollingErrorTest, EmptyInput) { cudf::test::fixed_width_column_wrapper<int32_t> empty_col{}; std::unique_ptr<cudf::column> output; EXPECT_NO_THROW(output = cudf::rolling_window( empty_col, 2, 0, 2, *cudf::make_sum_aggregation<cudf::rolling_aggregation>())); EXPECT_EQ(output->size(), 0); cudf::test::fixed_width_column_wrapper<int32_t> preceding_window{}; cudf::test::fixed_width_column_wrapper<int32_t> following_window{}; EXPECT_NO_THROW(output = cudf::rolling_window(empty_col, preceding_window, following_window, 2, *cudf::make_sum_aggregation<cudf::rolling_aggregation>())); EXPECT_EQ(output->size(), 0); cudf::test::fixed_width_column_wrapper<int32_t> nonempty_col{{1, 2, 3}}; EXPECT_NO_THROW(output = cudf::rolling_window(nonempty_col, preceding_window, following_window, 2, *cudf::make_sum_aggregation<cudf::rolling_aggregation>())); EXPECT_EQ(output->size(), 0); } TEST_F(RollingErrorTest, SizeMismatch) { cudf::test::fixed_width_column_wrapper<int32_t> nonempty_col{{1, 2, 3}}; std::unique_ptr<cudf::column> output; { cudf::test::fixed_width_column_wrapper<int32_t> preceding_window{{1, 1}}; // wrong size cudf::test::fixed_width_column_wrapper<int32_t> following_window{{1, 1, 1}}; EXPECT_THROW( output = cudf::rolling_window(nonempty_col, preceding_window, following_window, 2, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); } { cudf::test::fixed_width_column_wrapper<int32_t> preceding_window{{1, 1, 1}}; cudf::test::fixed_width_column_wrapper<int32_t> following_window{{1, 2}}; // wrong size EXPECT_THROW( output = cudf::rolling_window(nonempty_col, preceding_window, following_window, 2, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); } } TEST_F(RollingErrorTest, WindowWrongDtype) { cudf::test::fixed_width_column_wrapper<int32_t> nonempty_col{{1, 2, 3}}; std::unique_ptr<cudf::column> output; cudf::test::fixed_width_column_wrapper<float> preceding_window{{1.0f, 1.0f, 1.0f}}; cudf::test::fixed_width_column_wrapper<float> following_window{{1.0f, 1.0f, 1.0f}}; EXPECT_THROW( output = cudf::rolling_window(nonempty_col, preceding_window, following_window, 2, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); } // incorrect type/aggregation combo: sum of timestamps TEST_F(RollingErrorTest, SumTimestampNotSupported) { constexpr cudf::size_type size{10}; cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep> input_D( thrust::make_counting_iterator(0), thrust::make_counting_iterator(size)); cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep> input_s( thrust::make_counting_iterator(0), thrust::make_counting_iterator(size)); cudf::test::fixed_width_column_wrapper<cudf::timestamp_ms, cudf::timestamp_ms::rep> input_ms( thrust::make_counting_iterator(0), thrust::make_counting_iterator(size)); cudf::test::fixed_width_column_wrapper<cudf::timestamp_us, cudf::timestamp_us::rep> input_us( thrust::make_counting_iterator(0), thrust::make_counting_iterator(size)); cudf::test::fixed_width_column_wrapper<cudf::timestamp_ns, cudf::timestamp_ns::rep> input_ns( thrust::make_counting_iterator(0), thrust::make_counting_iterator(size)); EXPECT_THROW(cudf::rolling_window( input_D, 2, 2, 0, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); EXPECT_THROW(cudf::rolling_window( input_s, 2, 2, 0, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); EXPECT_THROW(cudf::rolling_window( input_ms, 2, 2, 0, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); EXPECT_THROW(cudf::rolling_window( input_us, 2, 2, 0, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); EXPECT_THROW(cudf::rolling_window( input_ns, 2, 2, 0, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); } // incorrect type/aggregation combo: mean of timestamps TEST_F(RollingErrorTest, MeanTimestampNotSupported) { constexpr cudf::size_type size{10}; cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep> input_D( thrust::make_counting_iterator(0), thrust::make_counting_iterator(size)); cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep> input_s( thrust::make_counting_iterator(0), thrust::make_counting_iterator(size)); cudf::test::fixed_width_column_wrapper<cudf::timestamp_ms, cudf::timestamp_ms::rep> input_ms( thrust::make_counting_iterator(0), thrust::make_counting_iterator(size)); cudf::test::fixed_width_column_wrapper<cudf::timestamp_us, cudf::timestamp_us::rep> input_us( thrust::make_counting_iterator(0), thrust::make_counting_iterator(size)); cudf::test::fixed_width_column_wrapper<cudf::timestamp_ns, cudf::timestamp_ns::rep> input_ns( thrust::make_counting_iterator(0), thrust::make_counting_iterator(size)); EXPECT_THROW(cudf::rolling_window( input_D, 2, 2, 0, *cudf::make_mean_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); EXPECT_THROW(cudf::rolling_window( input_s, 2, 2, 0, *cudf::make_mean_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); EXPECT_THROW(cudf::rolling_window( input_ms, 2, 2, 0, *cudf::make_mean_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); EXPECT_THROW(cudf::rolling_window( input_us, 2, 2, 0, *cudf::make_mean_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); EXPECT_THROW(cudf::rolling_window( input_ns, 2, 2, 0, *cudf::make_mean_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); } TYPED_TEST_SUITE(RollingTest, cudf::test::FixedWidthTypesWithoutFixedPoint); // simple example from Pandas docs TYPED_TEST(RollingTest, SimpleStatic) { // https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html auto const col_data = cudf::test::make_type_param_vector<TypeParam>({0, 1, 2, 0, 4}); const std::vector<bool> col_mask = {1, 1, 1, 0, 1}; cudf::test::fixed_width_column_wrapper<TypeParam> input( col_data.begin(), col_data.end(), col_mask.begin()); std::vector<cudf::size_type> window{2}; // static sizes this->run_test_col_agg(input, window, window, 1); } TYPED_TEST(RollingVarStdTest, SimpleStaticVarianceStd) { #define XXX 0 // NULL stub using ResultType = double; double const nan = std::numeric_limits<double>::signaling_NaN(); cudf::size_type const ddof = 1, min_periods = 0, preceding_window = 2, following_window = 1; auto const col_data = cudf::test::make_type_param_vector<TypeParam>({XXX, XXX, 9, 5, XXX, XXX, XXX, 0, 8, 5, 8}); const std::vector<bool> col_mask = {0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1}; auto const expected_var = cudf::is_boolean<TypeParam>() ? std::vector<ResultType>{XXX, nan, 0, 0, nan, XXX, nan, 0.5, 0.3333333333333333, 0, 0} : std::vector<ResultType>{XXX, nan, 8, 8, nan, XXX, nan, 32, 16.33333333333333, 3, 4.5}; std::vector<ResultType> expected_std(expected_var.size()); std::transform(expected_var.begin(), expected_var.end(), expected_std.begin(), [](auto const& x) { return std::sqrt(x); }); const std::vector<bool> expected_mask = {0, /* all null window */ 1, /* 0 div 0, nan */ 1, 1, 1, /* 0 div 0, nan */ 0, /* all null window */ 1, /* 0 div 0, nan */ 1, 1, 1, 1}; cudf::test::fixed_width_column_wrapper<TypeParam> input( col_data.begin(), col_data.end(), col_mask.begin()); cudf::test::fixed_width_column_wrapper<ResultType> var_expect( expected_var.begin(), expected_var.end(), expected_mask.begin()); cudf::test::fixed_width_column_wrapper<ResultType> std_expect( expected_std.begin(), expected_std.end(), expected_mask.begin()); std::unique_ptr<cudf::column> var_result, std_result; // static sizes EXPECT_NO_THROW(var_result = cudf::rolling_window(input, preceding_window, following_window, min_periods, dynamic_cast<cudf::rolling_aggregation const&>( *cudf::make_variance_aggregation(ddof)));); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*var_result, var_expect); EXPECT_NO_THROW(std_result = cudf::rolling_window(input, preceding_window, following_window, min_periods, dynamic_cast<cudf::rolling_aggregation const&>( *cudf::make_std_aggregation(ddof)));); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*std_result, std_expect); #undef XXX } TEST_F(RollingtVarStdTestUntyped, SimpleStaticVarianceStdInfNaN) { #define XXX 0. // NULL stub using ResultType = double; double const inf = std::numeric_limits<double>::infinity(); double const nan = std::numeric_limits<double>::signaling_NaN(); cudf::size_type const ddof = 1, min_periods = 1, preceding_window = 3, following_window = 0; auto const col_data = cudf::test::make_type_param_vector<double>({5., 4., XXX, inf, 4., 8., 0., nan, XXX, 5.}); const std::vector<bool> col_mask = {1, 1, 0, 1, 1, 1, 1, 1, 0, 1}; auto const expected_var = std::vector<ResultType>{nan, 0.5, 0.5, nan, nan, nan, 16, nan, nan, nan}; std::vector<ResultType> expected_std(expected_var.size()); std::transform(expected_var.begin(), expected_var.end(), expected_std.begin(), [](auto const& x) { return std::sqrt(x); }); const std::vector<bool> expected_mask = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; cudf::test::fixed_width_column_wrapper<double> input( col_data.begin(), col_data.end(), col_mask.begin()); cudf::test::fixed_width_column_wrapper<ResultType> var_expect( expected_var.begin(), expected_var.end(), expected_mask.begin()); cudf::test::fixed_width_column_wrapper<ResultType> std_expect( expected_std.begin(), expected_std.end(), expected_mask.begin()); std::unique_ptr<cudf::column> var_result, std_result; // static sizes EXPECT_NO_THROW(var_result = cudf::rolling_window(input, preceding_window, following_window, min_periods, dynamic_cast<cudf::rolling_aggregation const&>( *cudf::make_variance_aggregation(ddof)));); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*var_result, var_expect); EXPECT_NO_THROW(std_result = cudf::rolling_window(input, preceding_window, following_window, min_periods, dynamic_cast<cudf::rolling_aggregation const&>( *cudf::make_std_aggregation(ddof)));); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*std_result, std_expect); #undef XXX } /* // negative sizes TYPED_TEST(RollingTest, NegativeWindowSizes) { auto const col_data = cudf::test::make_type_param_vector<TypeParam>({0, 1, 2, 0, 4}); auto const col_valid = std::vector<bool>{1, 1, 1, 0, 1}; cudf::test::fixed_width_column_wrapper<TypeParam> input( col_data.begin(), col_data.end(), col_valid.begin()); std::vector<cudf::size_type> window{3}; std::vector<cudf::size_type> negative_window{-2}; this->run_test_col_agg(input, negative_window, window, 1); this->run_test_col_agg(input, window, negative_window, 1); this->run_test_col_agg(input, negative_window, negative_window, 1); } */ // simple example from Pandas docs: TYPED_TEST(RollingTest, SimpleDynamic) { // https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html auto const col_data = cudf::test::make_type_param_vector<TypeParam>({0, 1, 2, 0, 4}); const std::vector<bool> col_mask = {1, 1, 1, 0, 1}; cudf::test::fixed_width_column_wrapper<TypeParam> input( col_data.begin(), col_data.end(), col_mask.begin()); std::vector<cudf::size_type> preceding_window({1, 2, 3, 4, 2}); std::vector<cudf::size_type> following_window({2, 1, 2, 1, 2}); // dynamic sizes this->run_test_col_agg(input, preceding_window, following_window, 1); } // this is a special test to check the volatile count variable issue (see rolling.cu for detail) TYPED_TEST(RollingTest, VolatileCount) { auto const col_data = cudf::test::make_type_param_vector<TypeParam>({8, 70, 45, 20, 59, 80}); const std::vector<bool> col_mask = {1, 1, 0, 0, 1, 0}; cudf::test::fixed_width_column_wrapper<TypeParam> input( col_data.begin(), col_data.end(), col_mask.begin()); std::vector<cudf::size_type> preceding_window({5, 9, 4, 8, 3, 3}); std::vector<cudf::size_type> following_window({1, 1, 9, 2, 8, 9}); // dynamic sizes this->run_test_col_agg(input, preceding_window, following_window, 1); } // all rows are invalid TYPED_TEST(RollingTest, AllInvalid) { cudf::size_type num_rows = 1000; std::vector<TypeParam> col_data(num_rows); std::vector<bool> col_mask(num_rows, 0); cudf::test::fixed_width_column_wrapper<TypeParam> input( col_data.begin(), col_data.end(), col_mask.begin()); std::vector<cudf::size_type> window({100}); cudf::size_type periods = 100; this->run_test_col_agg(input, window, window, periods); } // window = following_window = 0 // Note: Preceding includes current row, so its value is set to 1. TYPED_TEST(RollingTest, ZeroWindow) { cudf::size_type num_rows = 1000; std::vector<int> col_data(num_rows, 1); std::vector<bool> col_mask(num_rows, 1); cudf::test::fixed_width_column_wrapper<TypeParam, int> input( col_data.begin(), col_data.end(), col_mask.begin()); std::vector<cudf::size_type> preceding({0}); std::vector<cudf::size_type> following({1}); cudf::size_type periods = num_rows; this->run_test_col_agg(input, preceding, following, periods); } // min_periods = 0 TYPED_TEST(RollingTest, ZeroPeriods) { cudf::size_type num_rows = 1000; std::vector<int> col_data(num_rows, 1); std::vector<bool> col_mask(num_rows, 1); cudf::test::fixed_width_column_wrapper<TypeParam, int> input( col_data.begin(), col_data.end(), col_mask.begin()); std::vector<cudf::size_type> window({num_rows}); cudf::size_type periods = 0; this->run_test_col_agg(input, window, window, periods); } // window in one direction is not large enough to collect enough samples, // but if using both directions we should get == min_periods, // also tests out of boundary accesses TYPED_TEST(RollingTest, BackwardForwardWindow) { cudf::size_type num_rows = 1000; std::vector<int> col_data(num_rows, 1); std::vector<bool> col_mask(num_rows, 1); cudf::test::fixed_width_column_wrapper<TypeParam, int> input( col_data.begin(), col_data.end(), col_mask.begin()); std::vector<cudf::size_type> window({num_rows}); cudf::size_type periods = num_rows; this->run_test_col_agg(input, window, window, periods); } // random input data, static parameters, no nulls TYPED_TEST(RollingTest, RandomStaticAllValid) { cudf::size_type num_rows = 10000; // random input std::vector<TypeParam> col_data(num_rows); cudf::test::UniformRandomGenerator<TypeParam> rng; std::generate(col_data.begin(), col_data.end(), [&rng]() { return rng.generate(); }); cudf::test::fixed_width_column_wrapper<TypeParam> input(col_data.begin(), col_data.end()); std::vector<cudf::size_type> window({50}); cudf::size_type periods = 50; this->run_test_col_agg(input, window, window, periods); } // random input data, static parameters, with nulls TYPED_TEST(RollingTest, RandomStaticWithInvalid) { cudf::size_type num_rows = 10000; // random input std::vector<TypeParam> col_data(num_rows); std::vector<bool> col_valid(num_rows); cudf::test::UniformRandomGenerator<TypeParam> rng; cudf::test::UniformRandomGenerator<bool> rbg; std::generate(col_data.begin(), col_data.end(), [&rng]() { return rng.generate(); }); std::generate(col_valid.begin(), col_valid.end(), [&rbg]() { return rbg.generate(); }); cudf::test::fixed_width_column_wrapper<TypeParam> input( col_data.begin(), col_data.end(), col_valid.begin()); std::vector<cudf::size_type> window({50}); cudf::size_type periods = 50; this->run_test_col_agg(input, window, window, periods); } // random input data, dynamic parameters, no nulls TYPED_TEST(RollingTest, RandomDynamicAllValid) { cudf::size_type num_rows = 50000; cudf::size_type max_window_size = 50; // random input std::vector<TypeParam> col_data(num_rows); cudf::test::UniformRandomGenerator<TypeParam> rng; std::generate(col_data.begin(), col_data.end(), [&rng]() { return rng.generate(); }); cudf::test::fixed_width_column_wrapper<TypeParam> input(col_data.begin(), col_data.end()); // random parameters cudf::test::UniformRandomGenerator<cudf::size_type> window_rng(0, max_window_size); auto generator = [&]() { return window_rng.generate(); }; std::vector<cudf::size_type> preceding_window(num_rows); std::vector<cudf::size_type> following_window(num_rows); std::generate(preceding_window.begin(), preceding_window.end(), generator); std::generate(following_window.begin(), following_window.end(), generator); this->run_test_col_agg(input, preceding_window, following_window, max_window_size); } // random input data, dynamic parameters, with nulls TYPED_TEST(RollingTest, RandomDynamicWithInvalid) { cudf::size_type num_rows = 50000; cudf::size_type max_window_size = 50; // random input with nulls std::vector<TypeParam> col_data(num_rows); std::vector<bool> col_valid(num_rows); cudf::test::UniformRandomGenerator<TypeParam> rng; cudf::test::UniformRandomGenerator<bool> rbg; std::generate(col_data.begin(), col_data.end(), [&rng]() { return rng.generate(); }); std::generate(col_valid.begin(), col_valid.end(), [&rbg]() { return rbg.generate(); }); cudf::test::fixed_width_column_wrapper<TypeParam> input( col_data.begin(), col_data.end(), col_valid.begin()); // random parameters cudf::test::UniformRandomGenerator<cudf::size_type> window_rng(0, max_window_size); auto generator = [&]() { return window_rng.generate(); }; std::vector<cudf::size_type> preceding_window(num_rows); std::vector<cudf::size_type> following_window(num_rows); std::generate(preceding_window.begin(), preceding_window.end(), generator); std::generate(following_window.begin(), following_window.end(), generator); this->run_test_col_agg(input, preceding_window, following_window, max_window_size); } // ------------- non-fixed-width types -------------------- using RollingTestStrings = RollingTest<cudf::string_view>; TEST_F(RollingTestStrings, StringsUnsupportedOperators) { cudf::test::strings_column_wrapper input{{"This", "is", "not", "a", "string", "type"}, {1, 1, 1, 0, 1, 0}}; std::vector<cudf::size_type> window{1}; EXPECT_THROW( cudf::rolling_window(input, 2, 2, 0, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); EXPECT_THROW( cudf::rolling_window(input, 2, 2, 0, *cudf::make_mean_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); EXPECT_THROW(cudf::rolling_window(input, 2, 2, 0, *cudf::make_udf_aggregation<cudf::rolling_aggregation>( cudf::udf_type::PTX, std::string{}, cudf::data_type{})), cudf::logic_error); EXPECT_THROW(cudf::rolling_window(input, 2, 2, 0, *cudf::make_udf_aggregation<cudf::rolling_aggregation>( cudf::udf_type::CUDA, std::string{}, cudf::data_type{})), cudf::logic_error); } /*TEST_F(RollingTestStrings, SimpleStatic) { cudf::test::strings_column_wrapper input{{"This", "is", "not", "a", "string", "type"}, {1, 1, 1, 0, 1, 0}}; std::vector<cudf::size_type> window{1}; EXPECT_NO_THROW(this->run_test_col(input, window, window, 0, rolling_operator::MIN)); EXPECT_NO_THROW(this->run_test_col(input, window, window, 0, rolling_operator::MAX)); EXPECT_NO_THROW(this->run_test_col(input, window, window, 0, rolling_operator::COUNT_VALID)); EXPECT_NO_THROW(this->run_test_col(input, window, window, 0, rolling_operator::COUNT_ALL)); }*/ struct RollingTestUdf : public cudf::test::BaseFixture { const std::string cuda_func{ R"***( template <typename OutType, typename InType> __device__ void CUDA_GENERIC_AGGREGATOR(OutType *ret, InType *in_col, cudf::size_type start, cudf::size_type count) { OutType val = 0; for (cudf::size_type i = 0; i < count; i++) { val += in_col[start + i]; } *ret = val; } )***"}; const std::string ptx_func{ R"***( // // Generated by NVIDIA NVVM Compiler // // Compiler Build ID: CL-24817639 // Cuda compilation tools, release 10.0, V10.0.130 // Based on LLVM 3.4svn // .version 6.3 .target sm_70 .address_size 64 // .globl _ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE .common .global .align 8 .u64 _ZN08NumbaEnv8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE; .visible .func (.param .b32 func_retval0) _ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE( .param .b64 _ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_0, .param .b64 _ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_1, .param .b64 _ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_2, .param .b64 _ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_3, .param .b64 _ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_4, .param .b64 _ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_5, .param .b64 _ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_6, .param .b64 _ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_7 ) { .reg .pred %p<3>; .reg .b32 %r<6>; .reg .b64 %rd<18>; ld.param.u64 %rd6, [_ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_0]; ld.param.u64 %rd7, [_ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_5]; ld.param.u64 %rd8, [_ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_6]; ld.param.u64 %rd9, [_ZN8__main__7add$241E5ArrayIiLi1E1A7mutable7alignedE_paam_7]; mov.u64 %rd15, 0; mov.u64 %rd16, %rd15; BB0_1: mov.u64 %rd2, %rd16; mov.u32 %r5, 0; setp.ge.s64 %p1, %rd15, %rd8; mov.u64 %rd17, %rd15; @%p1 bra BB0_3; mul.lo.s64 %rd12, %rd15, %rd9; add.s64 %rd13, %rd12, %rd7; ld.u32 %r5, [%rd13]; add.s64 %rd17, %rd15, 1; BB0_3: cvt.s64.s32 %rd14, %r5; add.s64 %rd16, %rd14, %rd2; setp.lt.s64 %p2, %rd15, %rd8; mov.u64 %rd15, %rd17; @%p2 bra BB0_1; st.u64 [%rd6], %rd2; mov.u32 %r4, 0; st.param.b32 [func_retval0+0], %r4; ret; } )***"}; }; TEST_F(RollingTestUdf, StaticWindow) { cudf::size_type size = 1000; cudf::test::fixed_width_column_wrapper<int32_t> input(thrust::make_counting_iterator(0), thrust::make_counting_iterator(size), thrust::make_constant_iterator(true)); std::unique_ptr<cudf::column> output; auto start = cudf::detail::make_counting_transform_iterator(0, [size](cudf::size_type row) { return std::accumulate(thrust::make_counting_iterator(std::max(0, row - 2 + 1)), thrust::make_counting_iterator(std::min(size, row + 2 + 1)), 0); }); auto valid = cudf::detail::make_counting_transform_iterator( 0, [size](cudf::size_type row) { return (row != 0 && row != size - 2 && row != size - 1); }); cudf::test::fixed_width_column_wrapper<int64_t> expected{start, start + size, valid}; // Test CUDA UDF auto cuda_udf_agg = cudf::make_udf_aggregation<cudf::rolling_aggregation>( cudf::udf_type::CUDA, this->cuda_func, cudf::data_type{cudf::type_id::INT64}); output = cudf::rolling_window(input, 2, 2, 4, *cuda_udf_agg); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*output, expected); // Test NUMBA UDF auto ptx_udf_agg = cudf::make_udf_aggregation<cudf::rolling_aggregation>( cudf::udf_type::PTX, this->ptx_func, cudf::data_type{cudf::type_id::INT64}); output = cudf::rolling_window(input, 2, 2, 4, *ptx_udf_agg); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*output, expected); } TEST_F(RollingTestUdf, DynamicWindow) { cudf::size_type size = 1000; cudf::test::fixed_width_column_wrapper<int32_t> input(thrust::make_counting_iterator(0), thrust::make_counting_iterator(size), thrust::make_constant_iterator(true)); auto prec = cudf::detail::make_counting_transform_iterator( 0, [] __device__(cudf::size_type row) { return row % 2 + 2; }); auto follow = cudf::detail::make_counting_transform_iterator( 0, [] __device__(cudf::size_type row) { return row % 2; }); cudf::test::fixed_width_column_wrapper<int32_t> preceding(prec, prec + size); cudf::test::fixed_width_column_wrapper<int32_t> following(follow, follow + size); std::unique_ptr<cudf::column> output; auto start = cudf::detail::make_counting_transform_iterator(0, [size] __device__(cudf::size_type row) { return std::accumulate(thrust::make_counting_iterator(std::max(0, row - (row % 2 + 2) + 1)), thrust::make_counting_iterator(std::min(size, row + (row % 2) + 1)), 0); }); auto valid = cudf::detail::make_counting_transform_iterator( 0, [] __device__(cudf::size_type row) { return row != 0; }); cudf::test::fixed_width_column_wrapper<int64_t> expected{start, start + size, valid}; // Test CUDA UDF auto cuda_udf_agg = cudf::make_udf_aggregation<cudf::rolling_aggregation>( cudf::udf_type::CUDA, this->cuda_func, cudf::data_type{cudf::type_id::INT64}); output = cudf::rolling_window(input, preceding, following, 2, *cuda_udf_agg); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*output, expected); // Test PTX UDF auto ptx_udf_agg = cudf::make_udf_aggregation<cudf::rolling_aggregation>( cudf::udf_type::PTX, this->ptx_func, cudf::data_type{cudf::type_id::INT64}); output = cudf::rolling_window(input, preceding, following, 2, *ptx_udf_agg); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*output, expected); } template <typename T> struct FixedPointTests : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(FixedPointTests, cudf::test::FixedPointTypes); TYPED_TEST(FixedPointTests, MinMaxCountLagLead) { using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; using fw_wrapper = cudf::test::fixed_width_column_wrapper<cudf::size_type>; auto const scale = numeric::scale_type{-1}; auto const input = fp_wrapper{{42, 1729, 55, 3, 1, 2}, {1, 1, 1, 1, 1, 1}, scale}; auto const expected_min = fp_wrapper{{42, 42, 3, 1, 1, 1}, {1, 1, 1, 1, 1, 1}, scale}; auto const expected_max = fp_wrapper{{1729, 1729, 1729, 55, 3, 2}, {1, 1, 1, 1, 1, 1}, scale}; auto const expected_lag = fp_wrapper{{0, 42, 1729, 55, 3, 1}, {0, 1, 1, 1, 1, 1}, scale}; auto const expected_lead = fp_wrapper{{1729, 55, 3, 1, 2, 0}, {1, 1, 1, 1, 1, 0}, scale}; auto const expected_count_val = fw_wrapper{{2, 3, 3, 3, 3, 2}, {1, 1, 1, 1, 1, 1}}; auto const expected_count_all = fw_wrapper{{2, 3, 3, 3, 3, 2}, {1, 1, 1, 1, 1, 1}}; auto const expected_rowno = fw_wrapper{{1, 2, 2, 2, 2, 2}, {1, 1, 1, 1, 1, 1}}; auto const expected_rowno1 = fw_wrapper{{1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1}}; auto const min = cudf::rolling_window(input, 2, 1, 1, *cudf::make_min_aggregation<cudf::rolling_aggregation>()); auto const max = cudf::rolling_window(input, 2, 1, 1, *cudf::make_max_aggregation<cudf::rolling_aggregation>()); auto const lag = cudf::rolling_window(input, 2, 1, 1, *cudf::make_lag_aggregation<cudf::rolling_aggregation>(1)); auto const lead = cudf::rolling_window( input, 2, 1, 1, *cudf::make_lead_aggregation<cudf::rolling_aggregation>(1)); auto const valid = cudf::rolling_window( input, 2, 1, 1, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); auto const all = cudf::rolling_window( input, 2, 1, 1, *cudf::make_count_aggregation<cudf::rolling_aggregation>(cudf::null_policy::INCLUDE)); auto const rowno = cudf::rolling_window( input, 2, 1, 1, *cudf::make_row_number_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_min, min->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_max, max->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lag, lag->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lead, lead->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_count_val, valid->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_count_all, all->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_rowno, rowno->view()); // ROW_NUMBER will always return row 1 if the preceding window is set to a constant 1 for (int following = 1; following < 5; ++following) { auto const rowno1 = cudf::rolling_window( input, 1, following, 1, *cudf::make_row_number_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_rowno1, rowno1->view()); } } TYPED_TEST(FixedPointTests, MinMaxCountLagLeadNulls) { using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; using fw_wrapper = cudf::test::fixed_width_column_wrapper<cudf::size_type>; auto const scale = numeric::scale_type{-1}; auto const input = fp_wrapper{{42, 1729, 55, 343, 1, 2}, {1, 0, 1, 0, 1, 1}, scale}; auto const expected_sum = fp_wrapper{{42, 97, 55, 56, 3, 3}, {1, 1, 1, 1, 1, 1}, scale}; auto const expected_min = fp_wrapper{{42, 42, 55, 1, 1, 1}, {1, 1, 1, 1, 1, 1}, scale}; auto const expected_max = fp_wrapper{{42, 55, 55, 55, 2, 2}, {1, 1, 1, 1, 1, 1}, scale}; auto const expected_lag = fp_wrapper{{0, 42, 1729, 55, 343, 1}, {0, 1, 0, 1, 0, 1}, scale}; auto const expected_lead = fp_wrapper{{1729, 55, 343, 1, 2, 0}, {0, 1, 0, 1, 1, 0}, scale}; auto const expected_count_val = fw_wrapper{{1, 2, 1, 2, 2, 2}, {1, 1, 1, 1, 1, 1}}; auto const expected_count_all = fw_wrapper{{2, 3, 3, 3, 3, 2}, {1, 1, 1, 1, 1, 1}}; auto const expected_rowno = fw_wrapper{{1, 2, 2, 2, 2, 2}, {1, 1, 1, 1, 1, 1}}; auto const sum = cudf::rolling_window(input, 2, 1, 1, *cudf::make_sum_aggregation<cudf::rolling_aggregation>()); auto const min = cudf::rolling_window(input, 2, 1, 1, *cudf::make_min_aggregation<cudf::rolling_aggregation>()); auto const max = cudf::rolling_window(input, 2, 1, 1, *cudf::make_max_aggregation<cudf::rolling_aggregation>()); auto const lag = cudf::rolling_window(input, 2, 1, 1, *cudf::make_lag_aggregation<cudf::rolling_aggregation>(1)); auto const lead = cudf::rolling_window( input, 2, 1, 1, *cudf::make_lead_aggregation<cudf::rolling_aggregation>(1)); auto const valid = cudf::rolling_window( input, 2, 1, 1, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); auto const all = cudf::rolling_window( input, 2, 1, 1, *cudf::make_count_aggregation<cudf::rolling_aggregation>(cudf::null_policy::INCLUDE)); auto const rowno = cudf::rolling_window( input, 2, 1, 1, *cudf::make_row_number_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_sum, sum->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_min, min->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_max, max->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lag, lag->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lead, lead->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_count_val, valid->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_count_all, all->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_rowno, rowno->view()); } TYPED_TEST(FixedPointTests, VarStd) { using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; using fw_wrapper = cudf::test::fixed_width_column_wrapper<double>; double const nan = std::numeric_limits<double>::signaling_NaN(); double const inf = std::numeric_limits<double>::infinity(); cudf::size_type preceding_window{3}, following_window{0}, min_periods{1}, ddof{2}; // The variance of `input` given `scale` == 0 std::vector<double> result_base_v{ nan, inf, 1882804.66666666667, 1928018.666666666667, 1874.6666666666667, 2.0}; std::vector<bool> result_mask_v{1, 1, 1, 1, 1, 1}; // var tests for (int32_t s = -2; s <= 2; s++) { auto const scale = numeric::scale_type{s}; auto const input = fp_wrapper{{42, 1729, 55, 3, 1, 2}, {1, 1, 1, 1, 1, 1}, scale}; auto got = cudf::rolling_window( input, preceding_window, following_window, min_periods, dynamic_cast<cudf::rolling_aggregation const&>(*cudf::make_variance_aggregation(ddof))); std::vector<double> result_scaled_v(result_base_v.size()); std::transform( result_base_v.begin(), result_base_v.end(), result_scaled_v.begin(), [&s](auto x) { // When values are scaled by 10^n, the variance is scaled by 10^2n. return x * exp10(s) * exp10(s); }); fw_wrapper expect(result_scaled_v.begin(), result_scaled_v.end(), result_mask_v.begin()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expect, *got); } // std tests for (int32_t s = -2; s <= 2; s++) { auto const scale = numeric::scale_type{s}; auto const input = fp_wrapper{{42, 1729, 55, 3, 1, 2}, {1, 1, 1, 1, 1, 1}, scale}; auto got = cudf::rolling_window( input, preceding_window, following_window, min_periods, dynamic_cast<cudf::rolling_aggregation const&>(*cudf::make_std_aggregation(ddof))); std::vector<double> result_scaled_v(result_base_v.size()); std::transform( result_base_v.begin(), result_base_v.end(), result_scaled_v.begin(), [&s](auto x) { // When values are scaled by 10^n, the variance is scaled by 10^2n. return std::sqrt(x * exp10(s) * exp10(s)); }); fw_wrapper expect(result_scaled_v.begin(), result_scaled_v.end(), result_mask_v.begin()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expect, *got); } } class RollingDictionaryTest : public cudf::test::BaseFixture {}; TEST_F(RollingDictionaryTest, Count) { cudf::test::dictionary_column_wrapper<std::string> input( {"This", "is", "rolling", "test", "being", "operated", "on", "string", "column"}, {1, 0, 0, 1, 0, 1, 1, 1, 0}); cudf::test::fixed_width_column_wrapper<cudf::size_type> expected_count_val( {1, 2, 1, 2, 3, 3, 3, 2, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1}); cudf::test::fixed_width_column_wrapper<cudf::size_type> expected_count_all( {3, 4, 4, 4, 4, 4, 4, 3, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1}); cudf::test::fixed_width_column_wrapper<cudf::size_type> expected_row_number( {1, 2, 2, 2, 2, 2, 2, 2, 2}, {1, 1, 1, 1, 1, 1, 1, 1, 1}); auto got_count_valid = cudf::rolling_window( input, 2, 2, 1, *cudf::make_count_aggregation<cudf::rolling_aggregation>()); auto got_count_all = cudf::rolling_window( input, 2, 2, 1, *cudf::make_count_aggregation<cudf::rolling_aggregation>(cudf::null_policy::INCLUDE)); auto got_row_number = cudf::rolling_window( input, 2, 2, 1, *cudf::make_row_number_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_count_val, got_count_valid->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_count_all, got_count_all->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_row_number, got_row_number->view()); } TEST_F(RollingDictionaryTest, MinMax) { cudf::test::dictionary_column_wrapper<std::string> input( {"This", "is", "rolling", "test", "being", "operated", "on", "string", "column"}, {1, 0, 0, 1, 0, 1, 1, 1, 0}); cudf::test::strings_column_wrapper expected_min( {"This", "This", "test", "operated", "on", "on", "on", "on", "string"}, {1, 1, 1, 1, 1, 1, 1, 1, 1}); cudf::test::strings_column_wrapper expected_max( {"This", "test", "test", "test", "test", "string", "string", "string", "string"}, {1, 1, 1, 1, 1, 1, 1, 1, 1}); auto got_min_dict = cudf::rolling_window(input, 2, 2, 1, *cudf::make_min_aggregation<cudf::rolling_aggregation>()); auto got_min = cudf::dictionary::decode(cudf::dictionary_column_view(got_min_dict->view())); auto got_max_dict = cudf::rolling_window(input, 2, 2, 1, *cudf::make_max_aggregation<cudf::rolling_aggregation>()); auto got_max = cudf::dictionary::decode(cudf::dictionary_column_view(got_max_dict->view())); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_min, got_min->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_max, got_max->view()); } TEST_F(RollingDictionaryTest, LeadLag) { cudf::test::dictionary_column_wrapper<std::string> input( {"This", "is", "rolling", "test", "being", "operated", "on", "string", "column"}, {1, 0, 0, 1, 0, 1, 1, 1, 0}); cudf::test::strings_column_wrapper expected_lead( {"", "", "test", "", "operated", "on", "string", "", ""}, {0, 0, 1, 0, 1, 1, 1, 0, 0}); cudf::test::strings_column_wrapper expected_lag( {"", "This", "", "", "test", "", "operated", "on", "string"}, {0, 1, 0, 0, 1, 0, 1, 1, 1}); auto got_lead_dict = cudf::rolling_window( input, 2, 1, 1, *cudf::make_lead_aggregation<cudf::rolling_aggregation>(1)); auto got_lead = cudf::dictionary::decode(cudf::dictionary_column_view(got_lead_dict->view())); auto got_lag_dict = cudf::rolling_window(input, 2, 2, 1, *cudf::make_lag_aggregation<cudf::rolling_aggregation>(1)); auto got_lag = cudf::dictionary::decode(cudf::dictionary_column_view(got_lag_dict->view())); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lead, got_lead->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_lag, got_lag->view()); } CUDF_TEST_PROGRAM_MAIN()
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/rolling/empty_input_test.cpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/aggregation.hpp> #include <cudf/detail/aggregation/aggregation.hpp> #include <cudf/rolling.hpp> #include <cudf/scalar/scalar.hpp> namespace { // Helper functions to construct rolling window operators. auto count_valid() { return cudf::make_count_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE); } auto count_all() { return cudf::make_count_aggregation<cudf::rolling_aggregation>(cudf::null_policy::INCLUDE); } auto sum() { return cudf::make_sum_aggregation<cudf::rolling_aggregation>(); } auto mean() { return cudf::make_mean_aggregation<cudf::rolling_aggregation>(); } auto min() { return cudf::make_min_aggregation<cudf::rolling_aggregation>(); } auto max() { return cudf::make_max_aggregation<cudf::rolling_aggregation>(); } auto lead() { return cudf::make_lead_aggregation<cudf::rolling_aggregation>(3); } auto lag() { return cudf::make_lag_aggregation<cudf::rolling_aggregation>(3); } auto row_number() { return cudf::make_row_number_aggregation<cudf::rolling_aggregation>(); } auto collect_list() { return cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(); } auto udf() { return cudf::make_udf_aggregation<cudf::rolling_aggregation>( cudf::udf_type::CUDA, "", cudf::data_type{cudf::type_id::INT32}); } // Constants for rolling_window. auto constexpr min_periods = 1; auto constexpr preceding = 2; auto constexpr following = 2; auto preceding_scalar() { return cudf::numeric_scalar<cudf::size_type>(preceding); } auto following_scalar() { return cudf::numeric_scalar<cudf::size_type>(following); } auto preceding_column() { return cudf::test::fixed_width_column_wrapper<cudf::size_type>{}.release(); } auto following_column() { return cudf::test::fixed_width_column_wrapper<cudf::size_type>{}.release(); } } // namespace struct RollingEmptyInputTest : cudf::test::BaseFixture {}; template <typename T> struct TypedRollingEmptyInputTest : RollingEmptyInputTest {}; TYPED_TEST_SUITE(TypedRollingEmptyInputTest, cudf::test::FixedWidthTypes); using agg_vector_t = std::vector<std::unique_ptr<cudf::rolling_aggregation>>; void rolling_output_type_matches(cudf::column_view const& result, cudf::type_id expected_type, cudf::type_id expected_child_type) { EXPECT_EQ(result.type().id(), expected_type); EXPECT_EQ(result.size(), 0); if (expected_type == cudf::type_id::LIST) { EXPECT_EQ(result.child(cudf::lists_column_view::child_column_index).type().id(), expected_child_type); } if (expected_type == cudf::type_id::STRUCT) { EXPECT_EQ(result.child(0).type().id(), expected_child_type); } } void rolling_output_type_matches(cudf::column_view const& empty_input, agg_vector_t const& aggs, cudf::type_id expected_type, cudf::type_id expected_child_type = cudf::type_id::EMPTY) { auto const preceding_col = preceding_column(); auto const following_col = following_column(); for (auto const& agg : aggs) { auto rolling_output_numeric_bounds = cudf::rolling_window(empty_input, preceding, following, min_periods, *agg); rolling_output_type_matches( rolling_output_numeric_bounds->view(), expected_type, expected_child_type); auto rolling_output_columnar_bounds = cudf::rolling_window(empty_input, *preceding_col, *following_col, min_periods, *agg); rolling_output_type_matches( rolling_output_columnar_bounds->view(), expected_type, expected_child_type); auto grouped_rolling_output = cudf::grouped_rolling_window(cudf::table_view{std::vector{empty_input}}, empty_input, preceding, following, min_periods, *agg); rolling_output_type_matches(grouped_rolling_output->view(), expected_type, expected_child_type); auto grouped_range_rolling_output = cudf::grouped_range_rolling_window(cudf::table_view{std::vector{empty_input}}, empty_input, cudf::order::ASCENDING, empty_input, cudf::range_window_bounds::get(preceding_scalar()), cudf::range_window_bounds::get(following_scalar()), min_periods, *agg); rolling_output_type_matches( grouped_range_rolling_output->view(), expected_type, expected_child_type); } } void rolling_window_throws(cudf::column_view const& empty_input, agg_vector_t const& aggs) { for (auto const& agg : aggs) { EXPECT_THROW(cudf::rolling_window(empty_input, 2, 2, 1, *agg), cudf::logic_error); } } TYPED_TEST(TypedRollingEmptyInputTest, EmptyFixedWidthInputs) { using InputType = TypeParam; auto input_col = cudf::test::fixed_width_column_wrapper<InputType>{}.release(); auto empty_input = input_col->view(); /// Test aggregations that yield columns of type `size_type`. { auto aggs = agg_vector_t{}; aggs.emplace_back(count_valid()); aggs.emplace_back(count_all()); aggs.emplace_back(row_number()); rolling_output_type_matches(empty_input, aggs, cudf::type_to_id<cudf::size_type>()); } /// Test aggregations that yield columns of same type as input. { auto aggs = agg_vector_t{}; aggs.emplace_back(min()); aggs.emplace_back(max()); aggs.emplace_back(lead()); aggs.emplace_back(lag()); aggs.emplace_back(udf()); rolling_output_type_matches(empty_input, aggs, cudf::type_to_id<InputType>()); } /// `SUM` returns 64-bit promoted types for integral/decimal input. /// For other fixed-width input types, the same type is returned. /// Timestamp types are not supported. { auto aggs = agg_vector_t{}; aggs.emplace_back(sum()); using expected_type = cudf::detail::target_type_t<InputType, cudf::aggregation::SUM>; if constexpr (cudf::is_timestamp<InputType>()) { EXPECT_THROW( rolling_output_type_matches(empty_input, aggs, cudf::type_to_id<expected_type>()), cudf::logic_error); } else { rolling_output_type_matches(empty_input, aggs, cudf::type_to_id<expected_type>()); } } /// `MEAN` returns float64 for all numeric types, /// except for duration-types, which yield the same duration-type. /// Timestamp types are not supported. { auto aggs = agg_vector_t{}; aggs.emplace_back(mean()); using expected_type = cudf::detail::target_type_t<InputType, cudf::aggregation::MEAN>; if constexpr (cudf::is_timestamp<InputType>()) { EXPECT_THROW( rolling_output_type_matches(empty_input, aggs, cudf::type_to_id<expected_type>()), cudf::logic_error); } else { rolling_output_type_matches(empty_input, aggs, cudf::type_to_id<expected_type>()); } } /// For an input type `T`, `COLLECT_LIST` returns a column of type `list<T>`. { auto aggs = std::vector<std::unique_ptr<cudf::rolling_aggregation>>{}; aggs.emplace_back(collect_list()); rolling_output_type_matches( empty_input, aggs, cudf::type_to_id<cudf::list_view>(), cudf::type_to_id<InputType>()); } } TEST_F(RollingEmptyInputTest, Strings) { auto input_col = cudf::test::strings_column_wrapper{}.release(); auto empty_input = input_col->view(); /// Test aggregations that yield columns of type `size_type`. { auto aggs = agg_vector_t{}; aggs.emplace_back(count_valid()); aggs.emplace_back(count_all()); aggs.emplace_back(row_number()); rolling_output_type_matches(empty_input, aggs, cudf::type_to_id<cudf::size_type>()); } /// Test aggregations that yield columns of same type as input. { auto aggs = agg_vector_t{}; aggs.emplace_back(min()); aggs.emplace_back(max()); aggs.emplace_back(lead()); aggs.emplace_back(lag()); aggs.emplace_back(udf()); rolling_output_type_matches(empty_input, aggs, cudf::type_id::STRING); } /// For an input type `T`, `COLLECT_LIST` returns a column of type `list<T>`. { auto aggs = agg_vector_t{}; aggs.emplace_back(collect_list()); rolling_output_type_matches( empty_input, aggs, cudf::type_to_id<cudf::list_view>(), cudf::type_id::STRING); } /// All other aggregations are unsupported. { auto unsupported_aggs = agg_vector_t{}; unsupported_aggs.emplace_back(sum()); unsupported_aggs.emplace_back(mean()); rolling_window_throws(empty_input, unsupported_aggs); } } TEST_F(RollingEmptyInputTest, Dictionaries) { auto input_col = cudf::test::dictionary_column_wrapper<std::string>{}.release(); auto empty_input = input_col->view(); /// Test aggregations that yield columns of type `size_type`. { auto aggs = agg_vector_t{}; aggs.emplace_back(count_valid()); aggs.emplace_back(count_all()); aggs.emplace_back(row_number()); rolling_output_type_matches(empty_input, aggs, cudf::type_to_id<cudf::size_type>()); } /// Test aggregations that yield columns of same type as input. { auto aggs = agg_vector_t{}; aggs.emplace_back(min()); aggs.emplace_back(max()); aggs.emplace_back(lead()); aggs.emplace_back(lag()); aggs.emplace_back(udf()); rolling_output_type_matches(empty_input, aggs, cudf::type_id::DICTIONARY32); } /// For an input type `T`, `COLLECT_LIST` returns a column of type `list<T>`. { auto aggs = agg_vector_t{}; aggs.emplace_back(collect_list()); rolling_output_type_matches( empty_input, aggs, cudf::type_to_id<cudf::list_view>(), cudf::type_id::DICTIONARY32); } /// All other aggregations are unsupported. { auto unsupported_aggs = agg_vector_t{}; unsupported_aggs.emplace_back(sum()); unsupported_aggs.emplace_back(mean()); rolling_window_throws(empty_input, unsupported_aggs); } } TYPED_TEST(TypedRollingEmptyInputTest, Lists) { using T = TypeParam; auto input_col = cudf::test::lists_column_wrapper<T>{}.release(); auto empty_input = input_col->view(); /// Test aggregations that yield columns of type `size_type`. { auto aggs = agg_vector_t{}; aggs.emplace_back(count_valid()); aggs.emplace_back(count_all()); aggs.emplace_back(row_number()); rolling_output_type_matches(empty_input, aggs, cudf::type_to_id<cudf::size_type>()); } /// Test aggregations that yield columns of same type as input. { auto aggs = agg_vector_t{}; aggs.emplace_back(min()); aggs.emplace_back(max()); aggs.emplace_back(lead()); aggs.emplace_back(lag()); aggs.emplace_back(udf()); rolling_output_type_matches(empty_input, aggs, cudf::type_id::LIST, cudf::type_to_id<T>()); } /// For an input type `T`, `COLLECT_LIST` returns a column of type `list<T>`. { auto aggs = agg_vector_t{}; aggs.emplace_back(collect_list()); rolling_output_type_matches(empty_input, aggs, cudf::type_id::LIST, cudf::type_id::LIST); } /// All other aggregations are unsupported. { auto unsupported_aggs = agg_vector_t{}; unsupported_aggs.emplace_back(sum()); unsupported_aggs.emplace_back(mean()); rolling_window_throws(empty_input, unsupported_aggs); } } TYPED_TEST(TypedRollingEmptyInputTest, Structs) { using T = TypeParam; auto member_col = cudf::test::fixed_width_column_wrapper<T>{}; auto input_col = cudf::test::structs_column_wrapper{{member_col}}.release(); auto empty_input = input_col->view(); /// Test aggregations that yield columns of type `size_type`. { auto aggs = agg_vector_t{}; aggs.emplace_back(count_valid()); aggs.emplace_back(count_all()); aggs.emplace_back(row_number()); rolling_output_type_matches(empty_input, aggs, cudf::type_to_id<cudf::size_type>()); } /// Test aggregations that yield columns of same type as input. { auto aggs = agg_vector_t{}; aggs.emplace_back(min()); aggs.emplace_back(max()); aggs.emplace_back(lead()); aggs.emplace_back(lag()); aggs.emplace_back(udf()); rolling_output_type_matches(empty_input, aggs, cudf::type_id::STRUCT, cudf::type_to_id<T>()); } /// For an input type `T`, `COLLECT_LIST` returns a column of type `list<T>`. { auto aggs = agg_vector_t{}; aggs.emplace_back(collect_list()); rolling_output_type_matches(empty_input, aggs, cudf::type_id::LIST, cudf::type_id::STRUCT); } /// All other aggregations are unsupported. { auto unsupported_aggs = agg_vector_t{}; unsupported_aggs.emplace_back(sum()); unsupported_aggs.emplace_back(mean()); rolling_window_throws(empty_input, unsupported_aggs); } }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/rolling/collect_ops_test.cpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/aggregation.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/lists/sorting.hpp> #include <cudf/rolling.hpp> #include <cudf/table/table_view.hpp> #include <thrust/functional.h> #include <vector> struct CollectListTest : public cudf::test::BaseFixture {}; template <typename T> struct TypedCollectListTest : public CollectListTest {}; using TypesForTest = cudf::test::Concat<cudf::test::IntegralTypes, cudf::test::FloatingPointTypes, cudf::test::DurationTypes, cudf::test::FixedPointTypes>; TYPED_TEST_SUITE(TypedCollectListTest, TypesForTest); TYPED_TEST(TypedCollectListTest, BasicRollingWindow) { using T = TypeParam; auto const input_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{10, 11, 12, 13, 14}; auto const prev_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>{1, 2, 2, 2, 2}; auto const foll_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>{1, 1, 1, 1, 0}; EXPECT_EQ(static_cast<cudf::column_view>(prev_column).size(), static_cast<cudf::column_view>(foll_column).size()); auto const result_column_based_window = cudf::rolling_window(input_column, prev_column, foll_column, 1, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto const expected_result = cudf::test::lists_column_wrapper<T, int32_t>{ {10, 11}, {10, 11, 12}, {11, 12, 13}, {12, 13, 14}, {13, 14}, } .release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_column_based_window->view()); auto const result_fixed_window = cudf::rolling_window( input_column, 2, 1, 1, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_fixed_window->view()); auto const result_with_nulls_excluded = cudf::rolling_window( input_column, 2, 1, 1, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); } TYPED_TEST(TypedCollectListTest, RollingWindowWithEmptyOutputLists) { using T = TypeParam; auto const input_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{10, 11, 12, 13, 14, 15}; auto const prev_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>{1, 2, 2, 0, 2, 2}; auto const foll_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>{1, 1, 1, 0, 1, 0}; EXPECT_EQ(static_cast<cudf::column_view>(prev_column).size(), static_cast<cudf::column_view>(foll_column).size()); auto const result_column_based_window = cudf::rolling_window(input_column, prev_column, foll_column, 0, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto const expected_result = cudf::test::lists_column_wrapper<T, int32_t>{ {10, 11}, {10, 11, 12}, {11, 12, 13}, {}, {13, 14, 15}, {14, 15}, } .release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_column_based_window->view()); auto const result_with_nulls_excluded = cudf::rolling_window( input_column, prev_column, foll_column, 0, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); } TYPED_TEST(TypedCollectListTest, RollingWindowWithEmptyOutputListsAtEnds) { using T = TypeParam; auto const input_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{0, 1, 2, 3, 4, 5}; auto const prev_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 2, 2, 2, 2, 0}; auto foll_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 1, 1, 1, 1, 0}; auto const result = cudf::rolling_window(input_column, prev_column, foll_column, 0, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto const expected_result = cudf::test::lists_column_wrapper<T, int32_t>{{}, {0, 1, 2}, {1, 2, 3}, {2, 3, 4}, {3, 4, 5}, {}} .release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = cudf::rolling_window( input_column, prev_column, foll_column, 0, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); } TYPED_TEST(TypedCollectListTest, RollingWindowHonoursMinPeriods) { // Test that when the number of observations is fewer than min_periods, // the result is null. using T = TypeParam; auto const input_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{0, 1, 2, 3, 4, 5}; auto const num_elements = static_cast<cudf::column_view>(input_column).size(); auto preceding = 2; auto following = 1; auto min_periods = 3; auto const result = cudf::rolling_window(input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto const expected_result = cudf::test::lists_column_wrapper<T, int32_t>{ {{}, {0, 1, 2}, {1, 2, 3}, {2, 3, 4}, {3, 4, 5}, {}}, cudf::detail::make_counting_transform_iterator(0, [num_elements](auto i) { return i != 0 && i != (num_elements - 1); })}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = cudf::rolling_window( input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); preceding = 2; following = 2; min_periods = 4; auto result_2 = cudf::rolling_window(input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto expected_result_2 = cudf::test::lists_column_wrapper<T, int32_t>{ {{}, {0, 1, 2, 3}, {1, 2, 3, 4}, {2, 3, 4, 5}, {}, {}}, cudf::detail::make_counting_transform_iterator(0, [num_elements](auto i) { return i != 0 && i < 4; })}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result_2->view(), result_2->view()); auto result_2_with_nulls_excluded = cudf::rolling_window( input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result_2->view(), result_2_with_nulls_excluded->view()); } TYPED_TEST(TypedCollectListTest, RollingWindowWithNullInputsHonoursMinPeriods) { // Test that when the number of observations is fewer than min_periods, // the result is null. // Input column has null inputs. using T = TypeParam; auto const input_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{{0, 1, 2, 3, 4, 5}, {1, 0, 1, 1, 0, 1}}; { // One result row at each end should be null. auto preceding = 2; auto following = 1; auto min_periods = 3; auto const result = cudf::rolling_window(input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto expected_result_child_values = std::vector<int32_t>{0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4, 5}; auto expected_result_child_validity = std::vector<bool>{1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1}; auto expected_result_child = cudf::test::fixed_width_column_wrapper<T, int32_t>(expected_result_child_values.begin(), expected_result_child_values.end(), expected_result_child_validity.begin()); auto expected_offsets = cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 0, 3, 6, 9, 12, 12}.release(); auto expected_num_rows = expected_offsets->size() - 1; auto null_mask_iter = cudf::detail::make_counting_transform_iterator( cudf::size_type{0}, [expected_num_rows](auto i) { return i != 0 && i != (expected_num_rows - 1); }); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(null_mask_iter, null_mask_iter + expected_num_rows); auto expected_result = cudf::make_lists_column(expected_num_rows, std::move(expected_offsets), expected_result_child.release(), null_count, std::move(null_mask)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); } { // One result row at each end should be null. // Exclude nulls: No nulls elements for any output list rows. auto preceding = 2; auto following = 1; auto min_periods = 3; auto const result = cudf::rolling_window( input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); auto expected_result_child_values = std::vector<int32_t>{0, 2, 2, 3, 2, 3, 3, 5}; auto expected_result_child = cudf::test::fixed_width_column_wrapper<T, int32_t>( expected_result_child_values.begin(), expected_result_child_values.end()); auto expected_offsets = cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 0, 2, 4, 6, 8, 8}.release(); auto expected_num_rows = expected_offsets->size() - 1; auto null_mask_iter = cudf::detail::make_counting_transform_iterator( cudf::size_type{0}, [expected_num_rows](auto i) { return i != 0 && i != (expected_num_rows - 1); }); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(null_mask_iter, null_mask_iter + expected_num_rows); auto expected_result = cudf::make_lists_column(expected_num_rows, std::move(expected_offsets), expected_result_child.release(), null_count, std::move(null_mask)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); } { // First result row, and the last two result rows should be null. auto preceding = 2; auto following = 2; auto min_periods = 4; auto const result = cudf::rolling_window(input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto expected_result_child_values = std::vector<int32_t>{0, 1, 2, 3, 1, 2, 3, 4, 2, 3, 4, 5}; auto expected_result_child_validity = std::vector<bool>{1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1}; auto expected_result_child = cudf::test::fixed_width_column_wrapper<T, int32_t>(expected_result_child_values.begin(), expected_result_child_values.end(), expected_result_child_validity.begin()); auto expected_offsets = cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 0, 4, 8, 12, 12, 12}.release(); auto expected_num_rows = expected_offsets->size() - 1; auto null_mask_iter = cudf::detail::make_counting_transform_iterator( cudf::size_type{0}, [expected_num_rows](auto i) { return i > 0 && i < 4; }); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(null_mask_iter, null_mask_iter + expected_num_rows); auto expected_result = cudf::make_lists_column(expected_num_rows, std::move(expected_offsets), expected_result_child.release(), null_count, std::move(null_mask)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); } { // First result row, and the last two result rows should be null. // Exclude nulls: No nulls elements for any output list rows. auto preceding = 2; auto following = 2; auto min_periods = 4; auto const result = cudf::rolling_window( input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); auto expected_result_child_values = std::vector<int32_t>{0, 2, 3, 2, 3, 2, 3, 5}; auto expected_result_child = cudf::test::fixed_width_column_wrapper<T, int32_t>( expected_result_child_values.begin(), expected_result_child_values.end()); auto expected_offsets = cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 0, 3, 5, 8, 8, 8}.release(); auto expected_num_rows = expected_offsets->size() - 1; auto null_mask_iter = cudf::detail::make_counting_transform_iterator( cudf::size_type{0}, [expected_num_rows](auto i) { return i > 0 && i < 4; }); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(null_mask_iter, null_mask_iter + expected_num_rows); auto expected_result = cudf::make_lists_column(expected_num_rows, std::move(expected_offsets), expected_result_child.release(), null_count, std::move(null_mask)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); } } TEST_F(CollectListTest, RollingWindowHonoursMinPeriodsOnStrings) { // Test that when the number of observations is fewer than min_periods, // the result is null. auto const input_column = cudf::test::strings_column_wrapper{"0", "1", "2", "3", "4", "5"}; auto const num_elements = static_cast<cudf::column_view>(input_column).size(); auto preceding = 2; auto following = 1; auto min_periods = 3; auto const result = cudf::rolling_window(input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto const expected_result = cudf::test::lists_column_wrapper<cudf::string_view>{ {{}, {"0", "1", "2"}, {"1", "2", "3"}, {"2", "3", "4"}, {"3", "4", "5"}, {}}, cudf::detail::make_counting_transform_iterator(0, [num_elements](auto i) { return i != 0 && i != (num_elements - 1); })}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = cudf::rolling_window( input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); preceding = 2; following = 2; min_periods = 4; auto result_2 = cudf::rolling_window(input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto expected_result_2 = cudf::test::lists_column_wrapper<cudf::string_view>{ {{}, {"0", "1", "2", "3"}, {"1", "2", "3", "4"}, {"2", "3", "4", "5"}, {}, {}}, cudf::detail::make_counting_transform_iterator(0, [num_elements](auto i) { return i != 0 && i < 4; })}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result_2->view(), result_2->view()); auto result_2_with_nulls_excluded = cudf::rolling_window( input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result_2->view(), result_2_with_nulls_excluded->view()); } TEST_F(CollectListTest, RollingWindowHonoursMinPeriodsWithDecimal) { // Test that when the number of observations is fewer than min_periods, // the result is null. auto const input_iter = cudf::detail::make_counting_transform_iterator(0, thrust::identity<int32_t>{}); auto const input_column = cudf::test::fixed_point_column_wrapper<int32_t>{ input_iter, input_iter + 6, numeric::scale_type{0}}; { // One result row at each end should be null. auto preceding = 2; auto following = 1; auto min_periods = 3; auto const result = cudf::rolling_window(input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto expected_result_child_values = std::vector<int32_t>{0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4, 5}; auto expected_result_child = cudf::test::fixed_point_column_wrapper<int32_t>{expected_result_child_values.begin(), expected_result_child_values.end(), numeric::scale_type{0}}; auto expected_offsets = cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 0, 3, 6, 9, 12, 12}.release(); auto expected_num_rows = expected_offsets->size() - 1; auto null_mask_iter = cudf::detail::make_counting_transform_iterator( cudf::size_type{0}, [expected_num_rows](auto i) { return i != 0 && i != (expected_num_rows - 1); }); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(null_mask_iter, null_mask_iter + expected_num_rows); auto expected_result = cudf::make_lists_column(expected_num_rows, std::move(expected_offsets), expected_result_child.release(), null_count, std::move(null_mask)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = cudf::rolling_window( input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); } { // First result row, and the last two result rows should be null. auto preceding = 2; auto following = 2; auto min_periods = 4; auto const result = cudf::rolling_window(input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto expected_result_child_values = std::vector<int32_t>{0, 1, 2, 3, 1, 2, 3, 4, 2, 3, 4, 5}; auto expected_result_child = cudf::test::fixed_point_column_wrapper<int32_t>{expected_result_child_values.begin(), expected_result_child_values.end(), numeric::scale_type{0}}; auto expected_offsets = cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 0, 4, 8, 12, 12, 12}.release(); auto expected_num_rows = expected_offsets->size() - 1; auto null_mask_iter = cudf::detail::make_counting_transform_iterator( cudf::size_type{0}, [expected_num_rows](auto i) { return i > 0 && i < 4; }); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(null_mask_iter, null_mask_iter + expected_num_rows); auto expected_result = cudf::make_lists_column(expected_num_rows, std::move(expected_offsets), expected_result_child.release(), null_count, std::move(null_mask)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = cudf::rolling_window( input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); } } TYPED_TEST(TypedCollectListTest, BasicGroupedRollingWindow) { using T = TypeParam; auto const group_column = cudf::test::fixed_width_column_wrapper<int32_t>{1, 1, 1, 1, 1, 2, 2, 2, 2}; auto const input_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{10, 11, 12, 13, 14, 20, 21, 22, 23}; auto const preceding = 2; auto const following = 1; auto const min_periods = 1; auto const result = grouped_rolling_window(cudf::table_view{std::vector<cudf::column_view>{group_column}}, input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto const expected_result = cudf::test::lists_column_wrapper<T, int32_t>{ {10, 11}, {10, 11, 12}, {11, 12, 13}, {12, 13, 14}, {13, 14}, {20, 21}, {20, 21, 22}, {21, 22, 23}, {22, 23}}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = grouped_rolling_window( cudf::table_view{std::vector<cudf::column_view>{group_column}}, input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); } TYPED_TEST(TypedCollectListTest, BasicGroupedRollingWindowWithNulls) { using T = TypeParam; auto const group_column = cudf::test::fixed_width_column_wrapper<int32_t>{1, 1, 1, 1, 1, 2, 2, 2, 2}; auto const input_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{ {10, 11, 12, 13, 14, 20, 21, 22, 23}, {1, 0, 1, 1, 1, 1, 0, 1, 1}}; auto const preceding = 2; auto const following = 1; auto const min_periods = 1; { // Nulls included. auto const result = grouped_rolling_window(cudf::table_view{std::vector<cudf::column_view>{group_column}}, input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto expected_child = cudf::test::fixed_width_column_wrapper<T, int32_t>{ {10, 11, 10, 11, 12, 11, 12, 13, 12, 13, 14, 13, 14, 20, 21, 20, 21, 22, 21, 22, 23, 22, 23}, {1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1}}; auto expected_offsets = cudf::test::fixed_width_column_wrapper<int32_t>{0, 2, 5, 8, 11, 13, 15, 18, 21, 23}; auto expected_result = cudf::make_lists_column(static_cast<cudf::column_view>(group_column).size(), expected_offsets.release(), expected_child.release(), 0, {}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); } { // Nulls excluded. auto const result = grouped_rolling_window( cudf::table_view{std::vector<cudf::column_view>{group_column}}, input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); auto expected_child = cudf::test::fixed_width_column_wrapper<T, int32_t>{ 10, 10, 12, 12, 13, 12, 13, 14, 13, 14, 20, 20, 22, 22, 23, 22, 23}; auto expected_offsets = cudf::test::fixed_width_column_wrapper<int32_t>{0, 1, 3, 5, 8, 10, 11, 13, 15, 17}; auto expected_result = cudf::make_lists_column(static_cast<cudf::column_view>(group_column).size(), expected_offsets.release(), expected_child.release(), 0, {}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); } } TYPED_TEST(TypedCollectListTest, BasicGroupedTimeRangeRollingWindow) { using T = TypeParam; auto const time_column = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ 1, 1, 2, 2, 3, 1, 4, 5, 6}; auto const group_column = cudf::test::fixed_width_column_wrapper<int32_t>{1, 1, 1, 1, 1, 2, 2, 2, 2}; auto const input_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{10, 11, 12, 13, 14, 20, 21, 22, 23}; auto const preceding = 2; auto const following = 1; auto const min_periods = 1; auto const result = cudf::grouped_time_range_rolling_window( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto const expected_result = cudf::test::lists_column_wrapper<T, int32_t>{ {10, 11, 12, 13}, {10, 11, 12, 13}, {10, 11, 12, 13, 14}, {10, 11, 12, 13, 14}, {10, 11, 12, 13, 14}, {20}, {21, 22}, {21, 22, 23}, {21, 22, 23}}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = cudf::grouped_time_range_rolling_window( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); } TYPED_TEST(TypedCollectListTest, GroupedTimeRangeRollingWindowWithNulls) { using T = TypeParam; auto const time_column = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ 1, 1, 2, 2, 3, 1, 4, 5, 6}; auto const group_column = cudf::test::fixed_width_column_wrapper<int32_t>{1, 1, 1, 1, 1, 2, 2, 2, 2}; auto const input_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{ {10, 11, 12, 13, 14, 20, 21, 22, 23}, {1, 0, 1, 1, 1, 1, 0, 1, 1}}; auto const preceding = 2; auto const following = 1; auto const min_periods = 1; auto const result = cudf::grouped_time_range_rolling_window( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto null_at_0 = cudf::test::iterators::null_at(0); auto null_at_1 = cudf::test::iterators::null_at(1); // In the results, `11` and `21` should be nulls. auto const expected_result = cudf::test::lists_column_wrapper<T, int32_t>{ {{10, 11, 12, 13}, null_at_1}, {{10, 11, 12, 13}, null_at_1}, {{10, 11, 12, 13, 14}, null_at_1}, {{10, 11, 12, 13, 14}, null_at_1}, {{10, 11, 12, 13, 14}, null_at_1}, {{20}, null_at_1}, {{21, 22}, null_at_0}, {{21, 22, 23}, null_at_0}, {{21, 22, 23}, null_at_0}}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = cudf::grouped_time_range_rolling_window( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); // After null exclusion, `11`, `21`, and `null` should not appear. auto const expected_result_with_nulls_excluded = cudf::test::lists_column_wrapper<T, int32_t>{ {10, 12, 13}, {10, 12, 13}, {10, 12, 13, 14}, {10, 12, 13, 14}, {10, 12, 13, 14}, {20}, {22}, {22, 23}, {22, 23}}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result_with_nulls_excluded->view(), result_with_nulls_excluded->view()); } TEST_F(CollectListTest, BasicGroupedTimeRangeRollingWindowOnStrings) { auto const time_column = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ 1, 1, 2, 2, 3, 1, 4, 5, 6}; auto const group_column = cudf::test::fixed_width_column_wrapper<int32_t>{1, 1, 1, 1, 1, 2, 2, 2, 2}; auto const input_column = cudf::test::strings_column_wrapper{"10", "11", "12", "13", "14", "20", "21", "22", "23"}; auto const preceding = 2; auto const following = 1; auto const min_periods = 1; auto const result = cudf::grouped_time_range_rolling_window( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto const expected_result = cudf::test::lists_column_wrapper<cudf::string_view>{ {"10", "11", "12", "13"}, {"10", "11", "12", "13"}, {"10", "11", "12", "13", "14"}, {"10", "11", "12", "13", "14"}, {"10", "11", "12", "13", "14"}, {"20"}, {"21", "22"}, {"21", "22", "23"}, {"21", "22", "23"}}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = cudf::grouped_time_range_rolling_window( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); } TEST_F(CollectListTest, GroupedTimeRangeRollingWindowOnStringsWithNulls) { auto const time_column = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ 1, 1, 2, 2, 3, 1, 4, 5, 6}; auto const group_column = cudf::test::fixed_width_column_wrapper<int32_t>{1, 1, 1, 1, 1, 2, 2, 2, 2}; auto const input_column = cudf::test::strings_column_wrapper{ {"10", "11", "12", "13", "14", "20", "21", "22", "23"}, {1, 0, 1, 1, 1, 1, 0, 1, 1}}; auto const preceding = 2; auto const following = 1; auto const min_periods = 1; auto const result = cudf::grouped_time_range_rolling_window( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto null_at_0 = cudf::test::iterators::null_at(0); auto null_at_1 = cudf::test::iterators::null_at(1); // In the results, `11` and `21` should be nulls. auto const expected_result = cudf::test::lists_column_wrapper<cudf::string_view>{ {{"10", "11", "12", "13"}, null_at_1}, {{"10", "11", "12", "13"}, null_at_1}, {{"10", "11", "12", "13", "14"}, null_at_1}, {{"10", "11", "12", "13", "14"}, null_at_1}, {{"10", "11", "12", "13", "14"}, null_at_1}, {"20"}, {{"21", "22"}, null_at_0}, {{"21", "22", "23"}, null_at_0}, {{"21", "22", "23"}, null_at_0}}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = cudf::grouped_time_range_rolling_window( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); // After null exclusion, `11`, `21`, and `null` should not appear. auto const expected_result_with_nulls_excluded = cudf::test::lists_column_wrapper<cudf::string_view>{{"10", "12", "13"}, {"10", "12", "13"}, {"10", "12", "13", "14"}, {"10", "12", "13", "14"}, {"10", "12", "13", "14"}, {"20"}, {"22"}, {"22", "23"}, {"22", "23"}} .release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result_with_nulls_excluded->view(), result_with_nulls_excluded->view()); } TYPED_TEST(TypedCollectListTest, BasicGroupedTimeRangeRollingWindowOnStructs) { using T = TypeParam; auto const time_column = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ 1, 1, 2, 2, 3, 1, 4, 5, 6}; auto const group_column = cudf::test::fixed_width_column_wrapper<int32_t>{1, 1, 1, 1, 1, 2, 2, 2, 2}; auto numeric_member_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{10, 11, 12, 13, 14, 20, 21, 22, 23}; auto string_member_column = cudf::test::strings_column_wrapper{"10", "11", "12", "13", "14", "20", "21", "22", "23"}; auto struct_members = std::vector<std::unique_ptr<cudf::column>>{}; struct_members.emplace_back(numeric_member_column.release()); struct_members.emplace_back(string_member_column.release()); auto const struct_column = cudf::make_structs_column(9, std::move(struct_members), 0, {}); auto const preceding = 2; auto const following = 1; auto const min_periods = 1; auto const result = cudf::grouped_time_range_rolling_window( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, struct_column->view(), preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto expected_numeric_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{ 10, 11, 12, 13, 10, 11, 12, 13, 10, 11, 12, 13, 14, 10, 11, 12, 13, 14, 10, 11, 12, 13, 14, 20, 21, 22, 21, 22, 23, 21, 22, 23}; auto expected_string_column = cudf::test::strings_column_wrapper{ "10", "11", "12", "13", "10", "11", "12", "13", "10", "11", "12", "13", "14", "10", "11", "12", "13", "14", "10", "11", "12", "13", "14", "20", "21", "22", "21", "22", "23", "21", "22", "23"}; auto expected_struct_members = std::vector<std::unique_ptr<cudf::column>>{}; expected_struct_members.emplace_back(expected_numeric_column.release()); expected_struct_members.emplace_back(expected_string_column.release()); auto expected_structs_column = cudf::make_structs_column(32, std::move(expected_struct_members), 0, {}); auto expected_offsets_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 4, 8, 13, 18, 23, 24, 26, 29, 32} .release(); auto expected_result = cudf::make_lists_column( 9, std::move(expected_offsets_column), std::move(expected_structs_column), 0, {}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = cudf::grouped_time_range_rolling_window( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, struct_column->view(), preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); } TYPED_TEST(TypedCollectListTest, GroupedTimeRangeRollingWindowWithMinPeriods) { // Test that min_periods is honoured. // i.e. output row is null when min_periods exceeds number of observations. using T = TypeParam; auto const time_column = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ 1, 1, 2, 2, 3, 1, 4, 5, 6}; auto const group_column = cudf::test::fixed_width_column_wrapper<int32_t>{1, 1, 1, 1, 1, 2, 2, 2, 2}; auto const input_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{10, 11, 12, 13, 14, 20, 21, 22, 23}; auto const preceding = 2; auto const following = 1; auto const min_periods = 4; auto const result = cudf::grouped_time_range_rolling_window( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto const expected_result = cudf::test::lists_column_wrapper<T, int32_t>{ {{10, 11, 12, 13}, {10, 11, 12, 13}, {10, 11, 12, 13, 14}, {10, 11, 12, 13, 14}, {10, 11, 12, 13, 14}, {}, {}, {}, {}}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i < 5; })}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = cudf::grouped_time_range_rolling_window( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); } TYPED_TEST(TypedCollectListTest, GroupedTimeRangeRollingWindowWithNullsAndMinPeriods) { // Test that min_periods is honoured. // i.e. output row is null when min_periods exceeds number of observations. using T = TypeParam; auto const time_column = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ 1, 1, 2, 2, 3, 1, 4, 5, 6}; auto const group_column = cudf::test::fixed_width_column_wrapper<int32_t>{1, 1, 1, 1, 1, 2, 2, 2, 2}; auto const input_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{ {10, 11, 12, 13, 14, 20, 21, 22, 23}, {1, 0, 1, 1, 1, 1, 0, 1, 1}}; auto const preceding = 2; auto const following = 1; auto const min_periods = 4; auto const result = cudf::grouped_time_range_rolling_window( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto null_at_1 = cudf::test::iterators::null_at(1); // In the results, `11` and `21` should be nulls. auto const expected_result = cudf::test::lists_column_wrapper<T, int32_t>{ {{{10, 11, 12, 13}, null_at_1}, {{10, 11, 12, 13}, null_at_1}, {{10, 11, 12, 13, 14}, null_at_1}, {{10, 11, 12, 13, 14}, null_at_1}, {{10, 11, 12, 13, 14}, null_at_1}, {}, {}, {}, {}}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i < 5; })}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = cudf::grouped_time_range_rolling_window( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); // After null exclusion, `11`, `21`, and `null` should not appear. auto const expected_result_with_nulls_excluded = cudf::test::lists_column_wrapper<T, int32_t>{ {{10, 12, 13}, {10, 12, 13}, {10, 12, 13, 14}, {10, 12, 13, 14}, {10, 12, 13, 14}, {}, {}, {}, {}}, cudf::detail::make_counting_transform_iterator( 0, [](auto i) { return i < 5; })}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result_with_nulls_excluded->view(), result_with_nulls_excluded->view()); } TEST_F(CollectListTest, GroupedTimeRangeRollingWindowOnStringsWithMinPeriods) { // Test that min_periods is honoured. // i.e. output row is null when min_periods exceeds number of observations. auto const time_column = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ 1, 1, 2, 2, 3, 1, 4, 5, 6}; auto const group_column = cudf::test::fixed_width_column_wrapper<int32_t>{1, 1, 1, 1, 1, 2, 2, 2, 2}; auto const input_column = cudf::test::strings_column_wrapper{"10", "11", "12", "13", "14", "20", "21", "22", "23"}; auto const preceding = 2; auto const following = 1; auto const min_periods = 4; auto const result = cudf::grouped_time_range_rolling_window( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto const expected_result = cudf::test::lists_column_wrapper<cudf::string_view>{ {{"10", "11", "12", "13"}, {"10", "11", "12", "13"}, {"10", "11", "12", "13", "14"}, {"10", "11", "12", "13", "14"}, {"10", "11", "12", "13", "14"}, {}, {}, {}, {}}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i < 5; })}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = cudf::grouped_time_range_rolling_window( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); } TEST_F(CollectListTest, GroupedTimeRangeRollingWindowOnStringsWithNullsAndMinPeriods) { // Test that min_periods is honoured. // i.e. output row is null when min_periods exceeds number of observations. auto const time_column = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ 1, 1, 2, 2, 3, 1, 4, 5, 6}; auto const group_column = cudf::test::fixed_width_column_wrapper<int32_t>{1, 1, 1, 1, 1, 2, 2, 2, 2}; auto const input_column = cudf::test::strings_column_wrapper{ {"10", "11", "12", "13", "14", "20", "21", "22", "23"}, {1, 0, 1, 1, 1, 1, 0, 1, 1}}; auto const preceding = 2; auto const following = 1; auto const min_periods = 4; auto const result = cudf::grouped_time_range_rolling_window( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto null_at_1 = cudf::test::iterators::null_at(1); // In the results, `11` and `21` should be nulls. auto const expected_result = cudf::test::lists_column_wrapper<cudf::string_view>{ {{{"10", "11", "12", "13"}, null_at_1}, {{"10", "11", "12", "13"}, null_at_1}, {{"10", "11", "12", "13", "14"}, null_at_1}, {{"10", "11", "12", "13", "14"}, null_at_1}, {{"10", "11", "12", "13", "14"}, null_at_1}, {}, {}, {}, {}}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i < 5; })}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = cudf::grouped_time_range_rolling_window( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, input_column, preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); // After null exclusion, `11`, `21`, and `null` should not appear. auto const expected_result_with_nulls_excluded = cudf::test::lists_column_wrapper<cudf::string_view>{ {{"10", "12", "13"}, {"10", "12", "13"}, {"10", "12", "13", "14"}, {"10", "12", "13", "14"}, {"10", "12", "13", "14"}, {}, {}, {}, {}}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i < 5; })} .release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result_with_nulls_excluded->view(), result_with_nulls_excluded->view()); } TYPED_TEST(TypedCollectListTest, GroupedTimeRangeRollingWindowOnStructsWithMinPeriods) { // Test that min_periods is honoured. // i.e. output row is null when min_periods exceeds number of observations. using T = TypeParam; auto const time_column = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ 1, 1, 2, 2, 3, 1, 4, 5, 6}; auto const group_column = cudf::test::fixed_width_column_wrapper<int32_t>{1, 1, 1, 1, 1, 2, 2, 2, 2}; auto numeric_member_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{10, 11, 12, 13, 14, 20, 21, 22, 23}; auto string_member_column = cudf::test::strings_column_wrapper{"10", "11", "12", "13", "14", "20", "21", "22", "23"}; auto struct_members = std::vector<std::unique_ptr<cudf::column>>{}; struct_members.emplace_back(numeric_member_column.release()); struct_members.emplace_back(string_member_column.release()); auto const struct_column = cudf::make_structs_column(9, std::move(struct_members), 0, {}); auto const preceding = 2; auto const following = 1; auto const min_periods = 4; auto const result = cudf::grouped_time_range_rolling_window( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, struct_column->view(), preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>()); auto expected_numeric_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{ 10, 11, 12, 13, 10, 11, 12, 13, 10, 11, 12, 13, 14, 10, 11, 12, 13, 14, 10, 11, 12, 13, 14}; auto expected_string_column = cudf::test::strings_column_wrapper{ "10", "11", "12", "13", "10", "11", "12", "13", "10", "11", "12", "13", "14", "10", "11", "12", "13", "14", "10", "11", "12", "13", "14"}; auto expected_struct_members = std::vector<std::unique_ptr<cudf::column>>{}; expected_struct_members.emplace_back(expected_numeric_column.release()); expected_struct_members.emplace_back(expected_string_column.release()); auto expected_structs_column = cudf::make_structs_column(23, std::move(expected_struct_members), 0, {}); auto expected_offsets_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 4, 8, 13, 18, 23, 23, 23, 23, 23} .release(); auto expected_validity_iter = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i < 5; }); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(expected_validity_iter, expected_validity_iter + 9); auto expected_result = cudf::make_lists_column(9, std::move(expected_offsets_column), std::move(expected_structs_column), null_count, std::move(null_mask)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = cudf::grouped_time_range_rolling_window( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, struct_column->view(), preceding, following, min_periods, *cudf::make_collect_list_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); } // The results of `collect_set` are unordered lists. // Thus, we have to sort the lists for comparison. namespace { template <typename WindowType> auto rolling_collect_set(cudf::column_view const& input, WindowType const& preceding_window, WindowType const& following_window, cudf::size_type min_periods, cudf::rolling_aggregation const& agg) { auto const result = cudf::rolling_window(input, preceding_window, following_window, min_periods, agg); EXPECT_EQ(result->type().id(), cudf::type_id::LIST); return cudf::lists::sort_lists( cudf::lists_column_view{result->view()}, cudf::order::ASCENDING, cudf::null_order::AFTER); } template <typename WindowType> auto grouped_rolling_collect_set(cudf::table_view const& group_keys, cudf::column_view const& input, WindowType const& preceding_window, WindowType const& following_window, cudf::size_type min_periods, cudf::rolling_aggregation const& agg) { auto const result = cudf::grouped_rolling_window( group_keys, input, preceding_window, following_window, min_periods, agg); EXPECT_EQ(result->type().id(), cudf::type_id::LIST); return cudf::lists::sort_lists( cudf::lists_column_view{result->view()}, cudf::order::ASCENDING, cudf::null_order::AFTER); } template <typename WindowType> auto grouped_time_range_rolling_collect_set(cudf::table_view const& group_keys, cudf::column_view const& timestamp_column, cudf::order const& timestamp_order, cudf::column_view const& input, WindowType const& preceding_window_in_days, WindowType const& following_window_in_days, cudf::size_type min_periods, cudf::rolling_aggregation const& agg) { auto const result = cudf::grouped_time_range_rolling_window(group_keys, timestamp_column, timestamp_order, input, preceding_window_in_days, following_window_in_days, min_periods, agg); EXPECT_EQ(result->type().id(), cudf::type_id::LIST); return cudf::lists::sort_lists( cudf::lists_column_view{result->view()}, cudf::order::ASCENDING, cudf::null_order::AFTER); } } // namespace struct CollectSetTest : public cudf::test::BaseFixture {}; template <typename T> struct TypedCollectSetTest : public CollectSetTest {}; using TypesForSetTest = cudf::test::Concat<cudf::test::IntegralTypesNotBool, cudf::test::FloatingPointTypes, cudf::test::DurationTypes, cudf::test::FixedPointTypes>; TYPED_TEST_SUITE(TypedCollectSetTest, TypesForSetTest); TYPED_TEST(TypedCollectSetTest, BasicRollingWindow) { using T = TypeParam; auto const input_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{10, 10, 11, 12, 11}; auto const prev_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>{1, 2, 2, 2, 2}; auto const foll_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>{1, 1, 1, 1, 0}; EXPECT_EQ(static_cast<cudf::column_view>(prev_column).size(), static_cast<cudf::column_view>(foll_column).size()); auto const result_column_based_window = rolling_collect_set(input_column, prev_column, foll_column, 1, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>()); auto const expected_result = cudf::test::lists_column_wrapper<T, int32_t>{ {10}, {10, 11}, {10, 11, 12}, {11, 12}, {11, 12}, } .release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_column_based_window->view()); auto const result_fixed_window = rolling_collect_set( input_column, 2, 1, 1, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_fixed_window->view()); auto const result_with_nulls_excluded = rolling_collect_set( input_column, 2, 1, 1, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); } TYPED_TEST(TypedCollectSetTest, RollingWindowWithEmptyOutputLists) { using T = TypeParam; auto const input_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{10, 11, 11, 11, 14, 15}; auto const prev_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>{1, 2, 2, 0, 2, 2}; auto const foll_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>{1, 1, 1, 0, 1, 0}; EXPECT_EQ(static_cast<cudf::column_view>(prev_column).size(), static_cast<cudf::column_view>(foll_column).size()); auto const result_column_based_window = rolling_collect_set(input_column, prev_column, foll_column, 0, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>()); auto const expected_result = cudf::test::lists_column_wrapper<T, int32_t>{ {10, 11}, {10, 11}, {11}, {}, {11, 14, 15}, {14, 15}, } .release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_column_based_window->view()); auto const result_with_nulls_excluded = rolling_collect_set( input_column, prev_column, foll_column, 0, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); } TYPED_TEST(TypedCollectSetTest, RollingWindowHonoursMinPeriods) { // Test that when the number of observations is fewer than min_periods, // the result is null. using T = TypeParam; auto const input_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{0, 1, 2, 2, 4, 5}; auto const num_elements = static_cast<cudf::column_view>(input_column).size(); auto preceding = 2; auto following = 1; auto min_periods = 3; auto const result = rolling_collect_set(input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>()); auto const expected_result = cudf::test::lists_column_wrapper<T, int32_t>{ {{}, {0, 1, 2}, {1, 2}, {2, 4}, {2, 4, 5}, {}}, cudf::detail::make_counting_transform_iterator(0, [num_elements](auto i) { return i != 0 && i != (num_elements - 1); })}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = rolling_collect_set( input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); preceding = 2; following = 2; min_periods = 4; auto result_2 = rolling_collect_set(input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>()); auto expected_result_2 = cudf::test::lists_column_wrapper<T, int32_t>{ {{}, {0, 1, 2}, {1, 2, 4}, {2, 4, 5}, {}, {}}, cudf::detail::make_counting_transform_iterator(0, [num_elements](auto i) { return i != 0 && i < 4; })}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result_2->view(), result_2->view()); auto result_2_with_nulls_excluded = rolling_collect_set( input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result_2->view(), result_2_with_nulls_excluded->view()); } TEST_F(CollectSetTest, RollingWindowHonoursMinPeriodsOnStrings) { // Test that when the number of observations is fewer than min_periods, // the result is null. auto const input_column = cudf::test::strings_column_wrapper{"0", "1", "2", "2", "4", "4"}; auto const num_elements = static_cast<cudf::column_view>(input_column).size(); auto preceding = 2; auto following = 1; auto min_periods = 3; auto const result = rolling_collect_set(input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>()); auto const expected_result = cudf::test::lists_column_wrapper<cudf::string_view>{ {{}, {"0", "1", "2"}, {"1", "2"}, {"2", "4"}, {"2", "4"}, {}}, cudf::detail::make_counting_transform_iterator(0, [num_elements](auto i) { return i != 0 && i != (num_elements - 1); })}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = rolling_collect_set( input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); preceding = 2; following = 2; min_periods = 4; auto result_2 = rolling_collect_set(input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>()); auto expected_result_2 = cudf::test::lists_column_wrapper<cudf::string_view>{ {{}, {"0", "1", "2"}, {"1", "2", "4"}, {"2", "4"}, {}, {}}, cudf::detail::make_counting_transform_iterator(0, [num_elements](auto i) { return i != 0 && i < 4; })}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result_2->view(), result_2->view()); auto result_2_with_nulls_excluded = rolling_collect_set( input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result_2->view(), result_2_with_nulls_excluded->view()); } TEST_F(CollectSetTest, RollingWindowHonoursMinPeriodsWithDecimal) { // Test that when the number of observations is fewer than min_periods, // the result is null. auto const input_column = cudf::test::fixed_point_column_wrapper<int32_t>{{0, 0, 1, 2, 3, 3}, numeric::scale_type{0}}; { // One result row at each end should be null. auto preceding = 2; auto following = 1; auto min_periods = 3; auto const result = rolling_collect_set(input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>()); auto expected_result_child_values = std::vector<int32_t>{0, 1, 0, 1, 2, 1, 2, 3, 2, 3}; auto expected_result_child = cudf::test::fixed_point_column_wrapper<int32_t>{expected_result_child_values.begin(), expected_result_child_values.end(), numeric::scale_type{0}}; auto expected_offsets = cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 0, 2, 5, 8, 10, 10}.release(); auto expected_num_rows = expected_offsets->size() - 1; auto null_mask_iter = cudf::detail::make_counting_transform_iterator( cudf::size_type{0}, [expected_num_rows](auto i) { return i != 0 && i != (expected_num_rows - 1); }); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(null_mask_iter, null_mask_iter + expected_num_rows); auto expected_result = cudf::make_lists_column(expected_num_rows, std::move(expected_offsets), expected_result_child.release(), null_count, std::move(null_mask)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = rolling_collect_set( input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); } { // First result row, and the last two result rows should be null. auto preceding = 2; auto following = 2; auto min_periods = 4; auto const result = rolling_collect_set(input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>()); auto expected_result_child_values = std::vector<int32_t>{0, 1, 2, 0, 1, 2, 3, 1, 2, 3}; auto expected_result_child = cudf::test::fixed_point_column_wrapper<int32_t>{expected_result_child_values.begin(), expected_result_child_values.end(), numeric::scale_type{0}}; auto expected_offsets = cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 0, 3, 7, 10, 10, 10}.release(); auto expected_num_rows = expected_offsets->size() - 1; auto null_mask_iter = cudf::detail::make_counting_transform_iterator( cudf::size_type{0}, [expected_num_rows](auto i) { return i > 0 && i < 4; }); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(null_mask_iter, null_mask_iter + expected_num_rows); auto expected_result = cudf::make_lists_column(expected_num_rows, std::move(expected_offsets), expected_result_child.release(), null_count, std::move(null_mask)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = rolling_collect_set( input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); } } TYPED_TEST(TypedCollectSetTest, BasicGroupedRollingWindow) { using T = TypeParam; auto const group_column = cudf::test::fixed_width_column_wrapper<int32_t>{1, 1, 1, 1, 1, 2, 2, 2, 2}; auto const input_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{10, 11, 11, 13, 13, 20, 21, 20, 23}; auto const preceding = 2; auto const following = 1; auto const min_periods = 1; auto const result = grouped_rolling_collect_set(cudf::table_view{std::vector<cudf::column_view>{group_column}}, input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>()); auto const expected_result = cudf::test::lists_column_wrapper<T, int32_t>{ {10, 11}, {10, 11}, {11, 13}, {11, 13}, {13}, {20, 21}, {20, 21}, {20, 21, 23}, {20, 23}} .release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = grouped_rolling_collect_set( cudf::table_view{std::vector<cudf::column_view>{group_column}}, input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); } TYPED_TEST(TypedCollectSetTest, BasicGroupedRollingWindowWithNulls) { using T = TypeParam; auto const group_column = cudf::test::fixed_width_column_wrapper<int32_t>{1, 1, 1, 1, 1, 2, 2, 2, 2, 2}; auto const input_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{ {10, 0, 0, 13, 13, 20, 21, 0, 0, 23}, {1, 0, 0, 1, 1, 1, 1, 0, 0, 1}}; auto const preceding = 2; auto const following = 1; auto const min_periods = 1; { // Nulls included and nulls are equal. auto const result = grouped_rolling_collect_set(cudf::table_view{std::vector<cudf::column_view>{group_column}}, input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>()); // Null values are sorted to the tails of lists (sets) auto expected_child = cudf::test::fixed_width_column_wrapper<T, int32_t>{{ 10, 0, // row 0 10, 0, // row 1 13, 0, // row 2 13, 0, // row 3 13, // row 4 20, 21, // row 5 20, 21, 0, // row 6 21, 0, // row 7 23, 0, // row 8 23, 0, // row 9 }, { 1, 0, // row 0 1, 0, // row 1 1, 0, // row 2 1, 0, // row 3 1, // row 4 1, 1, // row 5 1, 1, 0, // row 6 1, 0, // row 7 1, 0, // row 8 1, 0 // row 9 }}; auto expected_offsets = cudf::test::fixed_width_column_wrapper<int32_t>{0, 2, 4, 6, 8, 9, 11, 14, 16, 18, 20}; auto expected_result = cudf::make_lists_column(static_cast<cudf::column_view>(group_column).size(), expected_offsets.release(), expected_child.release(), 0, {}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); } { // Nulls included and nulls are NOT equal. auto const result = grouped_rolling_collect_set(cudf::table_view{std::vector<cudf::column_view>{group_column}}, input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>( cudf::null_policy::INCLUDE, cudf::null_equality::UNEQUAL)); // Null values are sorted to the tails of lists (sets) auto expected_child = cudf::test::fixed_width_column_wrapper<T, int32_t>{{ 10, 0, // row 0 10, 0, 0, // row 1 13, 0, 0, // row 2 13, 0, // row 3 13, // row 4 20, 21, // row 5 20, 21, 0, // row 6 21, 0, 0, // row 7 23, 0, 0, // row 8 23, 0 // row 9 }, { 1, 0, // row 0 1, 0, 0, // row 1 1, 0, 0, // row 2 1, 0, // row 3 1, // row 4 1, 1, // row 5 1, 1, 0, // row 6 1, 0, 0, // row 7 1, 0, 0, // row 8 1, 0 // row 9 }}; auto expected_offsets = cudf::test::fixed_width_column_wrapper<int32_t>{0, 2, 5, 8, 10, 11, 13, 16, 19, 22, 24}; auto expected_result = cudf::make_lists_column(static_cast<cudf::column_view>(group_column).size(), expected_offsets.release(), expected_child.release(), 0, {}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); } { // Nulls excluded. auto const result = grouped_rolling_collect_set( cudf::table_view{std::vector<cudf::column_view>{group_column}}, input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); auto expected_child = cudf::test::fixed_width_column_wrapper<T, int32_t>{ 10, // row 0 10, // row 1 13, // row 2 13, // row 3 13, // row 4 20, 21, // row 5 20, 21, // row 6 21, // row 7 23, // row 8 23 // row 9 }; auto expected_offsets = cudf::test::fixed_width_column_wrapper<int32_t>{0, 1, 2, 3, 4, 5, 7, 9, 10, 11, 12}; auto expected_result = cudf::make_lists_column(static_cast<cudf::column_view>(group_column).size(), expected_offsets.release(), expected_child.release(), 0, {}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); } } TYPED_TEST(TypedCollectSetTest, BasicGroupedTimeRangeRollingWindow) { using T = TypeParam; auto const time_column = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ 1, 1, 2, 2, 3, 1, 4, 5, 6}; auto const group_column = cudf::test::fixed_width_column_wrapper<int32_t>{1, 1, 1, 1, 1, 2, 2, 2, 2}; auto const input_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{10, 11, 12, 13, 14, 20, 21, 22, 23}; auto const preceding = 2; auto const following = 1; auto const min_periods = 1; auto const result = grouped_time_range_rolling_collect_set( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>()); auto const expected_result = cudf::test::lists_column_wrapper<T, int32_t>{ {10, 11, 12, 13}, {10, 11, 12, 13}, {10, 11, 12, 13, 14}, {10, 11, 12, 13, 14}, {10, 11, 12, 13, 14}, {20}, {21, 22}, {21, 22, 23}, {21, 22, 23}}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = grouped_time_range_rolling_collect_set( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); } TYPED_TEST(TypedCollectSetTest, GroupedTimeRangeRollingWindowWithNulls) { using T = TypeParam; auto const time_column = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ 1, 1, 2, 2, 3, 1, 4, 5, 6}; auto const group_column = cudf::test::fixed_width_column_wrapper<int32_t>{1, 1, 1, 1, 1, 2, 2, 2, 2}; auto const input_column = cudf::test::fixed_width_column_wrapper<T, int32_t>{ {10, 10, 12, 13, 14, 20, 21, 22, 22}, {1, 0, 1, 1, 1, 1, 0, 1, 1}}; auto const preceding = 2; auto const following = 1; auto const min_periods = 1; auto const result = grouped_time_range_rolling_collect_set( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>()); auto null_at_1 = cudf::test::iterators::null_at(1); auto null_at_3 = cudf::test::iterators::null_at(3); auto null_at_4 = cudf::test::iterators::null_at(4); // In the results, `11` and `21` should be nulls. auto const expected_result = cudf::test::lists_column_wrapper<T, int32_t>{ {{10, 12, 13, 10}, null_at_3}, {{10, 12, 13, 10}, null_at_3}, {{10, 12, 13, 14, 10}, null_at_4}, {{10, 12, 13, 14, 10}, null_at_4}, {{10, 12, 13, 14, 10}, null_at_4}, {{20}, null_at_1}, {{22, 21}, null_at_1}, {{22, 21}, null_at_1}, {{22, 21}, null_at_1}}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = grouped_time_range_rolling_collect_set( cudf::table_view{std::vector<cudf::column_view>{group_column}}, time_column, cudf::order::ASCENDING, input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); // After null exclusion, `11`, `21`, and `null` should not appear. auto const expected_result_with_nulls_excluded = cudf::test::lists_column_wrapper<T, int32_t>{ {10, 12, 13}, {10, 12, 13}, {10, 12, 13, 14}, {10, 12, 13, 14}, {10, 12, 13, 14}, {20}, {22}, {22}, {22}}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result_with_nulls_excluded->view(), result_with_nulls_excluded->view()); } TYPED_TEST(TypedCollectSetTest, SlicedGroupedRollingWindow) { using T = TypeParam; auto const group_original = cudf::test::fixed_width_column_wrapper<int32_t>{1, 1, 1, 1, 1, 2, 2, 2, 2}; auto const input_original = cudf::test::fixed_width_column_wrapper<T, int32_t>{10, 11, 11, 13, 13, 20, 21, 21, 23}; auto const group_col = cudf::slice(group_original, {2, 7})[0]; // { 1, 1, 1, 2, 2 } auto const input_col = cudf::slice(input_original, {2, 7})[0]; // { 11, 13, 13, 20, 21 } auto const preceding = 2; auto const following = 1; auto const min_periods = 1; auto const result = grouped_rolling_collect_set(cudf::table_view{std::vector<cudf::column_view>{group_col}}, input_col, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>()); auto const expected_result = cudf::test::lists_column_wrapper<T, int32_t>{{11, 13}, {11, 13}, {13}, {20, 21}, {20, 21}} .release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); } TEST_F(CollectSetTest, BoolRollingWindow) { auto const input_column = cudf::test::fixed_width_column_wrapper<bool>{false, false, true, true, true}; auto const prev_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>{1, 2, 2, 2, 2}; auto const foll_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>{1, 1, 1, 1, 0}; EXPECT_EQ(static_cast<cudf::column_view>(prev_column).size(), static_cast<cudf::column_view>(foll_column).size()); auto const result_column_based_window = rolling_collect_set(input_column, prev_column, foll_column, 1, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>()); auto const expected_result = cudf::test::lists_column_wrapper<bool>{ {false}, {false, true}, {false, true}, {true}, {true}, } .release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_column_based_window->view()); auto const result_fixed_window = rolling_collect_set( input_column, 2, 1, 1, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_fixed_window->view()); auto const result_with_nulls_excluded = rolling_collect_set( input_column, 2, 1, 1, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); } TEST_F(CollectSetTest, BoolGroupedRollingWindow) { auto const group_column = cudf::test::fixed_width_column_wrapper<int32_t>{1, 1, 1, 1, 1, 2, 2, 2, 2}; auto const input_column = cudf::test::fixed_width_column_wrapper<bool>{ false, true, false, true, false, false, false, true, true}; auto const preceding = 2; auto const following = 1; auto const min_periods = 1; auto const result = grouped_rolling_collect_set(cudf::table_view{std::vector<cudf::column_view>{group_column}}, input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>()); auto const expected_result = cudf::test::lists_column_wrapper<bool>{ {false, true}, {false, true}, {false, true}, {false, true}, {false, true}, {false}, {false, true}, {false, true}, {true}}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); auto const result_with_nulls_excluded = grouped_rolling_collect_set( cudf::table_view{std::vector<cudf::column_view>{group_column}}, input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>(cudf::null_policy::EXCLUDE)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); } TEST_F(CollectSetTest, FloatGroupedRollingWindowWithNaNs) { auto const group_column = cudf::test::fixed_width_column_wrapper<int32_t>{1, 1, 1, 1, 1, 2, 2, 2, 2}; auto const input_column = cudf::test::fixed_width_column_wrapper<double>{ {1.23, 0.2341, 0.2341, -5.23e9, std::nan("1"), 1.1, std::nan("1"), std::nan("1"), 0.0}, {true, true, true, true, true, true, true, true, false}}; auto const preceding = 2; auto const following = 1; auto const min_periods = 1; // test on nan_equality::UNEQUAL auto const result = grouped_rolling_collect_set( cudf::table_view{std::vector<cudf::column_view>{group_column}}, input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>( cudf::null_policy::INCLUDE, cudf::null_equality::EQUAL, cudf::nan_equality::UNEQUAL)); auto const expected_result = cudf::test::lists_column_wrapper<double>{ {{0.2341, 1.23}, std::initializer_list<bool>{true, true}}, {{0.2341, 1.23}, std::initializer_list<bool>{true, true}}, {{-5.23e9, 0.2341}, std::initializer_list<bool>{true, true}}, {{-5.23e9, 0.2341, std::nan("1")}, std::initializer_list<bool>{true, true, true}}, {{-5.23e9, std::nan("1")}, std::initializer_list<bool>{true, true}}, {{1.1, std::nan("1")}, std::initializer_list<bool>{true, true}}, {{1.1, std::nan("1"), std::nan("1")}, std::initializer_list<bool>{true, true, true}}, {{std::nan("1"), std::nan("1"), 0.0}, std::initializer_list<bool>{true, true, false}}, {{std::nan("1"), 0.0}, std::initializer_list<bool>{ true, false}}}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result->view()); // test on nan_equality::ALL_EQUAL auto const result_nan_equal = grouped_rolling_collect_set( cudf::table_view{std::vector<cudf::column_view>{group_column}}, input_column, preceding, following, min_periods, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>( cudf::null_policy::INCLUDE, cudf::null_equality::EQUAL, cudf::nan_equality::ALL_EQUAL)); auto const expected_result_nan_equal = cudf::test::lists_column_wrapper<double>{ {{0.2341, 1.23}, std::initializer_list<bool>{true, true}}, {{0.2341, 1.23}, std::initializer_list<bool>{true, true}}, {{-5.23e9, 0.2341}, std::initializer_list<bool>{true, true}}, {{-5.23e9, 0.2341, std::nan("1")}, std::initializer_list<bool>{true, true, true}}, {{-5.23e9, std::nan("1")}, std::initializer_list<bool>{true, true}}, {{1.1, std::nan("1")}, std::initializer_list<bool>{true, true}}, {{1.1, std::nan("1")}, std::initializer_list<bool>{true, true}}, {{std::nan("1"), 0.0}, std::initializer_list<bool>{true, false}}, {{std::nan("1"), 0.0}, std::initializer_list<bool>{true, false}}}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result_nan_equal->view(), result_nan_equal->view()); } TEST_F(CollectSetTest, BasicRollingWindowWithNaNs) { auto const input_column = cudf::test::fixed_width_column_wrapper<double>{ 1.23, 0.2341, std::nan("1"), std::nan("1"), -5.23e9}; auto const prev_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>{1, 2, 2, 2, 2}; auto const foll_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>{1, 1, 1, 1, 0}; EXPECT_EQ(static_cast<cudf::column_view>(prev_column).size(), static_cast<cudf::column_view>(foll_column).size()); auto const result_column_based_window = rolling_collect_set( input_column, prev_column, foll_column, 1, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>( cudf::null_policy::INCLUDE, cudf::null_equality::EQUAL, cudf::nan_equality::UNEQUAL)); auto const expected_result = cudf::test::lists_column_wrapper<double>{ {0.2341, 1.23}, {0.2341, 1.23, std::nan("1")}, {0.2341, std::nan("1"), std::nan("1")}, {-5.23e9, std::nan("1"), std::nan("1")}, {-5.23e9, std::nan("1")}, } .release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_column_based_window->view()); auto const result_fixed_window = rolling_collect_set( input_column, 2, 1, 1, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>( cudf::null_policy::INCLUDE, cudf::null_equality::EQUAL, cudf::nan_equality::UNEQUAL)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_fixed_window->view()); auto const result_with_nulls_excluded = rolling_collect_set( input_column, 2, 1, 1, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>( cudf::null_policy::EXCLUDE, cudf::null_equality::EQUAL, cudf::nan_equality::UNEQUAL)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result->view(), result_with_nulls_excluded->view()); auto const expected_result_for_nan_equal = cudf::test::lists_column_wrapper<double>{ {0.2341, 1.23}, {0.2341, 1.23, std::nan("1")}, {0.2341, std::nan("1")}, {-5.23e9, std::nan("1")}, {-5.23e9, std::nan("1")}, } .release(); auto const result_with_nan_equal = rolling_collect_set( input_column, 2, 1, 1, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>( cudf::null_policy::INCLUDE, cudf::null_equality::EQUAL, cudf::nan_equality::ALL_EQUAL)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_result_for_nan_equal->view(), result_with_nan_equal->view()); } TEST_F(CollectSetTest, StructTypeRollingWindow) { auto col1 = cudf::test::fixed_width_column_wrapper<int32_t>{1, 2, 3, 4, 5}; auto col2 = cudf::test::strings_column_wrapper{"a", "b", "c", "d", "e"}; auto const input_column = cudf::test::structs_column_wrapper{{col1, col2}}; auto const prev_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>{1, 2, 2, 2, 2}; auto const foll_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>{1, 1, 1, 1, 0}; auto const expected = [] { auto child1 = cudf::test::fixed_width_column_wrapper<int32_t>{1, 2, 1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5}; auto child2 = cudf::test::strings_column_wrapper{ "a", "b", "a", "b", "c", "b", "c", "d", "c", "d", "e", "d", "e"}; return cudf::make_lists_column( 5, cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 2, 5, 8, 11, 13}.release(), cudf::test::structs_column_wrapper{{child1, child2}}.release(), 0, {}); }(); auto const result = rolling_collect_set(input_column, prev_column, foll_column, 1, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected->view(), result->view()); } TEST_F(CollectSetTest, ListTypeRollingWindow) { auto const input_column = cudf::test::lists_column_wrapper<int32_t>{{1, 2, 3}, {4, 5}, {6}, {7, 8, 9}, {10}}; auto const prev_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>{1, 2, 2, 2, 2}; auto const foll_column = cudf::test::fixed_width_column_wrapper<cudf::size_type>{1, 1, 1, 1, 0}; auto const expected = [] { auto data = cudf::test::fixed_width_column_wrapper<int32_t>{ 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9, 6, 7, 8, 9, 10, 7, 8, 9, 10}; auto inner_offsets = cudf::test::fixed_width_column_wrapper<int32_t>{ 0, 3, 5, 8, 10, 11, 13, 14, 17, 18, 21, 22, 25, 26}; auto outer_offsets = cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 2, 5, 8, 11, 13}; auto inner_list = cudf::make_lists_column(13, inner_offsets.release(), data.release(), 0, {}); return cudf::make_lists_column(5, outer_offsets.release(), std::move(inner_list), 0, {}); }(); auto const result = rolling_collect_set(input_column, prev_column, foll_column, 1, *cudf::make_collect_set_aggregation<cudf::rolling_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected->view(), result->view()); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/rolling/lead_lag_test.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/aggregation.hpp> #include <cudf/column/column_factories.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/dictionary/dictionary_factories.hpp> #include <cudf/rolling.hpp> #include <cudf/scalar/scalar_factories.hpp> #include <cudf/types.hpp> #include <cudf/utilities/error.hpp> #include <thrust/iterator/counting_iterator.h> #include <thrust/iterator/transform_iterator.h> #include <initializer_list> #include <memory> #include <string> struct LeadLagWindowTest : public cudf::test::BaseFixture {}; template <typename T> struct TypedLeadLagWindowTest : public cudf::test::BaseFixture {}; using TypesForTest = cudf::test::Concat<cudf::test::IntegralTypes, cudf::test::FloatingPointTypes, cudf::test::DurationTypes, cudf::test::TimestampTypes>; TYPED_TEST_SUITE(TypedLeadLagWindowTest, TypesForTest); TYPED_TEST(TypedLeadLagWindowTest, LeadLagBasics) { using T = int32_t; auto const input_col = cudf::test::fixed_width_column_wrapper<T>{0, 1, 2, 3, 4, 5, 0, 10, 20, 30, 40, 50}.release(); auto const grouping_key = cudf::test::fixed_width_column_wrapper<int32_t>{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grouping_key}}; auto const preceding = 4; auto const following = 3; auto const min_periods = 1; auto lead_3_output_col = cudf::grouped_rolling_window(grouping_keys, input_col->view(), preceding, following, min_periods, *cudf::make_lead_aggregation<cudf::rolling_aggregation>(3)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *lead_3_output_col, cudf::test::fixed_width_column_wrapper<T>{{3, 4, 5, -1, -1, -1, 30, 40, 50, -1, -1, -1}, {1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0}} .release() ->view()); auto lag_2_output_col = cudf::grouped_rolling_window(grouping_keys, input_col->view(), preceding, following, min_periods, *cudf::make_lag_aggregation<cudf::rolling_aggregation>(2)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *lag_2_output_col, cudf::test::fixed_width_column_wrapper<T>{{-1, -1, 0, 1, 2, 3, -1, -1, 0, 10, 20, 30}, {0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1}} .release() ->view()); } TYPED_TEST(TypedLeadLagWindowTest, LeadLagWithNulls) { using T = TypeParam; auto const input_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 0, 10, 20, 30, 40, 50}, {1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1}} .release(); auto const grouping_key = cudf::test::fixed_width_column_wrapper<int32_t>{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grouping_key}}; auto const preceding = 4; auto const following = 3; auto const min_periods = 1; auto lead_3_output_col = cudf::grouped_rolling_window(grouping_keys, input_col->view(), preceding, following, min_periods, *cudf::make_lead_aggregation<cudf::rolling_aggregation>(3)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *lead_3_output_col, cudf::test::fixed_width_column_wrapper<T>{{3, 4, 5, -1, -1, -1, 30, 40, 50, -1, -1, -1}, {1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0}} .release() ->view()); auto const lag_2_output_col = cudf::grouped_rolling_window(grouping_keys, input_col->view(), preceding, following, min_periods, *cudf::make_lag_aggregation<cudf::rolling_aggregation>(2)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *lag_2_output_col, cudf::test::fixed_width_column_wrapper<T>{{-1, -1, 0, 1, -1, 3, -1, -1, 0, 10, -1, 30}, {0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1}} .release() ->view()); } TYPED_TEST(TypedLeadLagWindowTest, TestLeadLagWithDefaults) { using T = TypeParam; auto const input_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 0, 10, 20, 30, 40, 50}, {1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1}} .release(); auto const grouping_key = cudf::test::fixed_width_column_wrapper<int32_t>{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grouping_key}}; auto const preceding = 4; auto const following = 3; auto const min_periods = 1; auto const default_value = cudf::make_fixed_width_scalar(cudf::test::detail::fixed_width_type_converter<int32_t, T>{}(99)); auto const default_outputs = cudf::make_column_from_scalar(*default_value, input_col->size()); auto lead_3_output_col = cudf::grouped_rolling_window(grouping_keys, input_col->view(), *default_outputs, preceding, following, min_periods, *cudf::make_lead_aggregation<cudf::rolling_aggregation>(3)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *lead_3_output_col, cudf::test::fixed_width_column_wrapper<T>{{3, 4, 5, 99, 99, 99, 30, 40, 50, 99, 99, 99}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}} .release() ->view()); auto const lag_2_output_col = cudf::grouped_rolling_window(grouping_keys, input_col->view(), *default_outputs, preceding, following, min_periods, *cudf::make_lag_aggregation<cudf::rolling_aggregation>(2)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *lag_2_output_col, cudf::test::fixed_width_column_wrapper<T>{{99, 99, 0, 1, -1, 3, 99, 99, 0, 10, -1, 30}, {1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1}} .release() ->view()); } TYPED_TEST(TypedLeadLagWindowTest, TestLeadLagWithDefaultsContainingNulls) { using T = TypeParam; auto const input_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 0, 10, 20, 30, 40, 50}, {1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1}} .release(); auto const grouping_key = cudf::test::fixed_width_column_wrapper<int32_t>{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grouping_key}}; auto const default_outputs = cudf::test::fixed_width_column_wrapper<T>{{-1, 99, -1, 99, 99, -1, 99, 99, -1, 99, 99, -1}, {0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0}} .release(); auto const preceding = 4; auto const following = 3; auto const min_periods = 1; auto lead_3_output_col = cudf::grouped_rolling_window(grouping_keys, input_col->view(), *default_outputs, preceding, following, min_periods, *cudf::make_lead_aggregation<cudf::rolling_aggregation>(3)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *lead_3_output_col, cudf::test::fixed_width_column_wrapper<T>{{3, 4, 5, 99, 99, -1, 30, 40, 50, 99, 99, -1}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0}} .release() ->view()); auto const lag_2_output_col = cudf::grouped_rolling_window(grouping_keys, input_col->view(), *default_outputs, preceding, following, min_periods, *cudf::make_lag_aggregation<cudf::rolling_aggregation>(2)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *lag_2_output_col, cudf::test::fixed_width_column_wrapper<T>{{-1, 99, 0, 1, -1, 3, 99, 99, 0, 10, -1, 30}, {0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1}} .release() ->view()); } TYPED_TEST(TypedLeadLagWindowTest, TestLeadLagWithOutOfRangeOffsets) { using T = TypeParam; auto const input_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 0, 10, 20, 30, 40, 50}, {1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1}} .release(); auto const grouping_key = cudf::test::fixed_width_column_wrapper<int32_t>{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grouping_key}}; auto const default_value = cudf::make_fixed_width_scalar(cudf::test::detail::fixed_width_type_converter<int32_t, T>{}(99)); auto const default_outputs = cudf::make_column_from_scalar(*default_value, input_col->size()); auto const preceding = 4; auto const following = 3; auto const min_periods = 1; auto lead_30_output_col = cudf::grouped_rolling_window(grouping_keys, input_col->view(), preceding, following, min_periods, *cudf::make_lead_aggregation<cudf::rolling_aggregation>(30)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *lead_30_output_col, cudf::test::fixed_width_column_wrapper<T>{{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}} .release() ->view()); auto const lag_20_output_col = cudf::grouped_rolling_window(grouping_keys, input_col->view(), *default_outputs, preceding, following, min_periods, *cudf::make_lag_aggregation<cudf::rolling_aggregation>(20)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *lag_20_output_col, cudf::test::fixed_width_column_wrapper<T>{{99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}} .release() ->view()); } TYPED_TEST(TypedLeadLagWindowTest, TestLeadLagWithZeroOffsets) { using T = TypeParam; auto const input_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 0, 10, 20, 30, 40, 50}, {1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1}} .release(); auto const grouping_key = cudf::test::fixed_width_column_wrapper<int32_t>{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grouping_key}}; auto const preceding = 4; auto const following = 3; auto const min_periods = 1; auto lead_0_output_col = cudf::grouped_rolling_window(grouping_keys, input_col->view(), preceding, following, min_periods, *cudf::make_lead_aggregation<cudf::rolling_aggregation>(0)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*lead_0_output_col, *input_col); auto const lag_0_output_col = cudf::grouped_rolling_window(grouping_keys, input_col->view(), preceding, following, min_periods, *cudf::make_lag_aggregation<cudf::rolling_aggregation>(0)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*lag_0_output_col, *input_col); } TYPED_TEST(TypedLeadLagWindowTest, TestLeadLagWithNegativeOffsets) { using T = TypeParam; auto const input_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5, 0, 10, 20, 30, 40, 50}, {1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1}} .release(); auto const grouping_key = cudf::test::fixed_width_column_wrapper<int32_t>{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grouping_key}}; auto const default_value = cudf::make_fixed_width_scalar(cudf::test::detail::fixed_width_type_converter<int32_t, T>{}(99)); auto const default_outputs = cudf::make_column_from_scalar(*default_value, input_col->size()); auto const preceding = 4; auto const following = 3; auto const min_periods = 1; auto lag_minus_3_output_col = cudf::grouped_rolling_window(grouping_keys, input_col->view(), *default_outputs, preceding, following, min_periods, *cudf::make_lag_aggregation<cudf::rolling_aggregation>(-3)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *lag_minus_3_output_col, cudf::test::fixed_width_column_wrapper<T>{{3, 4, 5, 99, 99, 99, 30, 40, 50, 99, 99, 99}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}} .release() ->view()); auto const lead_minus_2_output_col = cudf::grouped_rolling_window(grouping_keys, input_col->view(), *default_outputs, preceding, following, min_periods, *cudf::make_lead_aggregation<cudf::rolling_aggregation>(-2)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *lead_minus_2_output_col, cudf::test::fixed_width_column_wrapper<T>{{99, 99, 0, 1, -1, 3, 99, 99, 0, 10, -1, 30}, {1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1}} .release() ->view()); } TYPED_TEST(TypedLeadLagWindowTest, TestLeadLagWithNoGrouping) { using T = TypeParam; auto const input_col = cudf::test::fixed_width_column_wrapper<T>{{0, 1, 2, 3, 4, 5}, {1, 1, 0, 1, 1, 1}}.release(); auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{}}; auto const default_value = cudf::make_fixed_width_scalar(cudf::test::detail::fixed_width_type_converter<int32_t, T>{}(99)); auto const default_outputs = cudf::make_column_from_scalar(*default_value, input_col->size()); auto const preceding = 4; auto const following = 3; auto const min_periods = 1; auto lead_3_output_col = cudf::grouped_rolling_window(grouping_keys, input_col->view(), *default_outputs, preceding, following, min_periods, *cudf::make_lead_aggregation<cudf::rolling_aggregation>(3)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *lead_3_output_col, cudf::test::fixed_width_column_wrapper<T>{{3, 4, 5, 99, 99, 99}, {1, 1, 1, 1, 1, 1}} .release() ->view()); auto const lag_2_output_col = cudf::grouped_rolling_window(grouping_keys, input_col->view(), *default_outputs, preceding, following, min_periods, *cudf::make_lag_aggregation<cudf::rolling_aggregation>(2)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *lag_2_output_col, cudf::test::fixed_width_column_wrapper<T>{{99, 99, 0, 1, -1, 3}, {1, 1, 1, 1, 0, 1}} .release() ->view()); } TYPED_TEST(TypedLeadLagWindowTest, TestLeadLagWithAllNullInput) { using T = TypeParam; auto const input_col = cudf::test::fixed_width_column_wrapper<T>{ {0, 1, 2, 3, 4, 5, 0, 10, 20, 30, 40, 50}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return false; })}.release(); auto const grouping_key = cudf::test::fixed_width_column_wrapper<int32_t>{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grouping_key}}; auto const default_value = cudf::make_fixed_width_scalar(cudf::test::detail::fixed_width_type_converter<int32_t, T>{}(99)); auto const default_outputs = cudf::make_column_from_scalar(*default_value, input_col->size()); auto const preceding = 4; auto const following = 3; auto const min_periods = 1; auto lead_3_output_col = cudf::grouped_rolling_window(grouping_keys, input_col->view(), *default_outputs, preceding, following, min_periods, *cudf::make_lead_aggregation<cudf::rolling_aggregation>(3)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *lead_3_output_col, cudf::test::fixed_width_column_wrapper<T>{{-1, -1, -1, 99, 99, 99, -1, -1, -1, 99, 99, 99}, {0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1}} .release() ->view()); auto const lag_2_output_col = cudf::grouped_rolling_window(grouping_keys, input_col->view(), *default_outputs, preceding, following, min_periods, *cudf::make_lag_aggregation<cudf::rolling_aggregation>(2)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( *lag_2_output_col, cudf::test::fixed_width_column_wrapper<T>{{99, 99, -1, -1, -1, -1, 99, 99, -1, -1, -1, -1}, {1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0}} .release() ->view()); } TYPED_TEST(TypedLeadLagWindowTest, DefaultValuesWithoutLeadLag) { // Test that passing default values for window-functions // other than lead/lag lead to cudf::logic_error. using T = TypeParam; auto const input_col = cudf::test::fixed_width_column_wrapper<T>{ {0, 1, 2, 3, 4, 5}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return true; })}.release(); auto const grouping_key = cudf::test::fixed_width_column_wrapper<int32_t>{0, 0, 0, 0, 0, 0}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grouping_key}}; auto const default_value = cudf::make_fixed_width_scalar(cudf::test::detail::fixed_width_type_converter<int32_t, T>{}(99)); auto const default_outputs = cudf::make_column_from_scalar(*default_value, input_col->size()); auto const preceding = 4; auto const following = 3; auto const min_periods = 1; auto const assert_aggregation_fails = [&](auto&& aggr) { EXPECT_THROW( cudf::grouped_rolling_window(grouping_keys, input_col->view(), default_outputs->view(), preceding, following, min_periods, *cudf::make_count_aggregation<cudf::rolling_aggregation>()), cudf::logic_error); }; auto aggs = {cudf::make_count_aggregation<cudf::rolling_aggregation>(), cudf::make_min_aggregation<cudf::rolling_aggregation>()}; std::for_each( aggs.begin(), aggs.end(), [&](auto& agg) { assert_aggregation_fails(std::move(agg)); }); } template <typename T> struct TypedNestedLeadLagWindowTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(TypedNestedLeadLagWindowTest, TypesForTest); TYPED_TEST(TypedNestedLeadLagWindowTest, NumericListsWithNullsAllOver) { using T = TypeParam; using lcw = cudf::test::lists_column_wrapper<T, int32_t>; auto null_at_2 = cudf::test::iterators::null_at(2); auto const input_col = lcw{{{0, 0}, {1, 1}, {2, 2}, {3, 3, 3}, {{4, 4, 4, 4}, null_at_2}, {5, 5, 5, 5, 5}, {0, 0}, {10, 10}, {20, 20}, {30, 30, 30}, {40, 40, 40, 40}, {{50, 50, 50, 50, 50}, null_at_2}}, null_at_2} .release(); auto const grouping_key = cudf::test::fixed_width_column_wrapper<int32_t>{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grouping_key}}; auto const preceding = 4; auto const following = 3; auto const min_periods = 1; auto lead_3_output_col = cudf::grouped_rolling_window(grouping_keys, input_col->view(), preceding, following, min_periods, *cudf::make_lead_aggregation<cudf::rolling_aggregation>(3)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(lead_3_output_col->view(), lcw{{{3, 3, 3}, {{4, 4, 4, 4}, null_at_2}, {5, 5, 5, 5, 5}, {}, {}, {}, {30, 30, 30}, {40, 40, 40, 40}, {{50, 50, 50, 50, 50}, null_at_2}, {}, {}, {}}, cudf::test::iterators::nulls_at({3, 4, 5, 9, 10, 11})} .release() ->view()); auto lag_1_output_col = cudf::grouped_rolling_window(grouping_keys, input_col->view(), preceding, following, min_periods, *cudf::make_lag_aggregation<cudf::rolling_aggregation>(1)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(lag_1_output_col->view(), lcw{{{}, {0, 0}, {1, 1}, {2, 2}, {3, 3, 3}, {{4, 4, 4, 4}, null_at_2}, {}, {0, 0}, {10, 10}, {20, 20}, {30, 30, 30}, {40, 40, 40, 40}}, cudf::test::iterators::nulls_at({0, 3, 6})} .release() ->view()); } TYPED_TEST(TypedNestedLeadLagWindowTest, NumericListsWithDefaults) { using T = TypeParam; using lcw = cudf::test::lists_column_wrapper<T, int32_t>; auto null_at_2 = cudf::test::iterators::null_at(2); auto const input_col = lcw{{{0, 0}, {1, 1}, {2, 2}, {3, 3, 3}, {{4, 4, 4, 4}, null_at_2}, {5, 5, 5, 5, 5}, {0, 0}, {10, 10}, {20, 20}, {30, 30, 30}, {40, 40, 40, 40}, {{50, 50, 50, 50, 50}, null_at_2}}, null_at_2} .release(); auto const defaults_col = lcw{ { {}, {91, 91}, {92, 92}, {}, // null! {94, 94, 94}, {95, 95}, {}, {91, 91}, {92, 92}, {}, // null! {94, 94, 94}, {95, 95}, }, } .release(); auto const grouping_key = cudf::test::fixed_width_column_wrapper<int32_t>{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grouping_key}}; auto const preceding = 4; auto const following = 3; auto const min_periods = 1; auto lead_3_output_col = cudf::grouped_rolling_window(grouping_keys, input_col->view(), preceding, following, min_periods, *cudf::make_lead_aggregation<cudf::rolling_aggregation>(3)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(lead_3_output_col->view(), lcw{{{3, 3, 3}, {{4, 4, 4, 4}, null_at_2}, {5, 5, 5, 5, 5}, {}, {}, {}, {30, 30, 30}, {40, 40, 40, 40}, {{50, 50, 50, 50, 50}, null_at_2}, {}, {}, {}}, cudf::test::iterators::nulls_at({3, 4, 5, 9, 10, 11})} .release() ->view()); auto lag_1_output_col = cudf::grouped_rolling_window(grouping_keys, input_col->view(), preceding, following, min_periods, *cudf::make_lag_aggregation<cudf::rolling_aggregation>(1)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(lag_1_output_col->view(), lcw{{{}, {0, 0}, {1, 1}, {2, 2}, {3, 3, 3}, {{4, 4, 4, 4}, null_at_2}, {}, {0, 0}, {10, 10}, {20, 20}, {30, 30, 30}, {40, 40, 40, 40}}, cudf::test::iterators::nulls_at({0, 3, 6})} .release() ->view()); } TYPED_TEST(TypedNestedLeadLagWindowTest, Structs) { using T = TypeParam; using lcw = cudf::test::lists_column_wrapper<T, int32_t>; auto null_at_2 = cudf::test::iterators::null_at(2); auto lists_col = lcw{{{0, 0}, {1, 1}, {2, 2}, {3, 3, 3}, {{4, 4, 4, 4}, null_at_2}, {5, 5, 5, 5, 5}, {0, 0}, {10, 10}, {20, 20}, {30, 30, 30}, {40, 40, 40, 40}, {{50, 50, 50, 50, 50}, null_at_2}}, null_at_2}; auto strings_col = cudf::test::strings_column_wrapper{{"00", "11", "22", "333", "4444", "55555", "00", "1010", "2020", "303030", "40404040", "5050505050"}, cudf::test::iterators::null_at(9)}; auto structs_col = cudf::test::structs_column_wrapper{lists_col, strings_col}.release(); auto const grouping_key = cudf::test::fixed_width_column_wrapper<int32_t>{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grouping_key}}; auto const preceding = 4; auto const following = 3; auto const min_periods = 1; // Test LEAD(). { auto lead_3_output_col = cudf::grouped_rolling_window(grouping_keys, structs_col->view(), preceding, following, min_periods, *cudf::make_lead_aggregation<cudf::rolling_aggregation>(3)); auto expected_lists_col = lcw{{{3, 3, 3}, {{4, 4, 4, 4}, null_at_2}, {5, 5, 5, 5, 5}, {}, {}, {}, {30, 30, 30}, {40, 40, 40, 40}, {{50, 50, 50, 50, 50}, null_at_2}, {}, {}, {}}, cudf::test::iterators::nulls_at({3, 4, 5, 9, 10, 11})}; auto expected_strings_col = cudf::test::strings_column_wrapper{ {"333", "4444", "55555", "", "", "", "", "40404040", "5050505050", "", "", ""}, cudf::test::iterators::nulls_at({3, 4, 5, 6, 9, 10, 11})}; auto expected_structs_col = cudf::test::structs_column_wrapper{{expected_lists_col, expected_strings_col}, cudf::test::iterators::nulls_at({3, 4, 5, 9, 10, 11})} .release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(lead_3_output_col->view(), expected_structs_col->view()); } // Test LAG() { auto lag_1_output_col = cudf::grouped_rolling_window(grouping_keys, structs_col->view(), preceding, following, min_periods, *cudf::make_lag_aggregation<cudf::rolling_aggregation>(1)); auto expected_lists_col = lcw{{{}, // null. {0, 0}, {1, 1}, {}, // null. {3, 3, 3}, {{4, 4, 4, 4}, null_at_2}, {}, // null. {0, 0}, {10, 10}, {20, 20}, {30, 30, 30}, {40, 40, 40, 40}}, cudf::test::iterators::nulls_at({0, 3, 6})}; auto expected_strings_col = cudf::test::strings_column_wrapper{{"", // null. "00", "11", "22", "333", "4444", "", // null. "00", "1010", "2020", "", // null. "40404040"}, cudf::test::iterators::nulls_at({0, 6, 10})}; auto expected_structs_col = cudf::test::structs_column_wrapper{{expected_lists_col, expected_strings_col}, cudf::test::iterators::nulls_at({0, 6})} .release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(lag_1_output_col->view(), expected_structs_col->view()); } } struct LeadLagNonFixedWidthTest : cudf::test::BaseFixture {}; TEST_F(LeadLagNonFixedWidthTest, StringsNoDefaults) { auto input_col = cudf::test::strings_column_wrapper{{"", "A_1", "A_22", "A_333", "A_4444", "A_55555", "B_0", "", "B_22", "B_333", "B_4444", "B_55555"}, cudf::test::iterators::nulls_at(std::vector{0, 7})} .release(); auto const grouping_key = cudf::test::fixed_width_column_wrapper<int32_t>{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grouping_key}}; auto const preceding = 4; auto const following = 3; auto const min_periods = 1; auto lead_2 = grouped_rolling_window(grouping_keys, input_col->view(), preceding, following, min_periods, *cudf::make_lead_aggregation<cudf::rolling_aggregation>(2)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( lead_2->view(), cudf::test::strings_column_wrapper{ {"A_22", "A_333", "A_4444", "A_55555", "", "", "B_22", "B_333", "B_4444", "B_55555", "", ""}, cudf::test::iterators::nulls_at(std::vector{4, 5, 10, 11})}); auto lag_1 = grouped_rolling_window(grouping_keys, input_col->view(), preceding, following, min_periods, *cudf::make_lag_aggregation<cudf::rolling_aggregation>(1)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( lag_1->view(), cudf::test::strings_column_wrapper{ {"", "", "A_1", "A_22", "A_333", "A_4444", "", "B_0", "", "B_22", "B_333", "B_4444"}, cudf::test::iterators::nulls_at(std::vector{0, 1, 6, 8})}); } TEST_F(LeadLagNonFixedWidthTest, StringsWithDefaults) { auto input_col = cudf::test::strings_column_wrapper{{"", "A_1", "A_22", "A_333", "A_4444", "A_55555", "B_0", "", "B_22", "B_333", "B_4444", "B_55555"}, cudf::test::iterators::nulls_at(std::vector{0, 7})} .release(); auto defaults_col = cudf::test::strings_column_wrapper{"9999", "9999", "9999", "9999", "9999", "9999", "9999", "9999", "9999", "9999", "9999", "9999"} .release(); auto const grouping_key = cudf::test::fixed_width_column_wrapper<int32_t>{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grouping_key}}; auto const preceding = 4; auto const following = 3; auto const min_periods = 1; auto lead_2 = grouped_rolling_window(grouping_keys, input_col->view(), defaults_col->view(), preceding, following, min_periods, *cudf::make_lead_aggregation<cudf::rolling_aggregation>(2)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(lead_2->view(), cudf::test::strings_column_wrapper{"A_22", "A_333", "A_4444", "A_55555", "9999", "9999", "B_22", "B_333", "B_4444", "B_55555", "9999", "9999"}); auto lag_1 = grouped_rolling_window(grouping_keys, input_col->view(), defaults_col->view(), preceding, following, min_periods, *cudf::make_lag_aggregation<cudf::rolling_aggregation>(1)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( lag_1->view(), cudf::test::strings_column_wrapper{ {"9999", "", "A_1", "A_22", "A_333", "A_4444", "9999", "B_0", "", "B_22", "B_333", "B_4444"}, cudf::test::iterators::nulls_at(std::vector{1, 8})}); } TEST_F(LeadLagNonFixedWidthTest, StringsWithDefaultsNoGroups) { auto input_col = cudf::test::strings_column_wrapper{{"", "A_1", "A_22", "A_333", "A_4444", "A_55555", "B_0", "", "B_22", "B_333", "B_4444", "B_55555"}, cudf::test::iterators::nulls_at(std::vector{0, 7})} .release(); auto defaults_col = cudf::test::strings_column_wrapper{"9999", "9999", "9999", "9999", "9999", "9999", "9999", "9999", "9999", "9999", "9999", "9999"} .release(); auto const grouping_key = cudf::test::fixed_width_column_wrapper<int32_t>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grouping_key}}; auto const preceding = 4; auto const following = 3; auto const min_periods = 1; auto lead_2 = grouped_rolling_window(grouping_keys, input_col->view(), defaults_col->view(), preceding, following, min_periods, *cudf::make_lead_aggregation<cudf::rolling_aggregation>(2)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( lead_2->view(), cudf::test::strings_column_wrapper{{"A_22", "A_333", "A_4444", "A_55555", "B_0", "", "B_22", "B_333", "B_4444", "B_55555", "9999", "9999"}, cudf::test::iterators::null_at(5)}); auto lag_1 = grouped_rolling_window(grouping_keys, input_col->view(), defaults_col->view(), preceding, following, min_periods, *cudf::make_lag_aggregation<cudf::rolling_aggregation>(1)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( lag_1->view(), cudf::test::strings_column_wrapper{{"9999", "", "A_1", "A_22", "A_333", "A_4444", "A_55555", "B_0", "", "B_22", "B_333", "B_4444"}, cudf::test::iterators::nulls_at(std::vector{1, 8})}); } TEST_F(LeadLagNonFixedWidthTest, Dictionary) { using dictionary = cudf::test::dictionary_column_wrapper<std::string>; auto input_strings = std::initializer_list<std::string>{"", "A_1", "A_22", "A_333", "A_4444", "A_55555", "B_0", "", "B_22", "B_333", "B_4444", "B_55555"}; auto input_col = dictionary{input_strings}.release(); auto const grouping_key = cudf::test::fixed_width_column_wrapper<int32_t>{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1}; auto const grouping_keys = cudf::table_view{std::vector<cudf::column_view>{grouping_key}}; auto const preceding = 4; auto const following = 3; auto const min_periods = 1; { auto lead_2 = grouped_rolling_window(grouping_keys, input_col->view(), preceding, following, min_periods, *cudf::make_lead_aggregation<cudf::rolling_aggregation>(2)); auto expected_keys = cudf::test::strings_column_wrapper{input_strings}.release(); auto expected_values = cudf::test::fixed_width_column_wrapper<uint32_t>{ {2, 3, 4, 5, 0, 0, 7, 8, 9, 10, 0, 0}, cudf::test::iterators::nulls_at(std::vector{4, 5, 10, 11})} .release(); auto expected_output = make_dictionary_column(expected_keys->view(), expected_values->view()).release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(lead_2->view(), expected_output->view()); } { auto lag_1 = grouped_rolling_window(grouping_keys, input_col->view(), preceding, following, min_periods, *cudf::make_lag_aggregation<cudf::rolling_aggregation>(1)); auto expected_keys = cudf::test::strings_column_wrapper{input_strings}.release(); auto expected_values = cudf::test::fixed_width_column_wrapper<uint32_t>{ {0, 0, 1, 2, 3, 4, 0, 6, 0, 7, 8, 9}, cudf::test::iterators::nulls_at(std::vector{0, 6})} .release(); auto expected_output = make_dictionary_column(expected_keys->view(), expected_values->view()).release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(lag_1->view(), expected_output->view()); } }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/reshape/interleave_columns_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/column/column_factories.hpp> #include <cudf/reshape.hpp> using namespace cudf::test::iterators; namespace { constexpr cudf::test::debug_output_level verbosity{cudf::test::debug_output_level::FIRST_ERROR}; using TView = cudf::table_view; using IntCol = cudf::test::fixed_width_column_wrapper<int32_t>; using StructsCol = cudf::test::structs_column_wrapper; using StringsCol = cudf::test::strings_column_wrapper; using StrListsCol = cudf::test::lists_column_wrapper<cudf::string_view>; using IntListsCol = cudf::test::lists_column_wrapper<int32_t>; constexpr int32_t null{0}; // mark for null elements constexpr int32_t NOT_USE{-1}; // mark for elements that we don't care } // namespace template <typename T> struct InterleaveColumnsTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(InterleaveColumnsTest, cudf::test::FixedWidthTypes); TYPED_TEST(InterleaveColumnsTest, NoColumns) { cudf::table_view in(std::vector<cudf::column_view>{}); EXPECT_THROW(cudf::interleave_columns(in), cudf::logic_error); } TYPED_TEST(InterleaveColumnsTest, OneColumn) { using T = TypeParam; cudf::test::fixed_width_column_wrapper<T, int32_t> a({-1, 0, 1}); cudf::table_view in(std::vector<cudf::column_view>{a}); auto expected = cudf::test::fixed_width_column_wrapper<T, int32_t>({-1, 0, 1}); auto actual = cudf::interleave_columns(in); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, actual->view()); } TYPED_TEST(InterleaveColumnsTest, TwoColumns) { using T = TypeParam; auto a = cudf::test::fixed_width_column_wrapper<T, int32_t>({0, 2}); auto b = cudf::test::fixed_width_column_wrapper<T, int32_t>({1, 3}); cudf::table_view in(std::vector<cudf::column_view>{a, b}); auto expected = cudf::test::fixed_width_column_wrapper<T, int32_t>({0, 1, 2, 3}); auto actual = cudf::interleave_columns(in); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, actual->view()); } TYPED_TEST(InterleaveColumnsTest, ThreeColumns) { using T = TypeParam; auto a = cudf::test::fixed_width_column_wrapper<T, int32_t>({0, 3, 6}); auto b = cudf::test::fixed_width_column_wrapper<T, int32_t>({1, 4, 7}); auto c = cudf::test::fixed_width_column_wrapper<T, int32_t>({2, 5, 8}); cudf::table_view in(std::vector<cudf::column_view>{a, b, c}); auto expected = cudf::test::fixed_width_column_wrapper<T, int32_t>({0, 1, 2, 3, 4, 5, 6, 7, 8}); auto actual = cudf::interleave_columns(in); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, actual->view()); } TYPED_TEST(InterleaveColumnsTest, OneColumnEmpty) { using T = TypeParam; cudf::test::fixed_width_column_wrapper<T> a({}); cudf::table_view in(std::vector<cudf::column_view>{a}); auto expected = cudf::test::fixed_width_column_wrapper<T>({}); auto actual = cudf::interleave_columns(in); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, actual->view()); } TYPED_TEST(InterleaveColumnsTest, ThreeColumnsEmpty) { using T = TypeParam; cudf::test::fixed_width_column_wrapper<T> a({}); cudf::test::fixed_width_column_wrapper<T> b({}); cudf::test::fixed_width_column_wrapper<T> c({}); cudf::table_view in(std::vector<cudf::column_view>{a, b, c}); auto expected = cudf::test::fixed_width_column_wrapper<T>({}); auto actual = cudf::interleave_columns(in); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, actual->view()); } TYPED_TEST(InterleaveColumnsTest, OneColumnNullable) { using T = TypeParam; cudf::test::fixed_width_column_wrapper<T, int32_t> a({1, 2, 3}, {0, 1, 0}); cudf::table_view in(std::vector<cudf::column_view>{a}); auto expected = cudf::test::fixed_width_column_wrapper<T, int32_t>({0, 2, 0}, {0, 1, 0}); auto actual = cudf::interleave_columns(in); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, actual->view()); } TYPED_TEST(InterleaveColumnsTest, TwoColumnNullable) { using T = TypeParam; cudf::test::fixed_width_column_wrapper<T, int32_t> a({1, 2, 3}, {0, 1, 0}); cudf::test::fixed_width_column_wrapper<T, int32_t> b({4, 5, 6}, {1, 0, 1}); cudf::table_view in(std::vector<cudf::column_view>{a, b}); auto expected = cudf::test::fixed_width_column_wrapper<T, int32_t>({0, 4, 2, 0, 0, 6}, {0, 1, 1, 0, 0, 1}); auto actual = cudf::interleave_columns(in); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, actual->view()); } TYPED_TEST(InterleaveColumnsTest, ThreeColumnsNullable) { using T = TypeParam; cudf::test::fixed_width_column_wrapper<T, int32_t> a({1, 4, 7}, {1, 0, 1}); cudf::test::fixed_width_column_wrapper<T, int32_t> b({2, 5, 8}, {0, 1, 0}); cudf::test::fixed_width_column_wrapper<T, int32_t> c({3, 6, 9}, {1, 0, 1}); cudf::table_view in(std::vector<cudf::column_view>{a, b, c}); auto expected = cudf::test::fixed_width_column_wrapper<T, int32_t>({1, 0, 3, 0, 5, 0, 7, 0, 9}, {1, 0, 1, 0, 1, 0, 1, 0, 1}); auto actual = cudf::interleave_columns(in); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, actual->view()); } TYPED_TEST(InterleaveColumnsTest, MismatchedDtypes) { using T = TypeParam; if (not std::is_same_v<int, T> and not cudf::is_fixed_point<T>()) { cudf::test::fixed_width_column_wrapper<int32_t> input_a({1, 4, 7}, {1, 0, 1}); cudf::test::fixed_width_column_wrapper<T, int32_t> input_b({2, 5, 8}, {0, 1, 0}); cudf::table_view input(std::vector<cudf::column_view>{input_a, input_b}); EXPECT_THROW(cudf::interleave_columns(input), cudf::logic_error); } } struct InterleaveStringsColumnsTest : public cudf::test::BaseFixture {}; TEST_F(InterleaveStringsColumnsTest, ZeroSizedColumns) { auto const col0 = cudf::make_empty_column(cudf::type_id::STRING)->view(); auto results = cudf::interleave_columns(cudf::table_view{{col0}}); cudf::test::expect_column_empty(results->view()); } TEST_F(InterleaveStringsColumnsTest, SingleColumn) { auto col0 = cudf::test::strings_column_wrapper({"", "", "", ""}, {false, true, true, false}); auto results = cudf::interleave_columns(cudf::table_view{{col0}}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, col0, verbosity); } TEST_F(InterleaveStringsColumnsTest, MultiColumnNullAndEmpty) { auto col0 = cudf::test::strings_column_wrapper({"", "", "", ""}, {false, true, true, false}); auto col1 = cudf::test::strings_column_wrapper({"", "", "", ""}, {true, false, true, false}); auto exp_results = cudf::test::strings_column_wrapper( {"", "", "", "", "", "", "", ""}, {false, true, true, false, true, true, false, false}); auto results = cudf::interleave_columns(cudf::table_view{{col0, col1}}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, exp_results, verbosity); } TEST_F(InterleaveStringsColumnsTest, MultiColumnEmptyNonNullable) { auto col0 = cudf::test::strings_column_wrapper({"", "", "", ""}); auto col1 = cudf::test::strings_column_wrapper({"", "", "", ""}); auto exp_results = cudf::test::strings_column_wrapper({"", "", "", "", "", "", "", ""}); auto results = cudf::interleave_columns(cudf::table_view{{col0, col1}}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, exp_results, verbosity); } TEST_F(InterleaveStringsColumnsTest, MultiColumnStringMix) { auto col0 = cudf::test::strings_column_wrapper({"null", "null", "", "valid", "", "valid"}, {false, false, true, true, true, true}); auto col1 = cudf::test::strings_column_wrapper({"", "valid", "null", "null", "valid", ""}, {true, true, false, false, true, true}); auto col2 = cudf::test::strings_column_wrapper({"valid", "", "valid", "", "null", "null"}, {true, true, true, true, false, false}); auto exp_results = cudf::test::strings_column_wrapper({"null", "", "valid", "null", "valid", "", "", "null", "valid", "valid", "null", "", "", "valid", "null", "valid", "", "null"}, {false, true, true, false, true, true, true, false, true, true, false, true, true, true, false, true, true, false}); auto results = cudf::interleave_columns(cudf::table_view{{col0, col1, col2}}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, exp_results, verbosity); } TEST_F(InterleaveStringsColumnsTest, MultiColumnStringMixNonNullable) { auto col0 = cudf::test::strings_column_wrapper({"c00", "c01", "", "valid", "", "valid"}); auto col1 = cudf::test::strings_column_wrapper({"", "valid", "c13", "c14", "valid", ""}); auto col2 = cudf::test::strings_column_wrapper({"valid", "", "valid", "", "c24", "c25"}); auto exp_results = cudf::test::strings_column_wrapper({"c00", "", "valid", "c01", "valid", "", "", "c13", "valid", "valid", "c14", "", "", "valid", "c24", "valid", "", "c25"}); auto results = cudf::interleave_columns(cudf::table_view{{col0, col1, col2}}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, exp_results, verbosity); } TEST_F(InterleaveStringsColumnsTest, MultiColumnStringMixNullableMix) { auto col0 = cudf::test::strings_column_wrapper({"c00", "c01", "", "valid", "", "valid"}); auto col1 = cudf::test::strings_column_wrapper({"", "valid", "null", "null", "valid", ""}, {true, true, false, false, true, true}); auto col2 = cudf::test::strings_column_wrapper({"valid", "", "valid", "", "c24", "c25"}); auto exp_results = cudf::test::strings_column_wrapper({"c00", "", "valid", "c01", "valid", "", "", "null", "valid", "valid", "null", "", "", "valid", "c24", "valid", "", "c25"}, {true, true, true, true, true, true, true, false, true, true, false, true, true, true, true, true, true, true}); auto results = cudf::interleave_columns(cudf::table_view{{col0, col1, col2}}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, exp_results, verbosity); } template <typename T> struct FixedPointTestAllReps : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(FixedPointTestAllReps, cudf::test::FixedPointTypes); TYPED_TEST(FixedPointTestAllReps, FixedPointInterleave) { using namespace numeric; using decimalXX = TypeParam; for (int i = 0; i > -4; --i) { auto const ONE = decimalXX{1, scale_type{i}}; auto const TWO = decimalXX{2, scale_type{i}}; auto const FOUR = decimalXX{4, scale_type{i}}; auto const FIVE = decimalXX{5, scale_type{i}}; auto const a = cudf::test::fixed_width_column_wrapper<decimalXX>({ONE, FOUR}); auto const b = cudf::test::fixed_width_column_wrapper<decimalXX>({TWO, FIVE}); auto const input = cudf::table_view{std::vector<cudf::column_view>{a, b}}; auto const expected = cudf::test::fixed_width_column_wrapper<decimalXX>({ONE, TWO, FOUR, FIVE}); auto const actual = cudf::interleave_columns(input); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, actual->view()); } } struct ListsColumnsInterleaveTest : public cudf::test::BaseFixture {}; TEST_F(ListsColumnsInterleaveTest, InvalidInput) { // Input table contains non-list column { auto const col1 = IntCol{}.release(); auto const col2 = IntListsCol{}.release(); EXPECT_THROW(cudf::interleave_columns(TView{{col1->view(), col2->view()}}), cudf::logic_error); } // Types mismatch { auto const col1 = IntListsCol{}.release(); auto const col2 = StrListsCol{}.release(); EXPECT_THROW(cudf::interleave_columns(TView{{col1->view(), col2->view()}}), cudf::logic_error); } } template <typename T> struct ListsColumnsInterleaveTypedTest : public cudf::test::BaseFixture {}; using TypesForTest = cudf::test::Concat<cudf::test::IntegralTypesNotBool, cudf::test::FloatingPointTypes, cudf::test::FixedPointTypes>; TYPED_TEST_SUITE(ListsColumnsInterleaveTypedTest, TypesForTest); TYPED_TEST(ListsColumnsInterleaveTypedTest, InterleaveEmptyColumns) { using ListsCol = cudf::test::lists_column_wrapper<TypeParam>; auto const col = ListsCol{}.release(); auto const results = cudf::interleave_columns(TView{{col->view(), col->view()}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*col, *results, verbosity); } TYPED_TEST(ListsColumnsInterleaveTypedTest, InterleaveOneColumnNotNull) { using ListsCol = cudf::test::lists_column_wrapper<TypeParam>; auto const col = ListsCol{{1, 2}, {3, 4}, {5, 6}}.release(); auto const results = cudf::interleave_columns(TView{{col->view()}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*col, *results, verbosity); } TYPED_TEST(ListsColumnsInterleaveTypedTest, InterleaveOneColumnWithNulls) { using ListsCol = cudf::test::lists_column_wrapper<TypeParam>; auto const col = ListsCol{{ListsCol{{1, 2, null}, null_at(2)}, ListsCol{} /*NULL*/, ListsCol{{null, 3, 4, 4, 4, 4}, null_at(0)}, ListsCol{5, 6}}, null_at(1)} .release(); auto const results = cudf::interleave_columns(TView{{col->view()}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*col, *results, verbosity); } TYPED_TEST(ListsColumnsInterleaveTypedTest, SimpleInputNoNull) { using ListsCol = cudf::test::lists_column_wrapper<TypeParam>; auto const col1 = ListsCol{{1, 2}, {3, 4}, {5, 6}}.release(); auto const col2 = ListsCol{{7, 8}, {9, 10}, {11, 12}}.release(); auto const expected = ListsCol{{1, 2}, {7, 8}, {3, 4}, {9, 10}, {5, 6}, {11, 12}}.release(); auto const results = cudf::interleave_columns(TView{{col1->view(), col2->view()}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *results, verbosity); } TEST_F(ListsColumnsInterleaveTest, SimpleInputStringsColumnsNoNull) { auto const col1 = StrListsCol{ StrListsCol{"Tomato", "Apple"}, StrListsCol{"Banana", "Kiwi", "Cherry"}, StrListsCol{ "Coconut"}}.release(); auto const col2 = StrListsCol{StrListsCol{"Orange"}, StrListsCol{"Lemon", "Peach"}, StrListsCol{}}.release(); auto const expected = StrListsCol{ StrListsCol{"Tomato", "Apple"}, StrListsCol{"Orange"}, StrListsCol{"Banana", "Kiwi", "Cherry"}, StrListsCol{"Lemon", "Peach"}, StrListsCol{"Coconut"}, StrListsCol{}}.release(); auto const results = cudf::interleave_columns(TView{{col1->view(), col2->view()}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *results, verbosity); } TYPED_TEST(ListsColumnsInterleaveTypedTest, SimpleInputWithNulls) { using ListsCol = cudf::test::lists_column_wrapper<TypeParam>; auto const col1 = ListsCol{{ListsCol{{1, null, 3, 4}, null_at(1)}, ListsCol{{null, 2, 3, 4}, null_at(0)}, ListsCol{{null, 2, 3, 4}, null_at(0)}, ListsCol{} /*NULL*/, ListsCol{{1, 2, null, 4}, null_at(2)}, ListsCol{{1, 2, 3, null}, null_at(3)}}, null_at(3)} .release(); auto const col2 = ListsCol{{ListsCol{{10, 11, 12, null}, null_at(3)}, ListsCol{{13, 14, 15, 16, 17, null}, null_at(5)}, ListsCol{} /*NULL*/, ListsCol{{null, 18}, null_at(0)}, ListsCol{{19, 20, null}, null_at(2)}, ListsCol{{null}, null_at(0)}}, null_at(2)} .release(); auto const col3 = ListsCol{{ListsCol{} /*NULL*/, ListsCol{{20, null}, null_at(1)}, ListsCol{{null, 21, null, null}, nulls_at({0, 2, 3})}, ListsCol{}, ListsCol{22, 23, 24, 25}, ListsCol{{null, null, null, null, null}, all_nulls()}}, null_at(0)} .release(); auto const expected = ListsCol{{ListsCol{{1, null, 3, 4}, null_at(1)}, ListsCol{{10, 11, 12, null}, null_at(3)}, ListsCol{} /*NULL*/, ListsCol{{null, 2, 3, 4}, null_at(0)}, ListsCol{{13, 14, 15, 16, 17, null}, null_at(5)}, ListsCol{{20, null}, null_at(1)}, ListsCol{{null, 2, 3, 4}, null_at(0)}, ListsCol{} /*NULL*/, ListsCol{{null, 21, null, null}, nulls_at({0, 2, 3})}, ListsCol{} /*NULL*/, ListsCol{{null, 18}, null_at(0)}, ListsCol{}, ListsCol{{1, 2, null, 4}, null_at(2)}, ListsCol{{19, 20, null}, null_at(2)}, ListsCol{22, 23, 24, 25}, ListsCol{{1, 2, 3, null}, null_at(3)}, ListsCol{{null}, null_at(0)}, ListsCol{{null, null, null, null, null}, all_nulls()}}, nulls_at({2, 7, 9})} .release(); auto const results = cudf::interleave_columns(TView{{col1->view(), col2->view(), col3->view()}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *results, verbosity); } TYPED_TEST(ListsColumnsInterleaveTypedTest, SimpleInputWithNullableChild) { using ListsCol = cudf::test::lists_column_wrapper<TypeParam>; auto const col1 = ListsCol{{1, 2}, {3, 4}}.release(); auto const col2 = ListsCol{{5, 6}, {7, 8}}.release(); auto const col3 = ListsCol{{9, 10}, ListsCol{{null, 12}, null_at(0)}}.release(); auto const expected = ListsCol{{1, 2}, {5, 6}, {9, 10}, {3, 4}, {7, 8}, ListsCol{{null, 12}, null_at(0)}}.release(); auto const results = cudf::interleave_columns(TView{{col1->view(), col2->view(), col3->view()}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *results, verbosity); } TEST_F(ListsColumnsInterleaveTest, SimpleInputStringsColumnsWithNulls) { auto const col1 = StrListsCol{ StrListsCol{{"Tomato", "Bear" /*NULL*/, "Apple"}, null_at(1)}, StrListsCol{{"Banana", "Pig" /*NULL*/, "Kiwi", "Cherry", "Whale" /*NULL*/}, nulls_at({1, 4})}, StrListsCol{ "Coconut"}}.release(); auto const col2 = StrListsCol{ {StrListsCol{{"Orange", "Dog" /*NULL*/, "Fox" /*NULL*/, "Duck" /*NULL*/}, nulls_at({1, 2, 3})}, StrListsCol{"Lemon", "Peach"}, StrListsCol{{"Deer" /*NULL*/, "Snake" /*NULL*/, "Horse" /*NULL*/}, all_nulls()}}, /*NULL*/ null_at(2)} .release(); auto const expected = StrListsCol{ {StrListsCol{{"Tomato", "" /*NULL*/, "Apple"}, null_at(1)}, StrListsCol{{"Orange", "" /*NULL*/, "" /*NULL*/, "" /*NULL*/}, nulls_at({1, 2, 3})}, StrListsCol{{"Banana", "" /*NULL*/, "Kiwi", "Cherry", "" /*NULL*/}, nulls_at({1, 4})}, StrListsCol{"Lemon", "Peach"}, StrListsCol{"Coconut"}, StrListsCol{}}, /*NULL*/ null_at(5)} .release(); auto const results = cudf::interleave_columns(TView{{col1->view(), col2->view()}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *results, verbosity); } TEST_F(ListsColumnsInterleaveTest, SimpleInputStringsColumnsWithNullableChild) { auto const col1 = StrListsCol{ StrListsCol{"Tomato", "Bear", "Apple"}, StrListsCol{"Banana", "Pig", "Kiwi", "Cherry", "Whale"}, StrListsCol{ "Coconut"}}.release(); auto const col2 = StrListsCol{ StrListsCol{{"Orange", "Dog" /*NULL*/, "Fox" /*NULL*/, "Duck" /*NULL*/}, nulls_at({1, 2, 3})}, StrListsCol{"Lemon", "Peach"}, StrListsCol{ {"Deer" /*NULL*/, "Snake" /*NULL*/, "Horse" /*NULL*/}, all_nulls()}}.release(); auto const expected = StrListsCol{ StrListsCol{"Tomato", "Bear", "Apple"}, StrListsCol{{"Orange", "" /*NULL*/, "" /*NULL*/, "" /*NULL*/}, nulls_at({1, 2, 3})}, StrListsCol{"Banana", "Pig", "Kiwi", "Cherry", "Whale"}, StrListsCol{"Lemon", "Peach"}, StrListsCol{"Coconut"}, StrListsCol{ {"Deer" /*NULL*/, "Snake" /*NULL*/, "Horse" /*NULL*/}, all_nulls()}}.release(); auto const results = cudf::interleave_columns(TView{{col1->view(), col2->view()}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *results, verbosity); } TYPED_TEST(ListsColumnsInterleaveTypedTest, SlicedColumnsInputNoNull) { using ListsCol = cudf::test::lists_column_wrapper<TypeParam>; auto const col = ListsCol{{1, 2, 3}, {2, 3}, {3, 4, 5, 6}, {5, 6}, {}, {7}}.release(); auto const col1 = cudf::slice(col->view(), {0, 3})[0]; auto const col2 = cudf::slice(col->view(), {1, 4})[0]; auto const col3 = cudf::slice(col->view(), {2, 5})[0]; auto const col4 = cudf::slice(col->view(), {3, 6})[0]; auto const expected = ListsCol{ ListsCol{1, 2, 3}, ListsCol{2, 3}, ListsCol{3, 4, 5, 6}, ListsCol{5, 6}, ListsCol{2, 3}, ListsCol{3, 4, 5, 6}, ListsCol{5, 6}, ListsCol{}, ListsCol{3, 4, 5, 6}, ListsCol{5, 6}, ListsCol{}, ListsCol{7}}.release(); auto const results = cudf::interleave_columns(TView{{col1, col2, col3, col4}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *results, verbosity); } TYPED_TEST(ListsColumnsInterleaveTypedTest, SlicedColumnsInputWithNulls) { using ListsCol = cudf::test::lists_column_wrapper<TypeParam>; auto const col = ListsCol{{ListsCol{{null, 2, 3}, null_at(0)}, ListsCol{2, 3}, /*NULL*/ ListsCol{{3, null, 5, 6}, null_at(1)}, ListsCol{5, 6}, /*NULL*/ ListsCol{}, /*NULL*/ ListsCol{7}, ListsCol{8, 9, 10}}, nulls_at({1, 3, 4})} .release(); auto const col1 = cudf::slice(col->view(), {0, 3})[0]; auto const col2 = cudf::slice(col->view(), {1, 4})[0]; auto const col3 = cudf::slice(col->view(), {2, 5})[0]; auto const col4 = cudf::slice(col->view(), {3, 6})[0]; auto const col5 = cudf::slice(col->view(), {4, 7})[0]; auto const expected = ListsCol{{ListsCol{{null, 2, 3}, null_at(0)}, ListsCol{}, /*NULL*/ ListsCol{{3, null, 5, 6}, null_at(1)}, ListsCol{}, /*NULL*/ ListsCol{}, /*NULL*/ ListsCol{}, /*NULL*/ ListsCol{{3, null, 5, 6}, null_at(1)}, ListsCol{}, /*NULL*/ ListsCol{}, /*NULL*/ ListsCol{7}, ListsCol{{3, null, 5, 6}, null_at(1)}, ListsCol{}, /*NULL*/ ListsCol{}, /*NULL*/ ListsCol{7}, ListsCol{8, 9, 10}}, nulls_at({1, 3, 4, 5, 7, 8, 11, 12})} .release(); auto const results = cudf::interleave_columns(TView{{col1, col2, col3, col4, col5}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *results, verbosity); } TYPED_TEST(ListsColumnsInterleaveTypedTest, SlicedColumnsInputNullableChild) { using ListsCol = cudf::test::lists_column_wrapper<TypeParam>; auto const col = ListsCol{{1, 2, 3}, ListsCol{{null, 3}, null_at(0)}, {3, 4, 5, 6}, {5, 6}, {}, {7}}.release(); auto const col1 = cudf::slice(col->view(), {0, 3})[0]; auto const col2 = cudf::slice(col->view(), {1, 4})[0]; auto const col3 = cudf::slice(col->view(), {2, 5})[0]; auto const col4 = cudf::slice(col->view(), {3, 6})[0]; auto const expected = ListsCol{ ListsCol{1, 2, 3}, ListsCol{{null, 3}, null_at(0)}, ListsCol{3, 4, 5, 6}, ListsCol{5, 6}, ListsCol{{null, 3}, null_at(0)}, ListsCol{3, 4, 5, 6}, ListsCol{5, 6}, ListsCol{}, ListsCol{3, 4, 5, 6}, ListsCol{5, 6}, ListsCol{}, ListsCol{7}}.release(); auto const results = cudf::interleave_columns(TView{{col1, col2, col3, col4}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *results, verbosity); } TYPED_TEST(ListsColumnsInterleaveTypedTest, InputListsOfListsNoNull) { using ListsCol = cudf::test::lists_column_wrapper<TypeParam>; auto const col1 = ListsCol{ListsCol{ListsCol{1, 2, 3}, ListsCol{4, 5, 6}}, ListsCol{ListsCol{7, 8}, ListsCol{9, 10}}, ListsCol{ListsCol{11, 12, 13}, ListsCol{14, 15}, ListsCol{16, 17}}}; auto const col2 = ListsCol{ListsCol{ListsCol{11, 12, 13}, ListsCol{14, 15, 16}}, ListsCol{ListsCol{17, 18}, ListsCol{19, 110}}, ListsCol{ListsCol{111, 112, 13}, ListsCol{114, 115}, ListsCol{116, 117}}}; auto const expected = ListsCol{ListsCol{ListsCol{1, 2, 3}, ListsCol{4, 5, 6}}, ListsCol{ListsCol{11, 12, 13}, ListsCol{14, 15, 16}}, ListsCol{ListsCol{7, 8}, ListsCol{9, 10}}, ListsCol{ListsCol{17, 18}, ListsCol{19, 110}}, ListsCol{ListsCol{11, 12, 13}, ListsCol{14, 15}, ListsCol{16, 17}}, ListsCol{ListsCol{111, 112, 13}, ListsCol{114, 115}, ListsCol{116, 117}}} .release(); auto const results = cudf::interleave_columns(TView{{col1, col2}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *results, verbosity); } TYPED_TEST(ListsColumnsInterleaveTypedTest, InputListsOfListsWithNulls) { using ListsCol = cudf::test::lists_column_wrapper<TypeParam>; auto const col1 = ListsCol{ ListsCol{ListsCol{{null, 2, 3}, null_at(0)}, ListsCol{{4, null, null}, nulls_at({1, 2})}}, ListsCol{{ListsCol{7, 8}, ListsCol{9, 10}, ListsCol{null, null, null} /*NULL*/}, null_at(2)}, ListsCol{ListsCol{11, 12, 13}, ListsCol{{14, null}, null_at(1)}, ListsCol{16, 17}}}; auto const col2 = ListsCol{ListsCol{{ListsCol{11, 12, 13}, ListsCol{null, null} /*NULL*/}, null_at(1)}, ListsCol{ListsCol{17, 18}, ListsCol{{19, 110, null}, null_at(2)}}, ListsCol{ListsCol{111, 112, 13}, ListsCol{114, 115}, ListsCol{116, 117}}}; auto const expected = ListsCol{ ListsCol{ListsCol{{null, 2, 3}, null_at(0)}, ListsCol{{4, null, null}, nulls_at({1, 2})}}, ListsCol{{ListsCol{11, 12, 13}, ListsCol{null, null} /*NULL*/}, null_at(1)}, ListsCol{{ListsCol{7, 8}, ListsCol{9, 10}, ListsCol{null, null, null} /*NULL*/}, null_at(2)}, ListsCol{ListsCol{17, 18}, ListsCol{{19, 110, null}, null_at(2)}}, ListsCol{ListsCol{11, 12, 13}, ListsCol{{14, null}, null_at(1)}, ListsCol{16, 17}}, ListsCol{ ListsCol{111, 112, 13}, ListsCol{114, 115}, ListsCol{116, 117}}}.release(); auto const results = cudf::interleave_columns(TView{{col1, col2}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *results, verbosity); } TYPED_TEST(ListsColumnsInterleaveTypedTest, SlicedInputListsOfListsNoNull) { using ListsCol = cudf::test::lists_column_wrapper<TypeParam>; auto const col1_original = ListsCol{ ListsCol{ListsCol{11, 11, 11}, ListsCol{22}, ListsCol{33, 33, 33}}, // don't care ListsCol{ListsCol{11, 11, 11}, ListsCol{22}, ListsCol{33, 33, 33}}, // don't care // ListsCol{ListsCol{1, 2, 3}, ListsCol{4, 5, 6}}, ListsCol{ListsCol{7, 8}, ListsCol{9, 10}}, ListsCol{ListsCol{11, 12, 13}, ListsCol{14, 15}, ListsCol{16, 17}}, // ListsCol{ListsCol{11, 11, 11}, ListsCol{22}, ListsCol{33, 33, 33}}, // don't care ListsCol{ListsCol{11, 11, 11}, ListsCol{22}, ListsCol{33, 33, 33}} // don't care }; auto const col2_original = ListsCol{ ListsCol{ListsCol{11, 12, 13}, ListsCol{14, 15, 16}}, ListsCol{ListsCol{17, 18}, ListsCol{19, 110}}, ListsCol{ListsCol{111, 112, 13}, ListsCol{114, 115}, ListsCol{116, 117}}, // ListsCol{ListsCol{11, 11, 11}, ListsCol{22}, ListsCol{33, 33, 33}} // don't care }; auto const col1 = cudf::slice(col1_original, {2, 5})[0]; auto const col2 = cudf::slice(col2_original, {0, 3})[0]; auto const expected = ListsCol{ListsCol{ListsCol{1, 2, 3}, ListsCol{4, 5, 6}}, ListsCol{ListsCol{11, 12, 13}, ListsCol{14, 15, 16}}, ListsCol{ListsCol{7, 8}, ListsCol{9, 10}}, ListsCol{ListsCol{17, 18}, ListsCol{19, 110}}, ListsCol{ListsCol{11, 12, 13}, ListsCol{14, 15}, ListsCol{16, 17}}, ListsCol{ListsCol{111, 112, 13}, ListsCol{114, 115}, ListsCol{116, 117}}} .release(); auto const results = cudf::interleave_columns(TView{{col1, col2}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *results, verbosity); } TYPED_TEST(ListsColumnsInterleaveTypedTest, SlicedInputListsOfListsWithNulls) { using ListsCol = cudf::test::lists_column_wrapper<TypeParam>; auto const col1_original = ListsCol{ { ListsCol{ListsCol{{null, 11}, null_at(0)}, ListsCol{{22, null, null}, nulls_at({1, 2})}}, // don't care ListsCol{ListsCol{{null, 11}, null_at(0)}, ListsCol{{22, null, null}, nulls_at({1, 2})}}, // don't care ListsCol{ListsCol{{null, 11}, null_at(0)}, ListsCol{{22, null, null}, nulls_at({1, 2})}}, // don't care // ListsCol{ListsCol{{null, 2, 3}, null_at(0)}, ListsCol{{4, null, null}, nulls_at({1, 2})}}, ListsCol{{ListsCol{7, 8}, ListsCol{9, 10}, ListsCol{null, null, null} /*NULL*/}, null_at(2)}, ListsCol{ListsCol{11, 12, 13}, ListsCol{{14, null}, null_at(1)}, ListsCol{16, 17}}, // ListsCol{ListsCol{{null, 11}, null_at(0)}, ListsCol{{22, null, null}, nulls_at({1, 2})}} // don't care }, nulls_at({0, 2, 3})}; auto const col2_original = ListsCol{ ListsCol{ListsCol{{null, 11}, null_at(0)}, ListsCol{{22, null, null}, nulls_at({1, 2})}}, // don't care ListsCol{ListsCol{{null, 11}, null_at(0)}, ListsCol{{22, null, null}, nulls_at({1, 2})}}, // don't care // ListsCol{{ListsCol{11, 12, 13}, ListsCol{null, null} /*NULL*/}, null_at(1)}, ListsCol{ListsCol{17, 18}, ListsCol{{19, 110, null}, null_at(2)}}, ListsCol{ListsCol{111, 112, 13}, ListsCol{114, 115}, ListsCol{116, 117}}, ListsCol{ListsCol{{null, 11}, null_at(0)}, // ListsCol{{22, null, null}, nulls_at({1, 2})}}, // don't care ListsCol{ListsCol{{null, 11}, null_at(0)}, ListsCol{{22, null, null}, nulls_at({1, 2})}}, // don't care ListsCol{ListsCol{{null, 11}, null_at(0)}, ListsCol{{22, null, null}, nulls_at({1, 2})}} // don't care }; auto const col1 = cudf::slice(col1_original, {3, 6})[0]; auto const col2 = cudf::slice(col2_original, {2, 5})[0]; auto const expected = ListsCol{ {ListsCol{ListsCol{{null, 2, 3}, null_at(0)}, ListsCol{{4, null, null}, nulls_at({1, 2})}}, ListsCol{{ListsCol{11, 12, 13}, ListsCol{null, null} /*NULL*/}, null_at(1)}, ListsCol{{ListsCol{7, 8}, ListsCol{9, 10}, ListsCol{null, null, null} /*NULL*/}, null_at(2)}, ListsCol{ListsCol{17, 18}, ListsCol{{19, 110, null}, null_at(2)}}, ListsCol{ListsCol{11, 12, 13}, ListsCol{{14, null}, null_at(1)}, ListsCol{16, 17}}, ListsCol{ListsCol{111, 112, 13}, ListsCol{114, 115}, ListsCol{116, 117}}}, null_at(0)} .release(); auto const results = cudf::interleave_columns(TView{{col1, col2}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *results, verbosity); } TYPED_TEST(ListsColumnsInterleaveTypedTest, InputListsOfStructsNoNull) { using ColWrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto structs1 = [] { auto child1 = ColWrapper{1, 2, 3, 4, 5}; auto child2 = ColWrapper{6, 7, 8, 9, 10}; auto child3 = StringsCol{"Banana", "Mango", "Apple", "Cherry", "Kiwi"}; return StructsCol{{child1, child2, child3}}; }(); auto structs2 = [] { auto child1 = ColWrapper{11, 12, 13, 14, 15}; auto child2 = ColWrapper{16, 17, 18, 19, 110}; auto child3 = StringsCol{"Bear", "Duck", "Cat", "Dog", "Panda"}; return StructsCol{{child1, child2, child3}}; }(); auto structs_expected = [] { auto child1 = ColWrapper{1, 11, 12, 13, 2, 3, 14, 4, 5, 15}; auto child2 = ColWrapper{6, 16, 17, 18, 7, 8, 19, 9, 10, 110}; auto child3 = StringsCol{ "Banana", "Bear", "Duck", "Cat", "Mango", "Apple", "Dog", "Cherry", "Kiwi", "Panda"}; return StructsCol{{child1, child2, child3}}; }(); auto const col1 = cudf::make_lists_column(3, IntCol{0, 1, 3, 5}.release(), structs1.release(), 0, {}); auto const col2 = cudf::make_lists_column(3, IntCol{0, 3, 4, 5}.release(), structs2.release(), 0, {}); auto const expected = cudf::make_lists_column( 6, IntCol{0, 1, 4, 6, 7, 9, 10}.release(), structs_expected.release(), 0, {}); auto const results = cudf::interleave_columns(TView{{col1->view(), col2->view()}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *results, verbosity); } TYPED_TEST(ListsColumnsInterleaveTypedTest, InputListsOfStructsWithNulls) { using ColWrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto structs1 = [] { auto child1 = ColWrapper{{1, 2, null, 4, 5}, null_at(2)}; auto child2 = ColWrapper{{6, 7, 8, 9, null}, null_at(4)}; auto child3 = StringsCol{"Banana", "Mango", "Apple", "Cherry", "Kiwi"}; return StructsCol{{child1, child2, child3}, null_at(0)}; }(); auto structs2 = [] { auto child1 = ColWrapper{11, 12, 13, 14, 15}; auto child2 = ColWrapper{{null, 17, 18, 19, 110}, null_at(0)}; auto child3 = StringsCol{{"" /*NULL*/, "Duck", "Cat", "Dog", "" /*NULL*/}, nulls_at({0, 4})}; return StructsCol{{child1, child2, child3}}; }(); auto structs_expected = [] { auto child1 = ColWrapper{{1, 11, 12, 13, 2, null, 14, 4, 5, 15}, null_at(5)}; auto child2 = ColWrapper{{6, null, 17, 18, 7, 8, 19, 9, null, 110}, nulls_at({1, 8})}; auto child3 = StringsCol{{"Banana", "" /*NULL*/, "Duck", "Cat", "Mango", "Apple", "Dog", "Cherry", "Kiwi", "" /*NULL*/}, nulls_at({1, 9})}; return StructsCol{{child1, child2, child3}, null_at(0)}; }(); auto const col1 = cudf::make_lists_column(3, IntCol{0, 1, 3, 5}.release(), structs1.release(), 0, {}); auto const col2 = cudf::make_lists_column(3, IntCol{0, 3, 4, 5}.release(), structs2.release(), 0, {}); auto const expected = cudf::make_lists_column( 6, IntCol{0, 1, 4, 6, 7, 9, 10}.release(), structs_expected.release(), 0, {}); auto const results = cudf::interleave_columns(TView{{col1->view(), col2->view()}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *results, verbosity); } TYPED_TEST(ListsColumnsInterleaveTypedTest, SlicedInputListsOfStructsNoNull) { using ColWrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto structs1 = [] { auto child1 = ColWrapper{NOT_USE, NOT_USE, 1, 2, 3, 4, 5, NOT_USE}; auto child2 = ColWrapper{NOT_USE, NOT_USE, 6, 7, 8, 9, 10, NOT_USE}; auto child3 = StringsCol{"NOT_USE", "NOT_USE", "Banana", "Mango", "Apple", "Cherry", "Kiwi", "NOT_USE"}; return StructsCol{{child1, child2, child3}}; }(); auto structs2 = [] { auto child1 = ColWrapper{11, 12, 13, 14, 15, NOT_USE, NOT_USE}; auto child2 = ColWrapper{16, 17, 18, 19, 110, NOT_USE, NOT_USE}; auto child3 = StringsCol{"Bear", "Duck", "Cat", "Dog", "Panda", "NOT_USE", "NOT_USE"}; return StructsCol{{child1, child2, child3}}; }(); auto structs_expected = [] { auto child1 = ColWrapper{1, 11, 12, 13, 2, 3, 14, 4, 5, 15}; auto child2 = ColWrapper{6, 16, 17, 18, 7, 8, 19, 9, 10, 110}; auto child3 = StringsCol{ "Banana", "Bear", "Duck", "Cat", "Mango", "Apple", "Dog", "Cherry", "Kiwi", "Panda"}; return StructsCol{{child1, child2, child3}}; }(); auto const col1_original = cudf::make_lists_column(5, IntCol{0, 2, 3, 5, 7, 8}.release(), structs1.release(), 0, {}); auto const col2_original = cudf::make_lists_column(4, IntCol{0, 3, 4, 5, 7}.release(), structs2.release(), 0, {}); auto const expected = cudf::make_lists_column( 6, IntCol{0, 1, 4, 6, 7, 9, 10}.release(), structs_expected.release(), 0, {}); auto const col1 = cudf::slice(col1_original->view(), {1, 4})[0]; auto const col2 = cudf::slice(col2_original->view(), {0, 3})[0]; auto const results = cudf::interleave_columns(TView{{col1, col2}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *results, verbosity); } TYPED_TEST(ListsColumnsInterleaveTypedTest, SlicedInputListsOfStructsWithNulls) { using ColWrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto structs1 = [] { auto child1 = ColWrapper{{NOT_USE, 1, 2, null, 4, 5, NOT_USE}, nulls_at({0, 3})}; auto child2 = ColWrapper{{NOT_USE, 6, 7, 8, 9, null, NOT_USE}, null_at(5)}; auto child3 = StringsCol{"NOT_USE", "Banana", "Mango", "Apple", "Cherry", "Kiwi", "NOT_USE"}; return StructsCol{{child1, child2, child3}, nulls_at({1, 6})}; }(); auto structs2 = [] { auto child1 = ColWrapper{{NOT_USE, 11, 12, 13, 14, 15}, null_at(0)}; auto child2 = ColWrapper{{NOT_USE, null, 17, 18, 19, 110}, null_at(1)}; auto child3 = StringsCol{{"NOT_USE", "" /*NULL*/, "Duck", "Cat", "Dog", "" /*NULL*/}, nulls_at({0, 1, 5})}; return StructsCol{{child1, child2, child3}}; }(); auto structs_expected = [] { auto child1 = ColWrapper{{1, 11, 12, 13, 2, null, 14, 4, 5, 15}, null_at(5)}; auto child2 = ColWrapper{{6, null, 17, 18, 7, 8, 19, 9, null, 110}, nulls_at({1, 8})}; auto child3 = StringsCol{{"Banana", "" /*NULL*/, "Duck", "Cat", "Mango", "Apple", "Dog", "Cherry", "Kiwi", "" /*NULL*/}, nulls_at({1, 9})}; return StructsCol{{child1, child2, child3}, null_at(0)}; }(); auto const col1_original = cudf::make_lists_column(5, IntCol{0, 1, 2, 4, 6, 7}.release(), structs1.release(), 0, {}); auto const col2_original = cudf::make_lists_column(4, IntCol{0, 1, 4, 5, 6}.release(), structs2.release(), 0, {}); auto const col1 = cudf::slice(col1_original->view(), {1, 4})[0]; auto const col2 = cudf::slice(col2_original->view(), {1, 4})[0]; auto const expected = cudf::make_lists_column( 6, IntCol{0, 1, 4, 6, 7, 9, 10}.release(), structs_expected.release(), 0, {}); auto const results = cudf::interleave_columns(TView{{col1, col2}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *results, verbosity); } TEST_F(ListsColumnsInterleaveTest, SlicedStringsColumnsInputWithNulls) { auto const col = StrListsCol{ {StrListsCol{{"Tomato", "Bear" /*NULL*/, "Apple"}, null_at(1)}, StrListsCol{{"Banana", "Pig" /*NULL*/, "Kiwi", "Cherry", "Whale" /*NULL*/}, nulls_at({1, 4})}, StrListsCol{"Coconut"}, StrListsCol{{"Orange", "Dog" /*NULL*/, "Fox" /*NULL*/, "Duck" /*NULL*/}, nulls_at({1, 2, 3})}, StrListsCol{"Lemon", "Peach"}, StrListsCol{{"Deer" /*NULL*/, "Snake" /*NULL*/, "Horse" /*NULL*/}, all_nulls()}}, /*NULL*/ null_at(5)} .release(); auto const col1 = cudf::slice(col->view(), {0, 3})[0]; auto const col2 = cudf::slice(col->view(), {1, 4})[0]; auto const col3 = cudf::slice(col->view(), {2, 5})[0]; auto const col4 = cudf::slice(col->view(), {3, 6})[0]; auto const expected = StrListsCol{ {StrListsCol{{"Tomato", "" /*NULL*/, "Apple"}, null_at(1)}, StrListsCol{{"Banana", "" /*NULL*/, "Kiwi", "Cherry", "" /*NULL*/}, nulls_at({1, 4})}, StrListsCol{"Coconut"}, StrListsCol{{"Orange", "" /*NULL*/, "" /*NULL*/, "" /*NULL*/}, nulls_at({1, 2, 3})}, StrListsCol{{"Banana", "" /*NULL*/, "Kiwi", "Cherry", "" /*NULL*/}, nulls_at({1, 4})}, StrListsCol{"Coconut"}, StrListsCol{{"Orange", "" /*NULL*/, "" /*NULL*/, "" /*NULL*/}, nulls_at({1, 2, 3})}, StrListsCol{"Lemon", "Peach"}, StrListsCol{"Coconut"}, StrListsCol{{"Orange", "" /*NULL*/, "" /*NULL*/, "" /*NULL*/}, nulls_at({1, 2, 3})}, StrListsCol{"Lemon", "Peach"}, StrListsCol{}}, /*NULL*/ null_at(11)} .release(); auto const results = cudf::interleave_columns(TView{{col1, col2, col3, col4}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected, *results, verbosity); } struct StructsColumnsInterleaveTest : public cudf::test::BaseFixture {}; TEST_F(StructsColumnsInterleaveTest, InvalidInput) { // Input table contains non-structs column { auto const col1 = IntCol{}; auto const col2 = StructsCol{}; EXPECT_THROW(cudf::interleave_columns(TView{{col1, col2}}), cudf::logic_error); } // Types mismatch { auto const structs1 = [] { auto child1 = IntCol{1, 2, 3}; auto child2 = IntCol{4, 5, 6}; return StructsCol{{child1, child2}}; }(); auto const structs2 = [] { auto child1 = IntCol{7, 8, 9}; auto child2 = StringsCol{"", "abc", "123"}; return StructsCol{{child1, child2}}; }(); EXPECT_THROW(cudf::interleave_columns(TView{{structs1, structs2}}), cudf::logic_error); } // Numbers of children mismatch { auto const structs1 = [] { auto child1 = IntCol{1, 2, 3}; auto child2 = IntCol{4, 5, 6}; return StructsCol{{child1, child2}}; }(); auto const structs2 = [] { auto child1 = IntCol{7, 8, 9}; auto child2 = IntCol{10, 11, 12}; auto child3 = IntCol{13, 14, 15}; return StructsCol{{child1, child2, child3}}; }(); EXPECT_THROW(cudf::interleave_columns(TView{{structs1, structs2}}), cudf::logic_error); } } TEST_F(StructsColumnsInterleaveTest, InterleaveEmptyColumns) { auto const structs = StructsCol{}; auto const results = cudf::interleave_columns(TView{{structs, structs}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(structs, *results, verbosity); } template <typename T> struct StructsColumnsInterleaveTypedTest : public cudf::test::BaseFixture {}; using TypesForTest = cudf::test::Concat<cudf::test::IntegralTypesNotBool, cudf::test::FloatingPointTypes, cudf::test::FixedPointTypes>; TYPED_TEST_SUITE(StructsColumnsInterleaveTypedTest, TypesForTest); TYPED_TEST(StructsColumnsInterleaveTypedTest, InterleaveOneColumnNotNull) { using ColWrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto const structs = [] { auto child1 = ColWrapper{1, 2, 3}; auto child2 = ColWrapper{4, 5, 6}; auto child3 = StringsCol{"Banana", "Mango", "Apple"}; return StructsCol{{child1, child2, child3}}; }(); auto const results = cudf::interleave_columns(TView{{structs}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(structs, *results, verbosity); } TYPED_TEST(StructsColumnsInterleaveTypedTest, InterleaveOneColumnWithNulls) { using ColWrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto const structs = [] { auto child1 = ColWrapper{{1, 2, null, 3}, null_at(2)}; auto child2 = ColWrapper{{4, null, 5, 6}, null_at(1)}; auto child3 = StringsCol{{"" /*NULL*/, "Banana", "Mango", "Apple"}, null_at(0)}; return StructsCol{{child1, child2, child3}, null_at(3)}; }(); auto const results = cudf::interleave_columns(TView{{structs}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(structs, *results, verbosity); } TYPED_TEST(StructsColumnsInterleaveTypedTest, SimpleInputNoNull) { using ColWrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto const structs1 = [] { auto child1 = ColWrapper{1, 2, 3}; auto child2 = ColWrapper{4, 5, 6}; auto child3 = StringsCol{"Banana", "Mango", "Apple"}; return StructsCol{{child1, child2, child3}}; }(); auto const structs2 = [] { auto child1 = ColWrapper{7, 8, 9}; auto child2 = ColWrapper{10, 11, 12}; auto child3 = StringsCol{"Bear", "Duck", "Cat"}; return StructsCol{{child1, child2, child3}}; }(); auto const expected = [] { auto child1 = ColWrapper{1, 7, 2, 8, 3, 9}; auto child2 = ColWrapper{4, 10, 5, 11, 6, 12}; auto child3 = StringsCol{"Banana", "Bear", "Mango", "Duck", "Apple", "Cat"}; return StructsCol{{child1, child2, child3}}; }(); auto const results = cudf::interleave_columns(TView{{structs1, structs2}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *results, verbosity); } TYPED_TEST(StructsColumnsInterleaveTypedTest, SimpleInputWithNulls) { using ColWrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto const structs1 = [] { auto child1 = ColWrapper{{1, 2, null, 3, 4}, null_at(2)}; auto child2 = ColWrapper{{4, null, 5, 6, 7}, null_at(1)}; auto child3 = StringsCol{{"" /*NULL*/, "Banana", "Mango", "Apple", "Cherry"}, null_at(0)}; return StructsCol{{child1, child2, child3}, null_at(0)}; }(); auto const structs2 = [] { auto child1 = ColWrapper{{7, null, null, 8, 9}, nulls_at({1, 2})}; auto child2 = ColWrapper{{10, 11, 12, null, 14}, null_at(3)}; auto child3 = StringsCol{"Bear", "Duck", "Cat", "Dog", "Panda"}; return StructsCol{{child1, child2, child3}, null_at(4)}; }(); auto const structs3 = [] { auto child1 = ColWrapper{{-1, -2, -3, 0, null}, null_at(4)}; auto child2 = ColWrapper{{-5, 0, null, -1, -10}, null_at(2)}; auto child3 = StringsCol{"111", "Bànànà", "abcxyz", "é á í", "zzz"}; return StructsCol{{child1, child2, child3}, null_at(1)}; }(); auto const expected = [] { auto child1 = ColWrapper{{1, 7, -1, 2, null, -2, null, null, -3, 3, 8, 0, 4, 9, null}, nulls_at({4, 6, 7, 14})}; auto child2 = ColWrapper{{4, 10, -5, null, 11, 0, 5, 12, null, 6, null, -1, 7, 14, -10}, nulls_at({3, 8, 10})}; auto child3 = StringsCol{{"" /*NULL*/, "Bear", "111", "Banana", "Duck", "Bànànà", "Mango", "Cat", "abcxyz", "Apple", "Dog", "é á í", "Cherry", "Panda", "zzz"}, null_at(0)}; return StructsCol{{child1, child2, child3}, nulls_at({0, 5, 13})}; }(); auto const results = cudf::interleave_columns(TView{{structs1, structs2, structs3}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *results, verbosity); } TYPED_TEST(StructsColumnsInterleaveTypedTest, NestedInputStructsColumns) { using ColWrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto const structs1 = [] { auto child_structs1 = [] { auto child1 = ColWrapper{{null, 2, 3, 4, 5}, null_at(0)}; auto child2 = ColWrapper{{6, 7, 8, null, 10}, null_at(3)}; return StructsCol{{child1, child2}, null_at(0)}; }(); auto child_structs2 = [] { auto child1 = ColWrapper{{11, null, 13, 14, 15}, null_at(1)}; auto child2 = ColWrapper{{null, 17, 18, 19, 20}, null_at(0)}; return StructsCol{{child1, child2}, nulls_at({0, 1})}; }(); auto child_strings = [] { return StringsCol{"Banana", "Mango", "Apple", "Cherry", "Kiwi"}; }(); return StructsCol{{child_structs1, child_structs2, child_strings}, null_at(0)}; }(); auto const structs2 = [] { auto child_structs1 = [] { auto child1 = ColWrapper{{-1, null, -3, -4, -5}, null_at(1)}; auto child2 = ColWrapper{{-6, -7, -8, null, -10}, null_at(3)}; return StructsCol{{child1, child2}}; }(); auto child_structs2 = [] { auto child1 = ColWrapper{{-11, -12, null, -14, -15}, null_at(2)}; auto child2 = ColWrapper{{-16, -17, -18, -19, null}, null_at(4)}; return StructsCol{{child1, child2}, null_at(2)}; }(); auto child_strings = [] { return StringsCol{"Bear", "Duck", "Cat", "Dog", "Rabbit"}; }(); return StructsCol{{child_structs1, child_structs2, child_strings}, null_at(2)}; }(); auto const expected = [] { auto child_structs1 = [] { auto child1 = ColWrapper{{null, -1, 2, null, 3, -3, 4, -4, 5, -5}, nulls_at({0, 3})}; auto child2 = ColWrapper{{6, -6, 7, -7, 8, -8, null, null, 10, -10}, nulls_at({6, 7})}; return StructsCol{{child1, child2}, null_at(0)}; }(); auto child_structs2 = [] { auto child1 = ColWrapper{{11, -11, null, -12, 13, null, 14, -14, 15, -15}, nulls_at({2, 5})}; auto child2 = ColWrapper{{null, -16, 17, -17, 18, -18, 19, -19, 20, null}, nulls_at({0, 9})}; return StructsCol{{child1, child2}, nulls_at({0, 2, 5})}; }(); auto child_strings = [] { return StringsCol{ "Banana", "Bear", "Mango", "Duck", "Apple", "Cat", "Cherry", "Dog", "Kiwi", "Rabbit"}; }(); return StructsCol{{child_structs1, child_structs2, child_strings}, nulls_at({0, 5})}; }(); auto const results = cudf::interleave_columns(TView{{structs1, structs2}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *results, verbosity); } TYPED_TEST(StructsColumnsInterleaveTypedTest, SlicedColumnsInputNoNull) { using ColWrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; auto const structs1_original = [] { auto child1 = ColWrapper{NOT_USE, NOT_USE, 1, 2, 3, NOT_USE}; auto child2 = ColWrapper{NOT_USE, NOT_USE, 4, 5, 6, NOT_USE}; auto child3 = StringsCol{"NOT_USE", "NOT_USE", "Banana", "Mango", "Apple", "NOT_USE"}; return StructsCol{{child1, child2, child3}}; }(); // structs2 has more rows than structs1 auto const structs2_original = [] { auto child1 = ColWrapper{NOT_USE, 7, 8, 9, NOT_USE, NOT_USE, NOT_USE}; auto child2 = ColWrapper{NOT_USE, 10, 11, 12, NOT_USE, NOT_USE, NOT_USE}; auto child3 = StringsCol{"NOT_USE", "Bear", "Duck", "Cat", "NOT_USE", "NOT_USE", "NOT_USE"}; return StructsCol{{child1, child2, child3}}; }(); auto const expected = [] { auto child1 = ColWrapper{1, 7, 2, 8, 3, 9}; auto child2 = ColWrapper{4, 10, 5, 11, 6, 12}; auto child3 = StringsCol{"Banana", "Bear", "Mango", "Duck", "Apple", "Cat"}; return StructsCol{{child1, child2, child3}}; }(); auto const structs1 = cudf::slice(structs1_original, {2, 5})[0]; auto const structs2 = cudf::slice(structs2_original, {1, 4})[0]; auto const results = cudf::interleave_columns(TView{{structs1, structs2}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *results, verbosity); } TYPED_TEST(StructsColumnsInterleaveTypedTest, SlicedColumnsInputWithNulls) { using ColWrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; constexpr int32_t NOT_USE{-1}; // mark for elements that we don't care auto const structs1_original = [] { auto child1 = ColWrapper{{NOT_USE, NOT_USE, 1, 2, null, 3, 4, NOT_USE}, null_at(4)}; auto child2 = ColWrapper{{NOT_USE, NOT_USE, 4, null, 5, 6, 7, NOT_USE}, null_at(3)}; auto child3 = StringsCol{ {"NOT_USE", "NOT_USE", "" /*NULL*/, "Banana", "Mango", "Apple", "Cherry", "NOT_USE"}, null_at(2)}; return StructsCol{{child1, child2, child3}, null_at(2)}; }(); auto const structs2_original = [] { auto child1 = ColWrapper{{7, null, null, 8, 9, NOT_USE, NOT_USE}, nulls_at({1, 2})}; auto child2 = ColWrapper{{10, 11, 12, null, 14, NOT_USE, NOT_USE}, null_at(3)}; auto child3 = StringsCol{"Bear", "Duck", "Cat", "Dog", "Panda", "NOT_USE", "NOT_USE"}; return StructsCol{{child1, child2, child3}, null_at(4)}; }(); auto const structs3_original = [] { auto child1 = ColWrapper{{NOT_USE, NOT_USE, NOT_USE, -1, -2, -3, 0, null}, null_at(7)}; auto child2 = ColWrapper{{NOT_USE, NOT_USE, NOT_USE, -5, 0, null, -1, -10}, null_at(5)}; auto child3 = StringsCol{"NOT_USE", "NOT_USE", "NOT_USE", "111", "Bànànà", "abcxyz", "é á í", "zzz"}; return StructsCol{{child1, child2, child3}, null_at(4)}; }(); auto const expected = [] { auto child1 = ColWrapper{{1, 7, -1, 2, null, -2, null, null, -3, 3, 8, 0, 4, 9, null}, nulls_at({4, 6, 7, 14})}; auto child2 = ColWrapper{{4, 10, -5, null, 11, 0, 5, 12, null, 6, null, -1, 7, 14, -10}, nulls_at({3, 8, 10})}; auto child3 = StringsCol{{"" /*NULL*/, "Bear", "111", "Banana", "Duck", "Bànànà", "Mango", "Cat", "abcxyz", "Apple", "Dog", "é á í", "Cherry", "Panda", "zzz"}, null_at(0)}; return StructsCol{{child1, child2, child3}, nulls_at({0, 5, 13})}; }(); auto const structs1 = cudf::slice(structs1_original, {2, 7})[0]; auto const structs2 = cudf::slice(structs2_original, {0, 5})[0]; auto const structs3 = cudf::slice(structs3_original, {3, 8})[0]; auto const results = cudf::interleave_columns(TView{{structs1, structs2, structs3}}); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected, *results, verbosity); } CUDF_TEST_PROGRAM_MAIN()
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/reshape/byte_cast_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/reshape.hpp> class ByteCastTest : public cudf::test::BaseFixture {}; TEST_F(ByteCastTest, int16ValuesWithSplit) { using limits = std::numeric_limits<int16_t>; cudf::test::fixed_width_column_wrapper<int16_t> const int16_col( {short(0), short(100), short(-100), limits::min(), limits::max()}); cudf::test::lists_column_wrapper<uint8_t> const int16_expected( {{0x00, 0x00}, {0x64, 0x00}, {0x9c, 0xff}, {0x00, 0x80}, {0xff, 0x7f}}); cudf::test::lists_column_wrapper<uint8_t> const int16_expected_slice1( {{0x00, 0x00}, {0x00, 0x64}, {0xff, 0x9c}}); cudf::test::lists_column_wrapper<uint8_t> const int16_expected_slice2( {{0x80, 0x00}, {0x7f, 0xff}}); std::vector<cudf::size_type> splits({3}); std::vector<cudf::column_view> split_column = cudf::split(int16_col, splits); auto const output_int16 = cudf::byte_cast(int16_col, cudf::flip_endianness::NO); auto const output_int16_slice1 = cudf::byte_cast(split_column.at(0), cudf::flip_endianness::YES); auto const output_int16_slice2 = cudf::byte_cast(split_column.at(1), cudf::flip_endianness::YES); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output_int16->view(), int16_expected); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output_int16_slice1->view(), int16_expected_slice1); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output_int16_slice2->view(), int16_expected_slice2); } TEST_F(ByteCastTest, int16ValuesWithNulls) { using limits = std::numeric_limits<int16_t>; auto odd_validity = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2; }); cudf::test::fixed_width_column_wrapper<int16_t> const int16_col( {short(0), short(100), short(-100), limits::min(), limits::max()}, {0, 1, 0, 1, 0}); auto int16_data = cudf::test::fixed_width_column_wrapper<uint8_t>{0x00, 0x64, 0x80, 0x00}; auto [null_mask, null_count] = cudf::test::detail::make_null_mask(odd_validity, odd_validity + 5); auto int16_expected = cudf::make_lists_column( 5, std::move(cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 0, 2, 2, 4, 4}.release()), std::move(int16_data.release()), null_count, std::move(null_mask)); auto const output_int16 = cudf::byte_cast(int16_col, cudf::flip_endianness::YES); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(output_int16->view(), int16_expected->view()); } TEST_F(ByteCastTest, int32Values) { using limits = std::numeric_limits<int32_t>; cudf::test::fixed_width_column_wrapper<int32_t> const int32_col( {0, 100, -100, limits::min(), limits::max()}); cudf::test::lists_column_wrapper<uint8_t> const int32_expected_flipped( {{0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x64}, {0xff, 0xff, 0xff, 0x9c}, {0x80, 0x00, 0x00, 0x00}, {0x7f, 0xff, 0xff, 0xff}}); cudf::test::lists_column_wrapper<uint8_t> const int32_expected({{0x00, 0x00, 0x00, 0x00}, {0x64, 0x00, 0x00, 0x00}, {0x9c, 0xff, 0xff, 0xff}, {0x00, 0x00, 0x00, 0x80}, {0xff, 0xff, 0xff, 0x7f}}); auto const output_int32_flipped = cudf::byte_cast(int32_col, cudf::flip_endianness::YES); auto const output_int32 = cudf::byte_cast(int32_col, cudf::flip_endianness::NO); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output_int32_flipped->view(), int32_expected_flipped); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output_int32->view(), int32_expected); } TEST_F(ByteCastTest, int32ValuesWithNulls) { using limits = std::numeric_limits<int32_t>; auto even_validity = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return (i + 1) % 2; }); cudf::test::fixed_width_column_wrapper<int32_t> const int32_col( {0, 100, -100, limits::min(), limits::max()}, {1, 0, 1, 0, 1}); auto int32_data = cudf::test::fixed_width_column_wrapper<uint8_t>{ 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x9c, 0x7f, 0xff, 0xff, 0xff}; auto [null_mask, null_count] = cudf::test::detail::make_null_mask(even_validity, even_validity + 5); auto int32_expected = cudf::make_lists_column( 5, std::move(cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 4, 4, 8, 8, 12}.release()), std::move(int32_data.release()), null_count, std::move(null_mask)); auto const output_int32 = cudf::byte_cast(int32_col, cudf::flip_endianness::YES); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(output_int32->view(), int32_expected->view()); } TEST_F(ByteCastTest, int64ValuesWithSplit) { using limits = std::numeric_limits<int64_t>; cudf::test::fixed_width_column_wrapper<int64_t> const int64_col( {long(0), long(100), long(-100), limits::min(), limits::max()}); cudf::test::lists_column_wrapper<uint8_t> const int64_expected_flipped( {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x9c}, {0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}); cudf::test::lists_column_wrapper<uint8_t> const int64_expected_slice1( {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x9c, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}); cudf::test::lists_column_wrapper<uint8_t> const int64_expected_slice2( {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f}}); std::vector<cudf::size_type> splits({3}); std::vector<cudf::column_view> split_column = cudf::split(int64_col, splits); auto const output_int64_flipped = cudf::byte_cast(int64_col, cudf::flip_endianness::YES); auto const output_int64_slice1 = cudf::byte_cast(split_column.at(0), cudf::flip_endianness::NO); auto const output_int64_slice2 = cudf::byte_cast(split_column.at(1), cudf::flip_endianness::NO); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output_int64_flipped->view(), int64_expected_flipped); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output_int64_slice1->view(), int64_expected_slice1); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output_int64_slice2->view(), int64_expected_slice2); } TEST_F(ByteCastTest, int64ValuesWithNulls) { using limits = std::numeric_limits<int64_t>; auto odd_validity = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2; }); cudf::test::fixed_width_column_wrapper<int64_t> const int64_col( {long(0), long(100), long(-100), limits::min(), limits::max()}, {0, 1, 0, 1, 0}); auto int64_data = cudf::test::fixed_width_column_wrapper<uint8_t>{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; auto [null_mask, null_count] = cudf::test::detail::make_null_mask(odd_validity, odd_validity + 5); auto int64_expected = cudf::make_lists_column( 5, std::move( cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 0, 8, 8, 16, 16}.release()), std::move(int64_data.release()), null_count, std::move(null_mask)); auto const output_int64 = cudf::byte_cast(int64_col, cudf::flip_endianness::YES); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(output_int64->view(), int64_expected->view()); } TEST_F(ByteCastTest, fp32ValuesWithSplit) { using limits = std::numeric_limits<float>; float nan = limits::quiet_NaN(); float inf = limits::infinity(); cudf::test::fixed_width_column_wrapper<float> const fp32_col( {float(0.0), float(100.0), float(-100.0), limits::min(), limits::max(), nan, -nan, inf, -inf}); cudf::test::lists_column_wrapper<uint8_t> const fp32_expected({{0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0xc8, 0x42}, {0x00, 0x00, 0xc8, 0xc2}, {0x00, 0x00, 0x80, 0x00}, {0xff, 0xff, 0x7f, 0x7f}, {0x00, 0x00, 0xc0, 0x7f}, {0x00, 0x00, 0xc0, 0xff}, {0x00, 0x00, 0x80, 0x7f}, {0x00, 0x00, 0x80, 0xff}}); cudf::test::lists_column_wrapper<uint8_t> const fp32_expected_slice1({{0x00, 0x00, 0x00, 0x00}, {0x42, 0xc8, 0x00, 0x00}, {0xc2, 0xc8, 0x00, 0x00}, {0x00, 0x80, 0x00, 0x00}, {0x7f, 0x7f, 0xff, 0xff}}); cudf::test::lists_column_wrapper<uint8_t> const fp32_expected_slice2({{0x7f, 0xc0, 0x00, 0x00}, {0xff, 0xc0, 0x00, 0x00}, {0x7f, 0x80, 0x00, 0x00}, {0xff, 0x80, 0x00, 0x00}}); std::vector<cudf::size_type> splits({5}); std::vector<cudf::column_view> split_column = cudf::split(fp32_col, splits); auto const output_fp32 = cudf::byte_cast(fp32_col, cudf::flip_endianness::NO); auto const output_fp32_slice1 = cudf::byte_cast(split_column.at(0), cudf::flip_endianness::YES); auto const output_fp32_slice2 = cudf::byte_cast(split_column.at(1), cudf::flip_endianness::YES); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output_fp32->view(), fp32_expected); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output_fp32_slice1->view(), fp32_expected_slice1); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output_fp32_slice2->view(), fp32_expected_slice2); } TEST_F(ByteCastTest, fp32ValuesWithNulls) { using limits = std::numeric_limits<float>; auto even_validity = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return (i + 1) % 2; }); cudf::test::fixed_width_column_wrapper<float> const fp32_col( {float(0.0), float(100.0), float(-100.0), limits::min(), limits::max()}, {1, 0, 1, 0, 1}); auto fp32_data = cudf::test::fixed_width_column_wrapper<uint8_t>{ 0x00, 0x00, 0x00, 0x00, 0xc2, 0xc8, 0x00, 0x00, 0x7f, 0x7f, 0xff, 0xff}; auto [null_mask, null_count] = cudf::test::detail::make_null_mask(even_validity, even_validity + 5); auto fp32_expected = cudf::make_lists_column( 5, std::move(cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 4, 4, 8, 8, 12}.release()), std::move(fp32_data.release()), null_count, std::move(null_mask)); auto const output_fp32 = cudf::byte_cast(fp32_col, cudf::flip_endianness::YES); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(output_fp32->view(), fp32_expected->view()); } TEST_F(ByteCastTest, fp64ValuesWithSplit) { using limits = std::numeric_limits<double>; double nan = limits::quiet_NaN(); double inf = limits::infinity(); cudf::test::fixed_width_column_wrapper<double> const fp64_col({double(0.0), double(100.0), double(-100.0), limits::min(), limits::max(), nan, -nan, inf, -inf}); cudf::test::lists_column_wrapper<uint8_t> const fp64_flipped_expected( {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x40, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0xc0, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x7f, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}); cudf::test::lists_column_wrapper<uint8_t> const fp64_expected_slice1( {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x59, 0x40}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x59, 0xc0}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0x7f}}); cudf::test::lists_column_wrapper<uint8_t> const fp64_expected_slice2( {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x7f}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x7f}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xff}}); std::vector<cudf::size_type> splits({5}); std::vector<cudf::column_view> split_column = cudf::split(fp64_col, splits); auto const output_fp64_flipped = cudf::byte_cast(fp64_col, cudf::flip_endianness::YES); auto const output_fp64_slice1 = cudf::byte_cast(split_column.at(0), cudf::flip_endianness::NO); auto const output_fp64_slice2 = cudf::byte_cast(split_column.at(1), cudf::flip_endianness::NO); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output_fp64_flipped->view(), fp64_flipped_expected); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output_fp64_slice1->view(), fp64_expected_slice1); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output_fp64_slice2->view(), fp64_expected_slice2); } TEST_F(ByteCastTest, fp64ValuesWithNulls) { using limits = std::numeric_limits<double>; auto odd_validity = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2; }); cudf::test::fixed_width_column_wrapper<double> const fp64_col( {double(0.0), double(100.0), double(-100.0), limits::min(), limits::max()}, {0, 1, 0, 1, 0}); auto fp64_data = cudf::test::fixed_width_column_wrapper<uint8_t>{ 0x40, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; auto [null_mask, null_count] = cudf::test::detail::make_null_mask(odd_validity, odd_validity + 5); auto fp64_expected = cudf::make_lists_column( 5, std::move( cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 0, 8, 8, 16, 16}.release()), std::move(fp64_data.release()), null_count, std::move(null_mask)); auto const output_fp64 = cudf::byte_cast(fp64_col, cudf::flip_endianness::YES); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(output_fp64->view(), fp64_expected->view()); } TEST_F(ByteCastTest, StringValuesNoNulls) { cudf::test::strings_column_wrapper const strings_col( {"", "The quick", " brown fox...", "!\"#$%&\'()*+,-./", "0123456789:;<=>?@", "[\\]^_`{|}~"}); cudf::test::lists_column_wrapper<uint8_t> const strings_expected( {{}, {0x54, 0x68, 0x65, 0x20, 0x71, 0x75, 0x69, 0x63, 0x6b}, {0x20, 0x62, 0x72, 0x6f, 0x77, 0x6e, 0x20, 0x66, 0x6f, 0x78, 0x2e, 0x2e, 0x2e}, {0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f}, {0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40}, {0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x7b, 0x7c, 0x7d, 0x7e}}); auto const output_strings = cudf::byte_cast(strings_col, cudf::flip_endianness::YES); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output_strings->view(), strings_expected); } TEST_F(ByteCastTest, StringValuesWithNulls) { auto const strings_col = [] { auto output = cudf::test::strings_column_wrapper( {"", "The quick", " brown fox...", "!\"#$%&\'()*+,-./", "0123456789:;<=>?@", "[\\]^_`{|}~"}) .release(); // Set nulls by `set_null_mask` so the output column will have non-empty nulls. // This is intentional. auto const null_iter = cudf::test::iterators::nulls_at({2, 4}); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(null_iter, null_iter + output->size()); output->set_null_mask(std::move(null_mask), null_count); return output; }(); auto const strings_expected = cudf::test::lists_column_wrapper<uint8_t>{ {{}, {0x54, 0x68, 0x65, 0x20, 0x71, 0x75, 0x69, 0x63, 0x6b}, {} /*NULL*/, {0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f}, {} /*NULL*/, {0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x7b, 0x7c, 0x7d, 0x7e}}, cudf::test::iterators::nulls_at({2, 4})}; auto const output_strings = cudf::byte_cast(*strings_col, cudf::flip_endianness::YES); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output_strings->view(), strings_expected); } TEST_F(ByteCastTest, int32Empty) { auto const input = cudf::test::fixed_width_column_wrapper<int32_t>{}; auto const expected = cudf::test::lists_column_wrapper<uint8_t>{}; auto const output = cudf::byte_cast(input, cudf::flip_endianness::YES); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *output); } TEST_F(ByteCastTest, int32sAllNulls) { auto const input = cudf::test::fixed_width_column_wrapper<int32_t>{{0, 0, 0}, cudf::test::iterators::all_nulls()}; auto const output = cudf::byte_cast(input, cudf::flip_endianness::YES); auto const& out_child = output->child(cudf::lists_column_view::child_column_index); EXPECT_EQ(output->size(), 3); EXPECT_EQ(output->null_count(), 3); EXPECT_EQ(out_child.size(), 0); EXPECT_EQ(out_child.type().id(), cudf::type_id::UINT8); } TEST_F(ByteCastTest, StringEmpty) { auto const input = cudf::test::strings_column_wrapper{}; auto const expected = cudf::test::lists_column_wrapper<uint8_t>{}; auto const output = cudf::byte_cast(input, cudf::flip_endianness::YES); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *output); } TEST_F(ByteCastTest, StringsAllNulls) { auto const input = cudf::test::strings_column_wrapper{{"", "", ""}, cudf::test::iterators::all_nulls()}; auto const output = cudf::byte_cast(input, cudf::flip_endianness::YES); auto const& out_child = output->child(cudf::lists_column_view::child_column_index); EXPECT_EQ(output->size(), 3); EXPECT_EQ(output->null_count(), 3); EXPECT_EQ(out_child.size(), 0); EXPECT_EQ(out_child.type().id(), cudf::type_id::UINT8); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/reshape/tile_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/reshape.hpp> #include <cudf/table/table.hpp> #include <cudf/utilities/error.hpp> template <typename T> struct TileTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(TileTest, cudf::test::AllTypes); TYPED_TEST(TileTest, NoColumns) { cudf::table_view in(std::vector<cudf::column_view>{}); auto expected = in; auto actual = cudf::tile(in, 10); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, actual->view()); } TYPED_TEST(TileTest, NoRows) { using T = TypeParam; cudf::test::fixed_width_column_wrapper<T> in_a({}); cudf::table_view in(std::vector<cudf::column_view>{in_a}); auto expected = in; auto actual = cudf::tile(in, 10); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, actual->view()); } TYPED_TEST(TileTest, OneColumn) { using T = TypeParam; cudf::test::fixed_width_column_wrapper<T, int32_t> in_a({-1, 0, 1}); cudf::table_view in(std::vector<cudf::column_view>{in_a}); cudf::test::fixed_width_column_wrapper<T, int32_t> expected_a({-1, 0, 1, -1, 0, 1}); cudf::table_view expected(std::vector<cudf::column_view>{expected_a}); auto actual = cudf::tile(in, 2); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, actual->view()); } TYPED_TEST(TileTest, OneColumnNullable) { using T = TypeParam; cudf::test::fixed_width_column_wrapper<T, int32_t> in_a({-1, 0, 1}, {1, 0, 0}); cudf::table_view in(std::vector<cudf::column_view>{in_a}); cudf::test::fixed_width_column_wrapper<T, int32_t> expected_a({-1, 0, 1, -1, 0, 1}, {1, 0, 0, 1, 0, 0}); cudf::table_view expected(std::vector<cudf::column_view>{expected_a}); auto actual = cudf::tile(in, 2); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, actual->view()); } TYPED_TEST(TileTest, OneColumnNegativeCount) { using T = TypeParam; cudf::test::fixed_width_column_wrapper<T, int32_t> in_a({-1, 0, 1}, {1, 0, 0}); cudf::table_view in(std::vector<cudf::column_view>{in_a}); EXPECT_THROW(cudf::tile(in, -1), cudf::logic_error); } TYPED_TEST(TileTest, OneColumnZeroCount) { using T = TypeParam; cudf::test::fixed_width_column_wrapper<T, int32_t> in_a({-1, 0, 1}, {1, 0, 0}); cudf::table_view in(std::vector<cudf::column_view>{in_a}); std::vector<T> vals{}; std::vector<bool> mask{}; cudf::test::fixed_width_column_wrapper<T> expected_a(vals.begin(), vals.end(), mask.begin()); cudf::table_view expected(std::vector<cudf::column_view>{expected_a}); auto actual = cudf::tile(in, 0); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, actual->view()); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/column/compound_test.cu
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/column/column.hpp> #include <cudf/column/column_device_view.cuh> #include <cudf/column/column_view.hpp> #include <cudf/null_mask.hpp> #include <cudf/utilities/default_stream.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/cudf_gtest.hpp> #include <rmm/device_uvector.hpp> #include <rmm/exec_policy.hpp> #include <thrust/iterator/counting_iterator.h> #include <thrust/logical.h> #include <thrust/sequence.h> #include <vector> struct CompoundColumnTest : public cudf::test::BaseFixture {}; template <typename ColumnDeviceView> struct checker_for_level1 { ColumnDeviceView d_column; bool __device__ operator()(int32_t idx) { int32_t val1 = d_column.child(0).template element<int32_t>(idx); int32_t val2 = d_column.child(1).template element<int32_t>(idx); int32_t val3 = d_column.child(2).template element<int32_t>(idx); return ((val1 + 100) == val2) && ((val2 + 100) == val3); } }; template <typename ColumnDeviceView> struct checker_for_level2 { ColumnDeviceView d_column; bool __device__ operator()(int32_t idx) { bool bcheck = true; for (int i = 0; i < 2 && bcheck; ++i) { auto child = d_column.child(i); int32_t val1 = child.child(0).template element<int32_t>(idx); int32_t val2 = child.child(1).template element<int32_t>(idx); int32_t val3 = child.child(2).template element<int32_t>(idx); bcheck = ((val1 + 100) == val2) && ((val2 + 100) == val3); } return bcheck; } }; TEST_F(CompoundColumnTest, ChildrenLevel1) { rmm::device_uvector<int32_t> data(1000, cudf::get_default_stream()); thrust::sequence(rmm::exec_policy(cudf::get_default_stream()), data.begin(), data.end(), 1); auto null_mask = cudf::create_null_mask(100, cudf::mask_state::UNALLOCATED); rmm::device_buffer data1{data.data() + 100, 100 * sizeof(int32_t), cudf::get_default_stream()}; rmm::device_buffer data2{data.data() + 200, 100 * sizeof(int32_t), cudf::get_default_stream()}; rmm::device_buffer data3{data.data() + 300, 100 * sizeof(int32_t), cudf::get_default_stream()}; auto child1 = std::make_unique<cudf::column>(cudf::data_type{cudf::type_id::INT32}, 100, std::move(data1), cudf::create_null_mask(100, cudf::mask_state::UNALLOCATED), 0); auto child2 = std::make_unique<cudf::column>(cudf::data_type{cudf::type_id::INT32}, 200, std::move(data2), cudf::create_null_mask(100, cudf::mask_state::UNALLOCATED), 0); auto child3 = std::make_unique<cudf::column>(cudf::data_type{cudf::type_id::INT32}, 300, std::move(data3), cudf::create_null_mask(100, cudf::mask_state::UNALLOCATED), 0); std::vector<std::unique_ptr<cudf::column>> children; children.emplace_back(std::move(child1)); children.emplace_back(std::move(child2)); children.emplace_back(std::move(child3)); auto parent = std::make_unique<cudf::column>(cudf::data_type{cudf::type_id::STRING}, 100, rmm::device_buffer{}, rmm::device_buffer{}, 0, std::move(children)); { auto column = cudf::column_device_view::create(parent->view()); EXPECT_TRUE(thrust::any_of(rmm::exec_policy(cudf::get_default_stream()), thrust::make_counting_iterator<int32_t>(0), thrust::make_counting_iterator<int32_t>(100), checker_for_level1<cudf::column_device_view>{*column})); } { auto column = cudf::mutable_column_device_view::create(parent->mutable_view()); EXPECT_TRUE(thrust::any_of(rmm::exec_policy(cudf::get_default_stream()), thrust::make_counting_iterator<int32_t>(0), thrust::make_counting_iterator<int32_t>(100), checker_for_level1<cudf::mutable_column_device_view>{*column})); } } TEST_F(CompoundColumnTest, ChildrenLevel2) { rmm::device_uvector<int32_t> data(1000, cudf::get_default_stream()); thrust::sequence(rmm::exec_policy(cudf::get_default_stream()), data.begin(), data.end(), 1); auto null_mask = cudf::create_null_mask(100, cudf::mask_state::UNALLOCATED); rmm::device_buffer data11{data.data() + 100, 100 * sizeof(int32_t), cudf::get_default_stream()}; rmm::device_buffer data12{data.data() + 200, 100 * sizeof(int32_t), cudf::get_default_stream()}; rmm::device_buffer data13{data.data() + 300, 100 * sizeof(int32_t), cudf::get_default_stream()}; rmm::device_buffer data21{data.data() + 400, 100 * sizeof(int32_t), cudf::get_default_stream()}; rmm::device_buffer data22{data.data() + 500, 100 * sizeof(int32_t), cudf::get_default_stream()}; rmm::device_buffer data23{data.data() + 600, 100 * sizeof(int32_t), cudf::get_default_stream()}; auto gchild11 = std::make_unique<cudf::column>(cudf::data_type{cudf::type_id::INT32}, 100, std::move(data11), cudf::create_null_mask(100, cudf::mask_state::UNALLOCATED), 0); auto gchild12 = std::make_unique<cudf::column>(cudf::data_type{cudf::type_id::INT32}, 200, std::move(data12), cudf::create_null_mask(100, cudf::mask_state::UNALLOCATED), 0); auto gchild13 = std::make_unique<cudf::column>(cudf::data_type{cudf::type_id::INT32}, 300, std::move(data13), cudf::create_null_mask(100, cudf::mask_state::UNALLOCATED), 0); auto gchild21 = std::make_unique<cudf::column>(cudf::data_type{cudf::type_id::INT32}, 400, std::move(data21), cudf::create_null_mask(100, cudf::mask_state::UNALLOCATED), 0); auto gchild22 = std::make_unique<cudf::column>(cudf::data_type{cudf::type_id::INT32}, 500, std::move(data22), cudf::create_null_mask(100, cudf::mask_state::UNALLOCATED), 0); auto gchild23 = std::make_unique<cudf::column>(cudf::data_type{cudf::type_id::INT32}, 600, std::move(data23), cudf::create_null_mask(100, cudf::mask_state::UNALLOCATED), 0); std::vector<std::unique_ptr<cudf::column>> gchildren1; gchildren1.emplace_back(std::move(gchild11)); gchildren1.emplace_back(std::move(gchild12)); gchildren1.emplace_back(std::move(gchild13)); std::vector<std::unique_ptr<cudf::column>> gchildren2; gchildren2.emplace_back(std::move(gchild21)); gchildren2.emplace_back(std::move(gchild22)); gchildren2.emplace_back(std::move(gchild23)); auto children1 = std::make_unique<cudf::column>(cudf::data_type{cudf::type_id::STRING}, 100, rmm::device_buffer{}, rmm::device_buffer{}, 0, std::move(gchildren1)); auto children2 = std::make_unique<cudf::column>(cudf::data_type{cudf::type_id::STRING}, 100, rmm::device_buffer{}, rmm::device_buffer{}, 0, std::move(gchildren2)); std::vector<std::unique_ptr<cudf::column>> children; children.emplace_back(std::move(children1)); children.emplace_back(std::move(children2)); auto parent = std::make_unique<cudf::column>(cudf::data_type{cudf::type_id::STRING}, 100, rmm::device_buffer{}, rmm::device_buffer{}, 0, std::move(children)); { auto column = cudf::column_device_view::create(parent->view()); EXPECT_TRUE(thrust::any_of(rmm::exec_policy(cudf::get_default_stream()), thrust::make_counting_iterator<int32_t>(0), thrust::make_counting_iterator<int32_t>(100), checker_for_level2<cudf::column_device_view>{*column})); } { auto column = cudf::mutable_column_device_view::create(parent->mutable_view()); EXPECT_TRUE(thrust::any_of(rmm::exec_policy(cudf::get_default_stream()), thrust::make_counting_iterator<int32_t>(0), thrust::make_counting_iterator<int32_t>(100), checker_for_level2<cudf::mutable_column_device_view>{*column})); } }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/column/bit_cast_test.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/column/column_view.hpp> #include <cudf/types.hpp> #include <cudf/utilities/type_dispatcher.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/type_lists.hpp> #include <thrust/iterator/counting_iterator.h> #include <random> template <typename T, typename T2 = void> struct rep_type_impl { using type = void; }; template <typename T> struct rep_type_impl<T, std::enable_if_t<cudf::is_timestamp<T>()>> { using type = typename T::duration::rep; }; template <typename T> struct rep_type_impl<T, std::enable_if_t<cudf::is_duration<T>()>> { using type = typename T::rep; }; template <typename T> struct rep_type_impl<T, std::enable_if_t<cudf::is_fixed_point<T>()>> { using type = typename T::rep; }; template <typename T> using rep_type_t = typename rep_type_impl<T>::type; template <typename T> struct ColumnViewAllTypesTests : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(ColumnViewAllTypesTests, cudf::test::FixedWidthTypes); template <typename FromType, typename ToType, typename Iterator> void do_bit_cast(cudf::column_view const& column_view, Iterator begin, Iterator end) { auto mutable_column_view = reinterpret_cast<cudf::mutable_column_view const&>(column_view); cudf::data_type to_type{cudf::type_to_id<ToType>()}; if (std::is_same_v<FromType, ToType>) { // Cast to same to_type auto output = cudf::bit_cast(column_view, column_view.type()); auto output1 = cudf::bit_cast(mutable_column_view, mutable_column_view.type()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output, column_view); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output1, mutable_column_view); } else if (std::is_same_v<rep_type_t<FromType>, ToType> || std::is_same_v<FromType, rep_type_t<ToType>>) { // Cast integer to timestamp or vice versa auto output = cudf::bit_cast(column_view, to_type); auto output1 = cudf::bit_cast(mutable_column_view, to_type); cudf::test::fixed_width_column_wrapper<ToType, cudf::size_type> expected(begin, end); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output, expected); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output1, expected); } else { if (cuda::std::is_trivially_copyable_v<FromType> && cuda::std::is_trivially_copyable_v<ToType>) { constexpr auto from_size = sizeof(cudf::device_storage_type_t<FromType>); constexpr auto to_size = sizeof(cudf::device_storage_type_t<ToType>); if (from_size == to_size) { // Cast from FromType to ToType auto output1 = cudf::bit_cast(column_view, to_type); auto output1_mutable = cudf::bit_cast(mutable_column_view, to_type); // Cast back from ToType to FromType cudf::data_type from_type{cudf::type_to_id<FromType>()}; auto output2 = cudf::bit_cast(output1, from_type); auto output2_mutable = cudf::bit_cast(output1_mutable, from_type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output2, column_view); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output2_mutable, mutable_column_view); } else { // Not allow to cast if sizes are mismatched EXPECT_THROW(cudf::bit_cast(column_view, to_type), cudf::logic_error); EXPECT_THROW(cudf::bit_cast(mutable_column_view, to_type), cudf::logic_error); } } else { // Not allow to cast if any of from/to types is not trivially copyable EXPECT_THROW(cudf::bit_cast(column_view, to_type), cudf::logic_error); EXPECT_THROW(cudf::bit_cast(mutable_column_view, to_type), cudf::logic_error); } } } TYPED_TEST(ColumnViewAllTypesTests, BitCast) { auto begin = thrust::make_counting_iterator(1); auto end = thrust::make_counting_iterator(16); cudf::test::fixed_width_column_wrapper<TypeParam, cudf::size_type> input(begin, end); do_bit_cast<TypeParam, int8_t>(input, begin, end); do_bit_cast<TypeParam, int16_t>(input, begin, end); do_bit_cast<TypeParam, int32_t>(input, begin, end); do_bit_cast<TypeParam, int64_t>(input, begin, end); do_bit_cast<TypeParam, float>(input, begin, end); do_bit_cast<TypeParam, double>(input, begin, end); do_bit_cast<TypeParam, bool>(input, begin, end); do_bit_cast<TypeParam, cudf::duration_D>(input, begin, end); do_bit_cast<TypeParam, cudf::duration_s>(input, begin, end); do_bit_cast<TypeParam, cudf::duration_ms>(input, begin, end); do_bit_cast<TypeParam, cudf::duration_us>(input, begin, end); do_bit_cast<TypeParam, cudf::duration_ns>(input, begin, end); do_bit_cast<TypeParam, cudf::timestamp_D>(input, begin, end); do_bit_cast<TypeParam, cudf::timestamp_s>(input, begin, end); do_bit_cast<TypeParam, cudf::timestamp_ms>(input, begin, end); do_bit_cast<TypeParam, cudf::timestamp_us>(input, begin, end); do_bit_cast<TypeParam, cudf::timestamp_ns>(input, begin, end); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/column/column_test.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/type_list_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/column/column.hpp> #include <cudf/column/column_factories.hpp> #include <cudf/column/column_view.hpp> #include <cudf/copying.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/detail/utilities/vector_factories.hpp> #include <cudf/null_mask.hpp> #include <cudf/transform.hpp> #include <cudf/types.hpp> #include <cudf/utilities/default_stream.hpp> #include <cudf/utilities/error.hpp> #include <numeric> #include <random> template <typename T> struct TypedColumnTest : public cudf::test::BaseFixture { cudf::data_type type() { return cudf::data_type{cudf::type_to_id<T>()}; } TypedColumnTest(rmm::cuda_stream_view stream = cudf::get_default_stream()) : data{_num_elements * cudf::size_of(type()), stream}, mask{cudf::bitmask_allocation_size_bytes(_num_elements), stream} { std::vector<char> h_data(std::max(data.size(), mask.size())); std::iota(h_data.begin(), h_data.end(), 0); CUDF_CUDA_TRY( cudaMemcpyAsync(data.data(), h_data.data(), data.size(), cudaMemcpyDefault, stream.value())); CUDF_CUDA_TRY( cudaMemcpyAsync(mask.data(), h_data.data(), mask.size(), cudaMemcpyDefault, stream.value())); } cudf::size_type num_elements() { return _num_elements; } std::random_device r; std::default_random_engine generator{r()}; std::uniform_int_distribution<cudf::size_type> distribution{200, 1000}; cudf::size_type _num_elements{distribution(generator)}; rmm::device_buffer data{}; rmm::device_buffer mask{}; rmm::device_buffer all_valid_mask{create_null_mask(num_elements(), cudf::mask_state::ALL_VALID)}; rmm::device_buffer all_null_mask{create_null_mask(num_elements(), cudf::mask_state::ALL_NULL)}; }; TYPED_TEST_SUITE(TypedColumnTest, cudf::test::Types<int32_t>); /** * @brief Verifies equality of the properties and data of a `column`'s views. * * @param col The `column` to verify */ void verify_column_views(cudf::column col) { cudf::column_view view = col; cudf::mutable_column_view mutable_view = col; EXPECT_EQ(col.type(), view.type()); EXPECT_EQ(col.type(), mutable_view.type()); EXPECT_EQ(col.size(), view.size()); EXPECT_EQ(col.size(), mutable_view.size()); EXPECT_EQ(col.null_count(), view.null_count()); EXPECT_EQ(col.null_count(), mutable_view.null_count()); EXPECT_EQ(col.nullable(), view.nullable()); EXPECT_EQ(col.nullable(), mutable_view.nullable()); EXPECT_EQ(col.num_children(), view.num_children()); EXPECT_EQ(col.num_children(), mutable_view.num_children()); EXPECT_EQ(view.head(), mutable_view.head()); EXPECT_EQ(view.data<char>(), mutable_view.data<char>()); EXPECT_EQ(view.offset(), mutable_view.offset()); } TYPED_TEST(TypedColumnTest, DefaultNullCountNoMask) { cudf::column col{ this->type(), this->num_elements(), std::move(this->data), rmm::device_buffer{}, 0}; EXPECT_FALSE(col.nullable()); EXPECT_FALSE(col.has_nulls()); EXPECT_EQ(0, col.null_count()); } TYPED_TEST(TypedColumnTest, DefaultNullCountEmptyMask) { cudf::column col{ this->type(), this->num_elements(), std::move(this->data), rmm::device_buffer{}, 0}; EXPECT_FALSE(col.nullable()); EXPECT_FALSE(col.has_nulls()); EXPECT_EQ(0, col.null_count()); } TYPED_TEST(TypedColumnTest, DefaultNullCountAllValid) { cudf::column col{ this->type(), this->num_elements(), std::move(this->data), std::move(this->all_valid_mask), 0}; EXPECT_TRUE(col.nullable()); EXPECT_FALSE(col.has_nulls()); EXPECT_EQ(0, col.null_count()); } TYPED_TEST(TypedColumnTest, ExplicitNullCountAllValid) { cudf::column col{ this->type(), this->num_elements(), std::move(this->data), std::move(this->all_valid_mask), 0}; EXPECT_TRUE(col.nullable()); EXPECT_FALSE(col.has_nulls()); EXPECT_EQ(0, col.null_count()); } TYPED_TEST(TypedColumnTest, DefaultNullCountAllNull) { cudf::column col{this->type(), this->num_elements(), std::move(this->data), std::move(this->all_null_mask), this->num_elements()}; EXPECT_TRUE(col.nullable()); EXPECT_TRUE(col.has_nulls()); EXPECT_EQ(this->num_elements(), col.null_count()); } TYPED_TEST(TypedColumnTest, ExplicitNullCountAllNull) { cudf::column col{this->type(), this->num_elements(), std::move(this->data), std::move(this->all_null_mask), this->num_elements()}; EXPECT_TRUE(col.nullable()); EXPECT_TRUE(col.has_nulls()); EXPECT_EQ(this->num_elements(), col.null_count()); } TYPED_TEST(TypedColumnTest, SetNullCountNoMask) { cudf::column col{ this->type(), this->num_elements(), std::move(this->data), rmm::device_buffer{}, 0}; EXPECT_THROW(col.set_null_count(1), cudf::logic_error); } TYPED_TEST(TypedColumnTest, SetEmptyNullMaskNonZeroNullCount) { cudf::column col{ this->type(), this->num_elements(), std::move(this->data), rmm::device_buffer{}, 0}; rmm::device_buffer empty_null_mask{}; EXPECT_THROW(col.set_null_mask(std::move(empty_null_mask), this->num_elements()), cudf::logic_error); } TYPED_TEST(TypedColumnTest, SetInvalidSizeNullMaskNonZeroNullCount) { cudf::column col{ this->type(), this->num_elements(), std::move(this->data), rmm::device_buffer{}, 0}; auto invalid_size_null_mask = create_null_mask(std::min(this->num_elements() - 50, 0), cudf::mask_state::ALL_VALID); EXPECT_THROW( col.set_null_mask(invalid_size_null_mask, this->num_elements(), cudf::get_default_stream()), cudf::logic_error); } TYPED_TEST(TypedColumnTest, SetNullCountEmptyMask) { cudf::column col{ this->type(), this->num_elements(), std::move(this->data), rmm::device_buffer{}, 0}; EXPECT_THROW(col.set_null_count(1), cudf::logic_error); } TYPED_TEST(TypedColumnTest, SetNullCountAllValid) { cudf::column col{ this->type(), this->num_elements(), std::move(this->data), std::move(this->all_valid_mask), 0}; EXPECT_NO_THROW(col.set_null_count(0)); EXPECT_EQ(0, col.null_count()); } TYPED_TEST(TypedColumnTest, SetNullCountAllNull) { cudf::column col{this->type(), this->num_elements(), std::move(this->data), std::move(this->all_null_mask), this->num_elements()}; EXPECT_NO_THROW(col.set_null_count(this->num_elements())); EXPECT_EQ(this->num_elements(), col.null_count()); } TYPED_TEST(TypedColumnTest, ResetNullCountAllNull) { cudf::column col{this->type(), this->num_elements(), std::move(this->data), std::move(this->all_null_mask), this->num_elements()}; EXPECT_EQ(this->num_elements(), col.null_count()); } TYPED_TEST(TypedColumnTest, ResetNullCountAllValid) { cudf::column col{ this->type(), this->num_elements(), std::move(this->data), std::move(this->all_valid_mask), 0}; EXPECT_EQ(0, col.null_count()); } TYPED_TEST(TypedColumnTest, CopyDataNoMask) { cudf::column col{ this->type(), this->num_elements(), std::move(this->data), rmm::device_buffer{}, 0}; EXPECT_EQ(this->type(), col.type()); EXPECT_FALSE(col.nullable()); EXPECT_EQ(0, col.null_count()); EXPECT_EQ(this->num_elements(), col.size()); EXPECT_EQ(0, col.num_children()); verify_column_views(col); // Verify deep copy cudf::column_view v = col; EXPECT_NE(v.head(), this->data.data()); CUDF_TEST_EXPECT_EQUAL_BUFFERS(v.head(), this->data.data(), this->data.size()); } TYPED_TEST(TypedColumnTest, MoveDataNoMask) { void* original_data = this->data.data(); cudf::column col{ this->type(), this->num_elements(), std::move(this->data), rmm::device_buffer{}, 0}; EXPECT_EQ(this->type(), col.type()); EXPECT_FALSE(col.nullable()); EXPECT_EQ(0, col.null_count()); EXPECT_EQ(this->num_elements(), col.size()); EXPECT_EQ(0, col.num_children()); verify_column_views(col); // Verify shallow copy cudf::column_view v = col; EXPECT_EQ(v.head(), original_data); } TYPED_TEST(TypedColumnTest, CopyDataAndMask) { cudf::column col{this->type(), this->num_elements(), rmm::device_buffer{this->data, cudf::get_default_stream()}, rmm::device_buffer{this->all_valid_mask, cudf::get_default_stream()}, 0}; EXPECT_EQ(this->type(), col.type()); EXPECT_TRUE(col.nullable()); EXPECT_EQ(0, col.null_count()); EXPECT_EQ(this->num_elements(), col.size()); EXPECT_EQ(0, col.num_children()); verify_column_views(col); // Verify deep copy cudf::column_view v = col; EXPECT_NE(v.head(), this->data.data()); EXPECT_NE(v.null_mask(), this->all_valid_mask.data()); CUDF_TEST_EXPECT_EQUAL_BUFFERS(v.head(), this->data.data(), this->data.size()); CUDF_TEST_EXPECT_EQUAL_BUFFERS(v.null_mask(), this->all_valid_mask.data(), this->mask.size()); } TYPED_TEST(TypedColumnTest, MoveDataAndMask) { void* original_data = this->data.data(); void* original_mask = this->all_valid_mask.data(); cudf::column col{ this->type(), this->num_elements(), std::move(this->data), std::move(this->all_valid_mask), 0}; EXPECT_EQ(this->type(), col.type()); EXPECT_TRUE(col.nullable()); EXPECT_EQ(0, col.null_count()); EXPECT_EQ(this->num_elements(), col.size()); EXPECT_EQ(0, col.num_children()); verify_column_views(col); // Verify shallow copy cudf::column_view v = col; EXPECT_EQ(v.head(), original_data); EXPECT_EQ(v.null_mask(), original_mask); } TYPED_TEST(TypedColumnTest, CopyConstructorNoMask) { cudf::column original{ this->type(), this->num_elements(), std::move(this->data), rmm::device_buffer{}, 0}; cudf::column copy{original}; verify_column_views(copy); CUDF_TEST_EXPECT_COLUMNS_EQUAL(original, copy); // Verify deep copy cudf::column_view original_view = original; cudf::column_view copy_view = copy; EXPECT_NE(original_view.head(), copy_view.head()); } TYPED_TEST(TypedColumnTest, CopyConstructorWithMask) { cudf::column original{ this->type(), this->num_elements(), std::move(this->data), std::move(this->all_valid_mask), 0}; cudf::column copy{original}; verify_column_views(copy); CUDF_TEST_EXPECT_COLUMNS_EQUAL(original, copy); // Verify deep copy cudf::column_view original_view = original; cudf::column_view copy_view = copy; EXPECT_NE(original_view.head(), copy_view.head()); EXPECT_NE(original_view.null_mask(), copy_view.null_mask()); } TYPED_TEST(TypedColumnTest, MoveConstructorNoMask) { cudf::column original{ this->type(), this->num_elements(), std::move(this->data), rmm::device_buffer{}, 0}; auto original_data = original.view().head(); cudf::column moved_to{std::move(original)}; EXPECT_EQ(0, original.size()); EXPECT_EQ(cudf::data_type{cudf::type_id::EMPTY}, original.type()); verify_column_views(moved_to); // Verify move cudf::column_view moved_to_view = moved_to; EXPECT_EQ(original_data, moved_to_view.head()); } TYPED_TEST(TypedColumnTest, MoveConstructorWithMask) { cudf::column original{ this->type(), this->num_elements(), std::move(this->data), std::move(this->all_valid_mask), 0}; auto original_data = original.view().head(); auto original_mask = original.view().null_mask(); cudf::column moved_to{std::move(original)}; verify_column_views(moved_to); EXPECT_EQ(0, original.size()); EXPECT_EQ(cudf::data_type{cudf::type_id::EMPTY}, original.type()); // Verify move cudf::column_view moved_to_view = moved_to; EXPECT_EQ(original_data, moved_to_view.head()); EXPECT_EQ(original_mask, moved_to_view.null_mask()); } TYPED_TEST(TypedColumnTest, DeviceUvectorConstructorNoMask) { auto data = cudf::device_span<TypeParam const>(static_cast<TypeParam*>(this->data.data()), this->num_elements()); auto original = cudf::detail::make_device_uvector_async( data, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto original_data = original.data(); cudf::column moved_to{std::move(original), rmm::device_buffer{}, 0}; verify_column_views(moved_to); // Verify move cudf::column_view moved_to_view = moved_to; EXPECT_EQ(original_data, moved_to_view.head()); } TYPED_TEST(TypedColumnTest, DeviceUvectorConstructorWithMask) { auto data = cudf::device_span<TypeParam const>(static_cast<TypeParam*>(this->data.data()), this->num_elements()); auto original = cudf::detail::make_device_uvector_async( data, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto original_data = original.data(); auto original_mask = this->all_valid_mask.data(); cudf::column moved_to{std::move(original), std::move(this->all_valid_mask), 0}; verify_column_views(moved_to); // Verify move cudf::column_view moved_to_view = moved_to; EXPECT_EQ(original_data, moved_to_view.head()); EXPECT_EQ(original_mask, moved_to_view.null_mask()); } TYPED_TEST(TypedColumnTest, ConstructWithChildren) { std::vector<std::unique_ptr<cudf::column>> children; children.emplace_back(std::make_unique<cudf::column>( cudf::data_type{cudf::type_id::INT8}, 42, rmm::device_buffer{this->data, cudf::get_default_stream()}, rmm::device_buffer{this->all_valid_mask, cudf::get_default_stream()}, 0)); children.emplace_back(std::make_unique<cudf::column>( cudf::data_type{cudf::type_id::FLOAT64}, 314, rmm::device_buffer{this->data, cudf::get_default_stream()}, rmm::device_buffer{this->all_valid_mask, cudf::get_default_stream()}, 0)); cudf::column col{this->type(), this->num_elements(), rmm::device_buffer{this->data, cudf::get_default_stream()}, rmm::device_buffer{this->all_valid_mask, cudf::get_default_stream()}, 0, std::move(children)}; verify_column_views(col); EXPECT_EQ(2, col.num_children()); EXPECT_EQ(cudf::data_type{cudf::type_id::INT8}, col.child(0).type()); EXPECT_EQ(42, col.child(0).size()); EXPECT_EQ(cudf::data_type{cudf::type_id::FLOAT64}, col.child(1).type()); EXPECT_EQ(314, col.child(1).size()); } TYPED_TEST(TypedColumnTest, ReleaseNoChildren) { cudf::column col{ this->type(), this->num_elements(), std::move(this->data), std::move(this->all_valid_mask), 0}; auto original_data = col.view().head(); auto original_mask = col.view().null_mask(); cudf::column::contents contents = col.release(); EXPECT_EQ(original_data, contents.data->data()); EXPECT_EQ(original_mask, contents.null_mask->data()); EXPECT_EQ(0u, contents.children.size()); EXPECT_EQ(0, col.size()); EXPECT_EQ(0, col.null_count()); EXPECT_EQ(cudf::data_type{cudf::type_id::EMPTY}, col.type()); EXPECT_EQ(0, col.num_children()); } TYPED_TEST(TypedColumnTest, ReleaseWithChildren) { std::vector<std::unique_ptr<cudf::column>> children; children.emplace_back(std::make_unique<cudf::column>( this->type(), this->num_elements(), rmm::device_buffer{this->data, cudf::get_default_stream()}, rmm::device_buffer{this->all_valid_mask, cudf::get_default_stream()}, 0)); children.emplace_back(std::make_unique<cudf::column>( this->type(), this->num_elements(), rmm::device_buffer{this->data, cudf::get_default_stream()}, rmm::device_buffer{this->all_valid_mask, cudf::get_default_stream()}, 0)); cudf::column col{this->type(), this->num_elements(), rmm::device_buffer{this->data, cudf::get_default_stream()}, rmm::device_buffer{this->all_valid_mask, cudf::get_default_stream()}, 0, std::move(children)}; auto original_data = col.view().head(); auto original_mask = col.view().null_mask(); cudf::column::contents contents = col.release(); EXPECT_EQ(original_data, contents.data->data()); EXPECT_EQ(original_mask, contents.null_mask->data()); EXPECT_EQ(2u, contents.children.size()); EXPECT_EQ(0, col.size()); EXPECT_EQ(0, col.null_count()); EXPECT_EQ(cudf::data_type{cudf::type_id::EMPTY}, col.type()); EXPECT_EQ(0, col.num_children()); } TYPED_TEST(TypedColumnTest, ColumnViewConstructorWithMask) { cudf::column original{ this->type(), this->num_elements(), std::move(this->data), std::move(this->all_valid_mask), 0}; cudf::column_view original_view = original; cudf::column copy{original_view}; verify_column_views(copy); CUDF_TEST_EXPECT_COLUMNS_EQUAL(original, copy); // Verify deep copy cudf::column_view copy_view = copy; EXPECT_NE(original_view.head(), copy_view.head()); EXPECT_NE(original_view.null_mask(), copy_view.null_mask()); } template <typename T> struct ListsColumnTest : public cudf::test::BaseFixture {}; using NumericTypesNotBool = cudf::test::Concat<cudf::test::IntegralTypesNotBool, cudf::test::FloatingPointTypes>; TYPED_TEST_SUITE(ListsColumnTest, NumericTypesNotBool); TYPED_TEST(ListsColumnTest, ListsColumnViewConstructor) { cudf::test::lists_column_wrapper<TypeParam> list{{1, 2}, {3, 4}, {5, 6, 7}, {8, 9}}; auto result = std::make_unique<cudf::column>(list); CUDF_TEST_EXPECT_COLUMNS_EQUAL(list, result->view()); } TYPED_TEST(ListsColumnTest, ListsSlicedColumnViewConstructor) { cudf::test::lists_column_wrapper<TypeParam> list{{1, 2}, {3, 4}, {5, 6, 7}, {8, 9}}; cudf::test::lists_column_wrapper<TypeParam> expect{{3, 4}, {5, 6, 7}}; auto sliced = cudf::slice(list, {1, 3}).front(); auto result = std::make_unique<cudf::column>(sliced); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expect, result->view()); } TYPED_TEST(ListsColumnTest, ListsSlicedIncludesEmpty) { cudf::test::lists_column_wrapper<TypeParam> list{{1, 2}, {}, {3, 4}, {8, 9}}; cudf::test::lists_column_wrapper<TypeParam> expect{{}, {3, 4}}; auto sliced = cudf::slice(list, {1, 3}).front(); auto result = std::make_unique<cudf::column>(sliced); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expect, result->view()); } TYPED_TEST(ListsColumnTest, ListsSlicedNonNestedEmpty) { using LCW = cudf::test::lists_column_wrapper<TypeParam>; // Column of List<int> LCW list{{1, 2}, {}, {3, 4}, {8, 9}}; // Column of 1 row, an empty List<int> LCW expect{LCW{}}; auto sliced = cudf::slice(list, {1, 2}).front(); auto result = std::make_unique<cudf::column>(sliced); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expect, result->view()); } TYPED_TEST(ListsColumnTest, ListsSlicedNestedEmpty) { using LCW = cudf::test::lists_column_wrapper<TypeParam>; using FWCW_SZ = cudf::test::fixed_width_column_wrapper<cudf::size_type>; // Column of List<List<int>>, with incomplete hierarchy LCW list{{LCW{1}, LCW{2}}, {}, // < ----------- empty List<List<int>>, slice this {LCW{3}, LCW{4, 5}}}; // Make 1-row column of type List<List<int>>, the row data contains 0 element. // Well-formed memory layout: // type: List<List<int>> // Length: 1 // Mask: 1 // Offsets: 0, 0 // List<int> // Length: 0 // Offset: // INT // Length: 0 auto leaf = std::make_unique<cudf::column>(cudf::column(LCW{})); auto offset = std::make_unique<cudf::column>(cudf::column(FWCW_SZ{0, 0})); auto null_mask = cudf::create_null_mask(0, cudf::mask_state::UNALLOCATED); auto expect = cudf::make_lists_column(1, std::move(offset), std::move(leaf), 0, std::move(null_mask)); auto sliced = cudf::slice(list, {1, 2}).front(); auto result = std::make_unique<cudf::column>(sliced); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*expect, result->view()); } TYPED_TEST(ListsColumnTest, ListsSlicedZeroSliceLengthNested) { using LCW = cudf::test::lists_column_wrapper<TypeParam>; // Column of List<List<int>>, with incomplete hierarchy LCW list{{LCW{1}, LCW{2}}, {}, {LCW{3}, LCW{4, 5}}}; auto expect = cudf::empty_like(list); auto sliced = cudf::slice(list, {0, 0}).front(); auto result = std::make_unique<cudf::column>(sliced); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*expect, result->view()); } TYPED_TEST(ListsColumnTest, ListsSlicedZeroSliceLengthNonNested) { using LCW = cudf::test::lists_column_wrapper<TypeParam>; LCW list{{1, 2}, {}, {3, 4}, {8, 9}}; auto expect = cudf::empty_like(list); auto sliced = cudf::slice(list, {0, 0}).front(); auto result = std::make_unique<cudf::column>(sliced); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*expect, result->view()); } TYPED_TEST(ListsColumnTest, ListsSlicedColumnViewConstructorWithNulls) { auto valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 == 0; }); auto expect_valids = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2 != 0; }); using LCW = cudf::test::lists_column_wrapper<TypeParam>; cudf::test::lists_column_wrapper<TypeParam> list{ {{{{1, 2}, {3, 4}}, valids}, LCW{}, {{{5, 6, 7}, LCW{}, {8, 9}}, valids}, LCW{}, LCW{}}, valids}; cudf::test::lists_column_wrapper<TypeParam> expect{ {LCW{}, {{{5, 6, 7}, LCW{}, {8, 9}}, valids}, LCW{}, LCW{}}, expect_valids}; auto sliced = cudf::slice(list, {1, 5}).front(); auto result = std::make_unique<cudf::column>(sliced); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expect, result->view()); // TODO: null mask equality is being checked separately because // expect_columns_equal doesn't do the check for lists columns. // This is fixed in https://github.com/rapidsai/cudf/pull/5904, // so we should remove this check after that's merged: CUDF_TEST_EXPECT_COLUMNS_EQUAL( cudf::mask_to_bools(result->view().null_mask(), 0, 4)->view(), cudf::mask_to_bools(static_cast<cudf::column_view>(expect).null_mask(), 0, 4)->view()); } CUDF_TEST_PROGRAM_MAIN()
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/column/column_view_device_span_test.cpp
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/column/column_view.hpp> #include <cudf/null_mask.hpp> #include <cudf/types.hpp> #include <cudf/utilities/span.hpp> #include <cudf/utilities/traits.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/type_lists.hpp> #include <thrust/iterator/counting_iterator.h> #include <memory> template <typename T, CUDF_ENABLE_IF(cudf::is_numeric<T>() or cudf::is_chrono<T>())> std::unique_ptr<cudf::column> example_column() { auto begin = thrust::make_counting_iterator(1); auto end = thrust::make_counting_iterator(16); return cudf::test::fixed_width_column_wrapper<T>(begin, end).release(); } template <typename T> struct ColumnViewDeviceSpanTests : public cudf::test::BaseFixture {}; using DeviceSpanTypes = cudf::test::FixedWidthTypesWithoutFixedPoint; TYPED_TEST_SUITE(ColumnViewDeviceSpanTests, DeviceSpanTypes); TYPED_TEST(ColumnViewDeviceSpanTests, conversion_round_trip) { auto col = example_column<TypeParam>(); auto col_view = cudf::column_view{*col}; // Test implicit conversion, round trip cudf::device_span<TypeParam const> device_span_from_col_view = col_view; cudf::column_view col_view_from_device_span = device_span_from_col_view; CUDF_TEST_EXPECT_COLUMNS_EQUAL(col_view, col_view_from_device_span); } struct ColumnViewDeviceSpanErrorTests : public cudf::test::BaseFixture {}; TEST_F(ColumnViewDeviceSpanErrorTests, type_mismatch) { auto col = example_column<int32_t>(); auto col_view = cudf::column_view{*col}; EXPECT_THROW((void)cudf::device_span<float const>{col_view}, cudf::logic_error); } TEST_F(ColumnViewDeviceSpanErrorTests, nullable_column) { auto col = example_column<int32_t>(); col->set_null_mask(cudf::create_null_mask(col->size(), cudf::mask_state::ALL_NULL), col->size()); auto col_view = cudf::column_view{*col}; EXPECT_THROW((void)cudf::device_span<int32_t const>{col_view}, cudf::logic_error); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/column/factories_test.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/column/column.hpp> #include <cudf/column/column_factories.hpp> #include <cudf/null_mask.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/scalar/scalar_factories.hpp> #include <cudf/types.hpp> #include <cudf/utilities/default_stream.hpp> #include <cudf/utilities/type_dispatcher.hpp> #include <rmm/cuda_stream_view.hpp> #include <thrust/iterator/counting_iterator.h> class ColumnFactoryTest : public cudf::test::BaseFixture { cudf::size_type _size{1000}; public: cudf::size_type size() { return _size; } }; template <typename T> class NumericFactoryTest : public ColumnFactoryTest {}; TYPED_TEST_SUITE(NumericFactoryTest, cudf::test::NumericTypes); TYPED_TEST(NumericFactoryTest, EmptyNoMask) { auto column = cudf::make_numeric_column( cudf::data_type{cudf::type_to_id<TypeParam>()}, 0, cudf::mask_state::UNALLOCATED); EXPECT_EQ(column->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(column->size(), 0); EXPECT_EQ(0, column->null_count()); EXPECT_FALSE(column->nullable()); EXPECT_FALSE(column->has_nulls()); EXPECT_EQ(0, column->num_children()); } TYPED_TEST(NumericFactoryTest, EmptyAllValidMask) { auto column = cudf::make_numeric_column( cudf::data_type{cudf::type_to_id<TypeParam>()}, 0, cudf::mask_state::ALL_VALID); EXPECT_EQ(column->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(column->size(), 0); EXPECT_EQ(0, column->null_count()); EXPECT_FALSE(column->nullable()); EXPECT_FALSE(column->has_nulls()); EXPECT_EQ(0, column->num_children()); } TYPED_TEST(NumericFactoryTest, EmptyAllNullMask) { auto column = cudf::make_numeric_column( cudf::data_type{cudf::type_to_id<TypeParam>()}, 0, cudf::mask_state::ALL_NULL); EXPECT_EQ(column->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(column->size(), 0); EXPECT_EQ(0, column->null_count()); EXPECT_FALSE(column->nullable()); EXPECT_FALSE(column->has_nulls()); EXPECT_EQ(0, column->num_children()); } TYPED_TEST(NumericFactoryTest, NoMask) { auto column = cudf::make_numeric_column( cudf::data_type{cudf::type_to_id<TypeParam>()}, this->size(), cudf::mask_state::UNALLOCATED); EXPECT_EQ(column->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(column->size(), this->size()); EXPECT_EQ(0, column->null_count()); EXPECT_FALSE(column->nullable()); EXPECT_FALSE(column->has_nulls()); EXPECT_EQ(0, column->num_children()); } TYPED_TEST(NumericFactoryTest, UnitializedMask) { auto column = cudf::make_numeric_column( cudf::data_type{cudf::type_to_id<TypeParam>()}, this->size(), cudf::mask_state::UNINITIALIZED); EXPECT_EQ(column->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(column->size(), this->size()); EXPECT_TRUE(column->nullable()); EXPECT_EQ(0, column->num_children()); } TYPED_TEST(NumericFactoryTest, AllValidMask) { auto column = cudf::make_numeric_column( cudf::data_type{cudf::type_to_id<TypeParam>()}, this->size(), cudf::mask_state::ALL_VALID); EXPECT_EQ(column->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(column->size(), this->size()); EXPECT_EQ(0, column->null_count()); EXPECT_TRUE(column->nullable()); EXPECT_FALSE(column->has_nulls()); EXPECT_EQ(0, column->num_children()); } TYPED_TEST(NumericFactoryTest, AllNullMask) { auto column = cudf::make_numeric_column( cudf::data_type{cudf::type_to_id<TypeParam>()}, this->size(), cudf::mask_state::ALL_NULL); EXPECT_EQ(column->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(column->size(), this->size()); EXPECT_EQ(this->size(), column->null_count()); EXPECT_TRUE(column->nullable()); EXPECT_TRUE(column->has_nulls()); EXPECT_EQ(0, column->num_children()); } TYPED_TEST(NumericFactoryTest, NullMaskAsParm) { rmm::device_buffer null_mask{create_null_mask(this->size(), cudf::mask_state::ALL_NULL)}; auto column = cudf::make_numeric_column(cudf::data_type{cudf::type_to_id<TypeParam>()}, this->size(), std::move(null_mask), this->size()); EXPECT_EQ(column->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(column->size(), this->size()); EXPECT_EQ(this->size(), column->null_count()); EXPECT_TRUE(column->nullable()); EXPECT_TRUE(column->has_nulls()); EXPECT_EQ(0, column->num_children()); } TYPED_TEST(NumericFactoryTest, NullMaskAsEmptyParm) { auto column = cudf::make_numeric_column( cudf::data_type{cudf::type_to_id<TypeParam>()}, this->size(), rmm::device_buffer{}, 0); EXPECT_EQ(column->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(column->size(), this->size()); EXPECT_EQ(0, column->null_count()); EXPECT_FALSE(column->nullable()); EXPECT_FALSE(column->has_nulls()); EXPECT_EQ(0, column->num_children()); } class NonNumericFactoryTest : public ColumnFactoryTest, public testing::WithParamInterface<cudf::type_id> {}; // All non-numeric types should throw TEST_P(NonNumericFactoryTest, NonNumericThrow) { auto construct = [this]() { auto column = cudf::make_numeric_column( cudf::data_type{GetParam()}, this->size(), cudf::mask_state::UNALLOCATED); }; EXPECT_THROW(construct(), cudf::logic_error); } INSTANTIATE_TEST_CASE_P(NonNumeric, NonNumericFactoryTest, testing::ValuesIn(cudf::test::non_numeric_type_ids)); template <typename T> class FixedWidthFactoryTest : public ColumnFactoryTest {}; TYPED_TEST_SUITE(FixedWidthFactoryTest, cudf::test::FixedWidthTypes); TYPED_TEST(FixedWidthFactoryTest, EmptyNoMask) { auto column = cudf::make_fixed_width_column( cudf::data_type{cudf::type_to_id<TypeParam>()}, 0, cudf::mask_state::UNALLOCATED); EXPECT_EQ(column->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); } template <typename T> class EmptyFactoryTest : public ColumnFactoryTest {}; TYPED_TEST_SUITE(EmptyFactoryTest, cudf::test::AllTypes); TYPED_TEST(EmptyFactoryTest, Empty) { auto type = cudf::data_type{cudf::type_to_id<TypeParam>()}; auto column = cudf::make_empty_column(type); EXPECT_EQ(type, column->type()); EXPECT_EQ(column->size(), 0); EXPECT_EQ(0, column->null_count()); EXPECT_FALSE(column->nullable()); EXPECT_FALSE(column->has_nulls()); EXPECT_EQ(0, column->num_children()); } TYPED_TEST(FixedWidthFactoryTest, EmptyAllValidMask) { auto column = cudf::make_fixed_width_column( cudf::data_type{cudf::type_to_id<TypeParam>()}, 0, cudf::mask_state::ALL_VALID); EXPECT_EQ(column->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(column->size(), 0); EXPECT_EQ(0, column->null_count()); EXPECT_FALSE(column->nullable()); EXPECT_FALSE(column->has_nulls()); EXPECT_EQ(0, column->num_children()); } TYPED_TEST(FixedWidthFactoryTest, EmptyAllNullMask) { auto column = cudf::make_fixed_width_column( cudf::data_type{cudf::type_to_id<TypeParam>()}, 0, cudf::mask_state::ALL_NULL); EXPECT_EQ(column->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(column->size(), 0); EXPECT_EQ(0, column->null_count()); EXPECT_FALSE(column->nullable()); EXPECT_FALSE(column->has_nulls()); EXPECT_EQ(0, column->num_children()); } TYPED_TEST(FixedWidthFactoryTest, NoMask) { auto column = cudf::make_fixed_width_column( cudf::data_type{cudf::type_to_id<TypeParam>()}, this->size(), cudf::mask_state::UNALLOCATED); EXPECT_EQ(column->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(column->size(), this->size()); EXPECT_EQ(0, column->null_count()); EXPECT_FALSE(column->nullable()); EXPECT_FALSE(column->has_nulls()); EXPECT_EQ(0, column->num_children()); } TYPED_TEST(FixedWidthFactoryTest, UnitializedMask) { auto column = cudf::make_fixed_width_column( cudf::data_type{cudf::type_to_id<TypeParam>()}, this->size(), cudf::mask_state::UNINITIALIZED); EXPECT_EQ(column->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(column->size(), this->size()); EXPECT_TRUE(column->nullable()); EXPECT_EQ(0, column->num_children()); } TYPED_TEST(FixedWidthFactoryTest, AllValidMask) { auto column = cudf::make_fixed_width_column( cudf::data_type{cudf::type_to_id<TypeParam>()}, this->size(), cudf::mask_state::ALL_VALID); EXPECT_EQ(column->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(column->size(), this->size()); EXPECT_EQ(0, column->null_count()); EXPECT_TRUE(column->nullable()); EXPECT_FALSE(column->has_nulls()); EXPECT_EQ(0, column->num_children()); } TYPED_TEST(FixedWidthFactoryTest, AllNullMask) { auto column = cudf::make_fixed_width_column( cudf::data_type{cudf::type_to_id<TypeParam>()}, this->size(), cudf::mask_state::ALL_NULL); EXPECT_EQ(column->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(column->size(), this->size()); EXPECT_EQ(this->size(), column->null_count()); EXPECT_TRUE(column->nullable()); EXPECT_TRUE(column->has_nulls()); EXPECT_EQ(0, column->num_children()); } TYPED_TEST(FixedWidthFactoryTest, NullMaskAsParm) { rmm::device_buffer null_mask{create_null_mask(this->size(), cudf::mask_state::ALL_NULL)}; auto column = cudf::make_fixed_width_column(cudf::data_type{cudf::type_to_id<TypeParam>()}, this->size(), std::move(null_mask), this->size()); EXPECT_EQ(column->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(column->size(), this->size()); EXPECT_EQ(this->size(), column->null_count()); EXPECT_TRUE(column->nullable()); EXPECT_TRUE(column->has_nulls()); EXPECT_EQ(0, column->num_children()); } TYPED_TEST(FixedWidthFactoryTest, NullMaskAsEmptyParm) { auto column = cudf::make_fixed_width_column( cudf::data_type{cudf::type_to_id<TypeParam>()}, this->size(), rmm::device_buffer{}, 0); EXPECT_EQ(column->type(), cudf::data_type{cudf::type_to_id<TypeParam>()}); EXPECT_EQ(column->size(), this->size()); EXPECT_EQ(0, column->null_count()); EXPECT_FALSE(column->nullable()); EXPECT_FALSE(column->has_nulls()); EXPECT_EQ(0, column->num_children()); } class NonFixedWidthFactoryTest : public ColumnFactoryTest, public testing::WithParamInterface<cudf::type_id> {}; // All non-fixed types should throw TEST_P(NonFixedWidthFactoryTest, NonFixedWidthThrow) { auto construct = [this]() { auto column = cudf::make_fixed_width_column( cudf::data_type{GetParam()}, this->size(), cudf::mask_state::UNALLOCATED); }; EXPECT_THROW(construct(), cudf::logic_error); } INSTANTIATE_TEST_CASE_P(NonFixedWidth, NonFixedWidthFactoryTest, testing::ValuesIn(cudf::test::non_fixed_width_type_ids)); TYPED_TEST(NumericFactoryTest, FromScalar) { cudf::numeric_scalar<TypeParam> value(12); auto column = cudf::make_column_from_scalar(value, 10); EXPECT_EQ(column->type(), value.type()); EXPECT_EQ(10, column->size()); EXPECT_EQ(0, column->null_count()); EXPECT_FALSE(column->nullable()); EXPECT_FALSE(column->has_nulls()); EXPECT_EQ(0, column->num_children()); } TYPED_TEST(NumericFactoryTest, FromNullScalar) { cudf::numeric_scalar<TypeParam> value(0, false); auto column = cudf::make_column_from_scalar(value, 10); EXPECT_EQ(column->type(), value.type()); EXPECT_EQ(10, column->size()); EXPECT_EQ(10, column->null_count()); EXPECT_TRUE(column->nullable()); EXPECT_TRUE(column->has_nulls()); EXPECT_EQ(0, column->num_children()); } TYPED_TEST(NumericFactoryTest, FromScalarWithZeroSize) { cudf::numeric_scalar<TypeParam> value(7); auto column = cudf::make_column_from_scalar(value, 0); EXPECT_EQ(column->type(), value.type()); EXPECT_EQ(0, column->size()); EXPECT_EQ(0, column->null_count()); EXPECT_FALSE(column->nullable()); EXPECT_FALSE(column->has_nulls()); EXPECT_EQ(0, column->num_children()); } TEST_F(ColumnFactoryTest, FromStringScalar) { cudf::string_scalar value("hello"); auto column = cudf::make_column_from_scalar(value, 1); EXPECT_EQ(1, column->size()); EXPECT_EQ(column->type(), value.type()); EXPECT_EQ(0, column->null_count()); EXPECT_FALSE(column->nullable()); EXPECT_FALSE(column->has_nulls()); EXPECT_TRUE(column->num_children() > 0); } TEST_F(ColumnFactoryTest, FromNullStringScalar) { cudf::string_scalar value("", false); auto column = cudf::make_column_from_scalar(value, 2); EXPECT_EQ(2, column->size()); EXPECT_EQ(column->type(), value.type()); EXPECT_EQ(2, column->null_count()); EXPECT_TRUE(column->nullable()); EXPECT_TRUE(column->has_nulls()); EXPECT_TRUE(column->num_children() > 0); } TEST_F(ColumnFactoryTest, FromStringScalarWithZeroSize) { cudf::string_scalar value("hello"); auto column = cudf::make_column_from_scalar(value, 0); EXPECT_EQ(0, column->size()); EXPECT_EQ(column->type(), value.type()); EXPECT_EQ(0, column->null_count()); EXPECT_FALSE(column->nullable()); EXPECT_FALSE(column->has_nulls()); } TEST_F(ColumnFactoryTest, DictionaryFromStringScalar) { cudf::string_scalar value("hello"); auto column = cudf::make_dictionary_from_scalar(value, 1); EXPECT_EQ(1, column->size()); EXPECT_EQ(column->type(), cudf::data_type{cudf::type_id::DICTIONARY32}); EXPECT_EQ(0, column->null_count()); EXPECT_EQ(2, column->num_children()); EXPECT_FALSE(column->nullable()); EXPECT_FALSE(column->has_nulls()); } TEST_F(ColumnFactoryTest, DictionaryFromStringScalarError) { cudf::string_scalar value("hello", false); EXPECT_THROW(cudf::make_dictionary_from_scalar(value, 1), cudf::logic_error); } template <typename T> class ListsFixedWidthLeafTest : public ColumnFactoryTest {}; TYPED_TEST_SUITE(ListsFixedWidthLeafTest, cudf::test::FixedWidthTypes); TYPED_TEST(ListsFixedWidthLeafTest, FromNonNested) { using FCW = cudf::test::fixed_width_column_wrapper<TypeParam>; using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; using valid_t = std::vector<cudf::valid_type>; auto s = cudf::make_list_scalar(FCW({1, -1, 3}, {1, 0, 1})); auto col = cudf::make_column_from_scalar(*s, 3); auto expected = LCW{LCW({1, 2, 3}, valid_t{1, 0, 1}.begin()), LCW({1, 2, 3}, valid_t{1, 0, 1}.begin()), LCW({1, 2, 3}, valid_t{1, 0, 1}.begin())}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*col, expected); } TYPED_TEST(ListsFixedWidthLeafTest, FromNested) { using LCW = cudf::test::lists_column_wrapper<TypeParam, int32_t>; using valid_t = std::vector<cudf::valid_type>; #define row_data \ LCW({LCW({-1, -1, 3}, valid_t{0, 0, 1}.begin()), LCW{}, LCW{}}, valid_t{1, 0, 1}.begin()) auto s = cudf::make_list_scalar(row_data); auto col = cudf::make_column_from_scalar(*s, 5); auto expected = LCW{row_data, row_data, row_data, row_data, row_data}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*col, expected); #undef row_data } template <typename T> class ListsDictionaryLeafTest : public ColumnFactoryTest {}; TYPED_TEST_SUITE(ListsDictionaryLeafTest, cudf::test::FixedWidthTypes); TYPED_TEST(ListsDictionaryLeafTest, FromNonNested) { using DCW = cudf::test::dictionary_column_wrapper<TypeParam>; using offset_t = cudf::test::fixed_width_column_wrapper<cudf::size_type>; auto s = cudf::make_list_scalar(DCW({1, 3, -1, 1, 3}, {1, 1, 0, 1, 1})); auto col = cudf::make_column_from_scalar(*s, 2); DCW leaf({1, 3, -1, 1, 3, 1, 3, -1, 1, 3}, {1, 1, 0, 1, 1, 1, 1, 0, 1, 1}); offset_t offsets{0, 5, 10}; auto mask = cudf::create_null_mask(2, cudf::mask_state::UNALLOCATED); auto expected = cudf::make_lists_column(2, offsets.release(), leaf.release(), 0, std::move(mask)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*col, *expected); } TYPED_TEST(ListsDictionaryLeafTest, FromNested) { using DCW = cudf::test::dictionary_column_wrapper<TypeParam>; using offset_t = cudf::test::fixed_width_column_wrapper<cudf::size_type>; DCW leaf({1, 3, -1, 1, 3, 1, 3, -1, 1, 3}, {1, 1, 0, 1, 1, 1, 1, 0, 1, 1}); offset_t offsets{0, 3, 3, 6, 6, 10}; auto mask = cudf::create_null_mask(5, cudf::mask_state::ALL_VALID); cudf::set_null_mask(static_cast<cudf::bitmask_type*>(mask.data()), 1, 2, false); auto data = cudf::make_lists_column(5, offsets.release(), leaf.release(), 0, std::move(mask)); auto s = cudf::make_list_scalar(*data); auto col = cudf::make_column_from_scalar(*s, 3); DCW leaf2( {1, 3, -1, 1, 3, 1, 3, -1, 1, 3, 1, 3, -1, 1, 3, 1, 3, -1, 1, 3, 1, 3, -1, 1, 3, 1, 3, -1, 1, 3}, {1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1}); offset_t offsets2{0, 3, 3, 6, 6, 10, 13, 13, 16, 16, 20, 23, 23, 26, 26, 30}; auto mask2 = cudf::create_null_mask(15, cudf::mask_state::ALL_VALID); cudf::set_null_mask(static_cast<cudf::bitmask_type*>(mask2.data()), 1, 2, false); cudf::set_null_mask(static_cast<cudf::bitmask_type*>(mask2.data()), 6, 7, false); cudf::set_null_mask(static_cast<cudf::bitmask_type*>(mask2.data()), 11, 12, false); auto nested = cudf::make_lists_column(15, offsets2.release(), leaf2.release(), 3, std::move(mask2)); offset_t offsets3{0, 5, 10, 15}; auto mask3 = cudf::create_null_mask(3, cudf::mask_state::UNALLOCATED); auto expected = cudf::make_lists_column(3, offsets3.release(), std::move(nested), 0, std::move(mask3)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*col, *expected); } class ListsStringLeafTest : public ColumnFactoryTest {}; TEST_F(ListsStringLeafTest, FromNonNested) { using SCW = cudf::test::strings_column_wrapper; using LCW = cudf::test::lists_column_wrapper<cudf::string_view>; using valid_t = std::vector<cudf::valid_type>; auto s = cudf::make_list_scalar(SCW({"xx", "", "z"}, {true, false, true})); auto col = cudf::make_column_from_scalar(*s, 4); auto expected = LCW{LCW({"xx", "", "z"}, valid_t{1, 0, 1}.begin()), LCW({"xx", "", "z"}, valid_t{1, 0, 1}.begin()), LCW({"xx", "", "z"}, valid_t{1, 0, 1}.begin()), LCW({"xx", "", "z"}, valid_t{1, 0, 1}.begin())}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*col, expected); } TEST_F(ListsStringLeafTest, FromNested) { using LCW = cudf::test::lists_column_wrapper<cudf::string_view>; using valid_t = std::vector<cudf::valid_type>; #define row_data \ LCW({LCW{}, \ LCW({"@@", "rapids", "", "四", "ら"}, valid_t{1, 1, 0, 1, 1}.begin()), \ LCW{}, \ LCW({"hello", ""}, valid_t{1, 0}.begin())}, \ valid_t{0, 1, 1, 1}.begin()) auto s = cudf::make_list_scalar(row_data); auto col = cudf::make_column_from_scalar(*s, 3); auto expected = LCW{row_data, row_data, row_data}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*col, expected); #undef row_data } template <typename T> class ListsStructsLeafTest : public ColumnFactoryTest { protected: using SCW = cudf::test::structs_column_wrapper; /** * @brief Create a structs column that contains 3 fields: int, string, List<int> */ template <typename MaskIterator> SCW make_test_structs_column(cudf::test::fixed_width_column_wrapper<T> field1, cudf::test::strings_column_wrapper field2, cudf::test::lists_column_wrapper<T, int32_t> field3, MaskIterator mask) { return SCW{{field1, field2, field3}, mask}; } }; TYPED_TEST_SUITE(ListsStructsLeafTest, cudf::test::FixedWidthTypes); TYPED_TEST(ListsStructsLeafTest, FromNonNested) { using LCWinner_t = cudf::test::lists_column_wrapper<TypeParam, int32_t>; using StringCW = cudf::test::strings_column_wrapper; using offset_t = cudf::test::fixed_width_column_wrapper<cudf::size_type>; using valid_t = std::vector<cudf::valid_type>; auto data = this->make_test_structs_column( {{1, 3, 5, 2, 4}, {1, 0, 1, 0, 1}}, StringCW({"fleur", "flower", "", "花", "はな"}, {true, true, false, true, true}), LCWinner_t({{1, 2}, {}, {4, 5}, {-1}, {}}, valid_t{1, 1, 1, 1, 0}.begin()), valid_t{1, 1, 1, 0, 1}.begin()); auto s = cudf::make_list_scalar(data); auto col = cudf::make_column_from_scalar(*s, 2); auto leaf = this->make_test_structs_column( {{1, 3, 5, 2, 4, 1, 3, 5, 2, 4}, {1, 0, 1, 0, 1, 1, 0, 1, 0, 1}}, StringCW({"fleur", "flower", "", "花", "はな", "fleur", "flower", "", "花", "はな"}, {true, true, false, true, true, true, true, false, true, true}), LCWinner_t({{1, 2}, {}, {4, 5}, {-1}, {}, {1, 2}, {}, {4, 5}, {-1}, {}}, valid_t{1, 1, 1, 1, 0, 1, 1, 1, 1, 0}.begin()), valid_t{1, 1, 1, 0, 1, 1, 1, 1, 0, 1}.begin()); auto expected = cudf::make_lists_column(2, offset_t{0, 5, 10}.release(), leaf.release(), 0, cudf::create_null_mask(2, cudf::mask_state::UNALLOCATED)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*col, *expected); } TYPED_TEST(ListsStructsLeafTest, FromNested) { using LCWinner_t = cudf::test::lists_column_wrapper<TypeParam, int32_t>; using StringCW = cudf::test::strings_column_wrapper; using offset_t = cudf::test::fixed_width_column_wrapper<cudf::size_type>; using valid_t = std::vector<cudf::valid_type>; auto leaf = this->make_test_structs_column( {{1, 2}, {0, 1}}, StringCW({"étoile", "星"}, {true, true}), LCWinner_t({LCWinner_t{}, LCWinner_t{42}}, valid_t{1, 1}.begin()), valid_t{0, 1}.begin()); auto mask = cudf::create_null_mask(3, cudf::mask_state::ALL_VALID); cudf::set_null_mask(static_cast<cudf::bitmask_type*>(mask.data()), 0, 1, false); auto data = cudf::make_lists_column(3, offset_t{0, 0, 1, 2}.release(), leaf.release(), 1, std::move(mask)); auto s = cudf::make_list_scalar(*data); auto col = cudf::make_column_from_scalar(*s, 3); auto leaf2 = this->make_test_structs_column( {{1, 2, 1, 2, 1, 2}, {0, 1, 0, 1, 0, 1}}, StringCW({"étoile", "星", "étoile", "星", "étoile", "星"}, {true, true, true, true, true, true}), LCWinner_t( {LCWinner_t{}, LCWinner_t{42}, LCWinner_t{}, LCWinner_t{42}, LCWinner_t{}, LCWinner_t{42}}, valid_t{1, 1, 1, 1, 1, 1}.begin()), valid_t{0, 1, 0, 1, 0, 1}.begin()); auto mask2 = cudf::create_null_mask(9, cudf::mask_state::ALL_VALID); cudf::set_null_mask(static_cast<cudf::bitmask_type*>(mask2.data()), 0, 1, false); cudf::set_null_mask(static_cast<cudf::bitmask_type*>(mask2.data()), 3, 4, false); cudf::set_null_mask(static_cast<cudf::bitmask_type*>(mask2.data()), 6, 7, false); auto data2 = cudf::make_lists_column( 9, offset_t{0, 0, 1, 2, 2, 3, 4, 4, 5, 6}.release(), leaf2.release(), 3, std::move(mask2)); auto expected = cudf::make_lists_column(3, offset_t{0, 3, 6, 9}.release(), std::move(data2), 0, cudf::create_null_mask(3, cudf::mask_state::UNALLOCATED)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*col, *expected); } class ListsZeroLengthColumnTest : public ColumnFactoryTest { protected: using StructsCW = cudf::test::structs_column_wrapper; StructsCW make_test_structs_column(cudf::test::fixed_width_column_wrapper<int32_t> field1, cudf::test::strings_column_wrapper field2, cudf::test::lists_column_wrapper<int32_t> field3) { return StructsCW{field1, field2, field3}; } }; TEST_F(ListsZeroLengthColumnTest, MixedTypes) { using FCW = cudf::test::fixed_width_column_wrapper<int32_t>; using StringCW = cudf::test::strings_column_wrapper; using LCW = cudf::test::lists_column_wrapper<int32_t>; using offset_t = cudf::test::fixed_width_column_wrapper<cudf::size_type>; { auto s = cudf::make_list_scalar(FCW{1, 2, 3}); auto got = cudf::make_column_from_scalar(*s, 0); auto expected = cudf::make_lists_column(0, offset_t{}.release(), FCW{}.release(), 0, cudf::create_null_mask(0, cudf::mask_state::UNALLOCATED)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*got, *expected); } { auto s = cudf::make_list_scalar(LCW{LCW{1, 2, 3}, LCW{}, LCW{5, 6}}); auto got = cudf::make_column_from_scalar(*s, 0); auto nested = cudf::make_lists_column(0, offset_t{}.release(), FCW{}.release(), 0, cudf::create_null_mask(0, cudf::mask_state::UNALLOCATED)); auto expected = cudf::make_lists_column(0, offset_t{}.release(), std::move(nested), 0, cudf::create_null_mask(0, cudf::mask_state::UNALLOCATED)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*got, *expected); } { auto s = cudf::make_list_scalar( this->make_test_structs_column({1, 2, 3}, StringCW({"x", "", "y"}), LCW{{5, 6}, {}, {7}})); auto got = cudf::make_column_from_scalar(*s, 0); std::vector<std::unique_ptr<cudf::column>> children; children.emplace_back(FCW{}.release()); children.emplace_back(StringCW{}.release()); children.emplace_back(LCW{}.release()); auto nested = cudf::make_structs_column( 0, std::move(children), 0, cudf::create_null_mask(0, cudf::mask_state::UNALLOCATED)); auto expected = cudf::make_lists_column(0, offset_t{}.release(), std::move(nested), 0, cudf::create_null_mask(0, cudf::mask_state::UNALLOCATED)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*got, *expected); } } TEST_F(ListsZeroLengthColumnTest, SuperimposeNulls) { using FCW = cudf::test::fixed_width_column_wrapper<int32_t>; using StringCW = cudf::test::strings_column_wrapper; using LCW = cudf::test::lists_column_wrapper<int32_t>; using offset_t = cudf::test::fixed_width_column_wrapper<cudf::size_type>; auto const lists = [&] { auto child = this ->make_test_structs_column(FCW{1, 2, 3, 4, 5}, StringCW({"a", "b", "c", "d", "e"}), LCW{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11}, {12}}) .release(); auto offsets = offset_t{0, 3, 3, 5}.release(); auto const valid_iter = cudf::test::iterators::null_at(2); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(valid_iter, valid_iter + 3); return cudf::make_lists_column( 3, std::move(offsets), std::move(child), null_count, std::move(null_mask)); }(); auto const expected_child = this ->make_test_structs_column( FCW{1, 2, 3}, StringCW({"a", "b", "c"}), LCW{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}) .release(); auto const expected_offsets = offset_t{0, 3, 3, 3}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*expected_child, lists->child(cudf::lists_column_view::child_column_index)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*expected_offsets, lists->child(cudf::lists_column_view::offsets_column_index)); } void struct_from_scalar(bool is_valid) { using LCW = cudf::test::lists_column_wrapper<int>; cudf::test::fixed_width_column_wrapper<int> col0{1}; cudf::test::strings_column_wrapper col1{"abc"}; cudf::test::lists_column_wrapper<int> col2{{1, 2, 3}}; cudf::test::lists_column_wrapper<int> col3{LCW{}}; std::vector<cudf::column_view> src_children({col0, col1, col2, col3}); auto value = cudf::struct_scalar(src_children, is_valid); cudf::test::structs_column_wrapper struct_col({col0, col1, col2, col3}, {is_valid}); auto const num_rows = 32; auto result = cudf::make_column_from_scalar(value, num_rows); // generate a column of size num_rows std::vector<cudf::column_view> cols; auto iter = thrust::make_counting_iterator(0); std::transform(iter, iter + num_rows, std::back_inserter(cols), [&](int i) { return static_cast<cudf::column_view>(struct_col); }); auto expected = cudf::concatenate(cols); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, *expected); } TEST_F(ColumnFactoryTest, FromStructScalar) { struct_from_scalar(true); } TEST_F(ColumnFactoryTest, FromStructScalarNull) { struct_from_scalar(false); } TEST_F(ColumnFactoryTest, FromScalarErrors) { cudf::string_scalar ss("hello world"); EXPECT_THROW(cudf::make_column_from_scalar(ss, 214748365), std::overflow_error); using FCW = cudf::test::fixed_width_column_wrapper<int8_t>; auto s = cudf::make_list_scalar(FCW({1, 2, 3, 4, 5, 6, 7, 8, 9, 10})); EXPECT_THROW(cudf::make_column_from_scalar(*s, 214748365), std::overflow_error); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/column/column_view_shallow_test.cpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/column/column_view.hpp> #include <cudf/null_mask.hpp> #include <cudf/types.hpp> #include <cudf/utilities/traits.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/type_lists.hpp> #include <thrust/iterator/counting_iterator.h> #include <memory> #include <type_traits> // fixed_width, dict, string, list, struct template <typename T, std::enable_if_t<cudf::is_fixed_width<T>()>* = nullptr> std::unique_ptr<cudf::column> example_column() { auto begin = thrust::make_counting_iterator(1); auto end = thrust::make_counting_iterator(16); return cudf::test::fixed_width_column_wrapper<T>(begin, end).release(); } template <typename T, std::enable_if_t<cudf::is_dictionary<T>()>* = nullptr> std::unique_ptr<cudf::column> example_column() { return cudf::test::dictionary_column_wrapper<std::string>( {"fff", "aaa", "ddd", "bbb", "ccc", "ccc", "ccc", "", ""}, {1, 1, 1, 1, 1, 1, 1, 1, 0}) .release(); } template <typename T, std::enable_if_t<std::is_same_v<T, std::string> or std::is_same_v<T, cudf::string_view>>* = nullptr> std::unique_ptr<cudf::column> example_column() { return cudf::test::strings_column_wrapper( {"fff", "aaa", "ddd", "bbb", "ccc", "ccc", "ccc", "", ""}) .release(); } template <typename T, std::enable_if_t<std::is_same_v<T, cudf::list_view>>* = nullptr> std::unique_ptr<cudf::column> example_column() { return cudf::test::lists_column_wrapper<int>({{1, 2, 3}, {4, 5}, {}, {6, 7, 8}}).release(); } template <typename T, std::enable_if_t<std::is_same_v<T, cudf::struct_view>>* = nullptr> std::unique_ptr<cudf::column> example_column() { auto begin = thrust::make_counting_iterator(1); auto end = thrust::make_counting_iterator(16); auto member_0 = cudf::test::fixed_width_column_wrapper<int32_t>(begin, end); auto member_1 = cudf::test::fixed_width_column_wrapper<int32_t>(begin + 10, end + 10); return cudf::test::structs_column_wrapper({member_0, member_1}).release(); } template <typename T> struct ColumnViewShallowTests : public cudf::test::BaseFixture {}; using AllTypes = cudf::test::Concat<cudf::test::AllTypes, cudf::test::CompoundTypes>; TYPED_TEST_SUITE(ColumnViewShallowTests, AllTypes); // Test for fixed_width, dict, string, list, struct // column_view, column_view = same hash. // column_view, make a copy = same hash. // new column_view from column = same hash // column_view, copy column = diff hash // column_view, diff column = diff hash. // // column_view old, update data + new column_view = same hash. // column_view old, add null_mask + new column_view = diff hash. // column_view old, update nulls + new column_view = same hash. // column_view old, set_null_count + new column_view = same hash. // // column_view, sliced[0, size) = same hash (for split too) // column_view, sliced[n:) = diff hash (for split too) // column_view, bit_cast = diff hash // // mutable_column_view, column_view = same hash // mutable_column_view, modified mutable_column_view = same hash // // update the children column data = same hash // update the children column_views = diff hash TYPED_TEST(ColumnViewShallowTests, shallow_hash_basic) { using namespace cudf::detail; auto col = example_column<TypeParam>(); auto col_view = cudf::column_view{*col}; // same = same hash { EXPECT_EQ(shallow_hash(col_view), shallow_hash(col_view)); } // copy column_view = same hash { auto col_view_copy = col_view; EXPECT_EQ(shallow_hash(col_view), shallow_hash(col_view_copy)); } // new column_view from column = same hash { auto col_view_new = cudf::column_view{*col}; EXPECT_EQ(shallow_hash(col_view), shallow_hash(col_view_new)); } // copy column = diff hash { auto col_new = std::make_unique<cudf::column>(*col); auto col_view_copy = col_new->view(); EXPECT_NE(shallow_hash(col_view), shallow_hash(col_view_copy)); } // column_view, diff column = diff hash. { auto col_diff = example_column<TypeParam>(); auto col_view_diff = cudf::column_view{*col_diff}; EXPECT_NE(shallow_hash(col_view), shallow_hash(col_view_diff)); } } TYPED_TEST(ColumnViewShallowTests, shallow_hash_update_data) { using namespace cudf::detail; auto col = example_column<TypeParam>(); auto col_view = cudf::column_view{*col}; // update data + new column_view = same hash. { // update data by modifying some bits: fixed_width, string, dict, list, struct if constexpr (cudf::is_fixed_width<TypeParam>()) { // Update data auto data = reinterpret_cast<cudf::bitmask_type*>(col->mutable_view().head()); cudf::set_null_mask(data, 2, 64, true); } else { // Update child(0).data auto data = reinterpret_cast<cudf::bitmask_type*>(col->child(0).mutable_view().head()); cudf::set_null_mask(data, 2, 64, true); } auto col_view_new = cudf::column_view{*col}; EXPECT_EQ(shallow_hash(col_view), shallow_hash(col_view_new)); } // add null_mask + new column_view = diff hash. { col->set_null_mask(cudf::create_null_mask(col->size(), cudf::mask_state::ALL_VALID), 0); auto col_view_new = cudf::column_view{*col}; EXPECT_NE(shallow_hash(col_view), shallow_hash(col_view_new)); [[maybe_unused]] auto const nulls = col_view_new.null_count(); EXPECT_NE(shallow_hash(col_view), shallow_hash(col_view_new)); auto col_view_new2 = cudf::column_view{*col}; EXPECT_EQ(shallow_hash(col_view_new), shallow_hash(col_view_new2)); } col_view = cudf::column_view{*col}; // updating after adding null_mask // update nulls + new column_view = same hash. { cudf::set_null_mask(col->mutable_view().null_mask(), 2, 4, false); auto col_view_new = cudf::column_view{*col}; EXPECT_EQ(shallow_hash(col_view), shallow_hash(col_view_new)); } // set_null_count + new column_view = same hash. { col->set_null_count(col->size()); auto col_view_new2 = cudf::column_view{*col}; EXPECT_EQ(shallow_hash(col_view), shallow_hash(col_view_new2)); } } TYPED_TEST(ColumnViewShallowTests, shallow_hash_slice) { using namespace cudf::detail; auto col = example_column<TypeParam>(); auto col_view = cudf::column_view{*col}; // column_view, sliced[0, size) = same hash (for split too) { auto col_sliced = cudf::slice(col_view, {0, col_view.size()}); EXPECT_EQ(shallow_hash(col_view), shallow_hash(col_sliced[0])); auto col_split = cudf::split(col_view, {0}); EXPECT_NE(shallow_hash(col_view), shallow_hash(col_split[0])); EXPECT_EQ(shallow_hash(col_view), shallow_hash(col_split[1])); } // column_view, sliced[n:] = diff hash (for split too) { auto col_sliced = cudf::slice(col_view, {1, col_view.size()}); EXPECT_NE(shallow_hash(col_view), shallow_hash(col_sliced[0])); auto col_split = cudf::split(col_view, {1}); EXPECT_NE(shallow_hash(col_view), shallow_hash(col_split[0])); EXPECT_NE(shallow_hash(col_view), shallow_hash(col_split[1])); } // column_view, col copy sliced[0, 0) = same hash (empty column) { auto col_new = std::make_unique<cudf::column>(*col); auto col_new_view = col_new->view(); auto col_sliced = cudf::slice(col_view, {0, 0, 1, 1, col_view.size(), col_view.size()}); auto col_new_sliced = cudf::slice(col_new_view, {0, 0, 1, 1, col_view.size(), col_view.size()}); EXPECT_EQ(shallow_hash(col_sliced[0]), shallow_hash(col_sliced[1])); EXPECT_EQ(shallow_hash(col_sliced[1]), shallow_hash(col_sliced[2])); EXPECT_EQ(shallow_hash(col_sliced[0]), shallow_hash(col_new_sliced[0])); EXPECT_EQ(shallow_hash(col_sliced[1]), shallow_hash(col_new_sliced[1])); EXPECT_EQ(shallow_hash(col_sliced[2]), shallow_hash(col_new_sliced[2])); } // column_view, bit_cast = diff hash { if constexpr (std::is_integral_v<TypeParam> and not std::is_same_v<TypeParam, bool>) { using newType = std::conditional_t<std::is_signed_v<TypeParam>, std::make_unsigned_t<TypeParam>, std::make_signed_t<TypeParam>>; auto new_type = cudf::data_type(cudf::type_to_id<newType>()); auto col_bitcast = cudf::bit_cast(col_view, new_type); EXPECT_NE(shallow_hash(col_view), shallow_hash(col_bitcast)); } } } TYPED_TEST(ColumnViewShallowTests, shallow_hash_mutable) { using namespace cudf::detail; auto col = example_column<TypeParam>(); auto col_view = cudf::column_view{*col}; // mutable_column_view, column_view = same hash { auto col_mutable = cudf::mutable_column_view{*col}; EXPECT_EQ(shallow_hash(col_mutable), shallow_hash(col_view)); } // mutable_column_view, modified mutable_column_view = same hash // update the children column data = same hash { auto col_mutable = cudf::mutable_column_view{*col}; if constexpr (cudf::is_fixed_width<TypeParam>()) { // Update data auto data = reinterpret_cast<cudf::bitmask_type*>(col->mutable_view().head()); cudf::set_null_mask(data, 1, 32, false); } else { // Update child(0).data auto data = reinterpret_cast<cudf::bitmask_type*>(col->child(0).mutable_view().head()); cudf::set_null_mask(data, 1, 32, false); } EXPECT_EQ(shallow_hash(col_view), shallow_hash(col_mutable)); auto col_mutable_new = cudf::mutable_column_view{*col}; EXPECT_EQ(shallow_hash(col_mutable), shallow_hash(col_mutable_new)); } // update the children column_views = diff hash { if constexpr (cudf::is_nested<TypeParam>()) { col->child(0).set_null_mask( cudf::create_null_mask(col->child(0).size(), cudf::mask_state::ALL_NULL), col->child(0).size()); auto col_child_updated = cudf::mutable_column_view{*col}; EXPECT_NE(shallow_hash(col_view), shallow_hash(col_child_updated)); } } } TYPED_TEST(ColumnViewShallowTests, is_shallow_equivalent_basic) { using namespace cudf::detail; auto col = example_column<TypeParam>(); auto col_view = cudf::column_view{*col}; // same = same hash { EXPECT_TRUE(is_shallow_equivalent(col_view, col_view)); } // copy column_view = same hash { auto col_view_copy = col_view; EXPECT_TRUE(is_shallow_equivalent(col_view, col_view_copy)); } // new column_view from column = same hash { auto col_view_new = cudf::column_view{*col}; EXPECT_TRUE(is_shallow_equivalent(col_view, col_view_new)); } // copy column = diff hash { auto col_new = std::make_unique<cudf::column>(*col); auto col_view_copy = col_new->view(); EXPECT_FALSE(is_shallow_equivalent(col_view, col_view_copy)); } // column_view, diff column = diff hash. { auto col_diff = example_column<TypeParam>(); auto col_view_diff = cudf::column_view{*col_diff}; EXPECT_FALSE(is_shallow_equivalent(col_view, col_view_diff)); } } TYPED_TEST(ColumnViewShallowTests, is_shallow_equivalent_update_data) { using namespace cudf::detail; auto col = example_column<TypeParam>(); auto col_view = cudf::column_view{*col}; // update data + new column_view = same hash. { // update data by modifying some bits: fixed_width, string, dict, list, struct if constexpr (cudf::is_fixed_width<TypeParam>()) { // Update data auto data = reinterpret_cast<cudf::bitmask_type*>(col->mutable_view().head()); cudf::set_null_mask(data, 2, 64, true); } else { // Update child(0).data auto data = reinterpret_cast<cudf::bitmask_type*>(col->child(0).mutable_view().head()); cudf::set_null_mask(data, 2, 64, true); } auto col_view_new = cudf::column_view{*col}; EXPECT_TRUE(is_shallow_equivalent(col_view, col_view_new)); } // add null_mask + new column_view = diff hash. { col->set_null_mask(cudf::create_null_mask(col->size(), cudf::mask_state::ALL_VALID), 0); auto col_view_new = cudf::column_view{*col}; EXPECT_FALSE(is_shallow_equivalent(col_view, col_view_new)); [[maybe_unused]] auto const nulls = col_view_new.null_count(); EXPECT_FALSE(is_shallow_equivalent(col_view, col_view_new)); auto col_view_new2 = cudf::column_view{*col}; EXPECT_TRUE(is_shallow_equivalent(col_view_new, col_view_new2)); } col_view = cudf::column_view{*col}; // updating after adding null_mask // update nulls + new column_view = same hash. { cudf::set_null_mask(col->mutable_view().null_mask(), 2, 4, false); auto col_view_new = cudf::column_view{*col}; EXPECT_TRUE(is_shallow_equivalent(col_view, col_view_new)); } // set_null_count + new column_view = same hash. { col->set_null_count(col->size()); auto col_view_new2 = cudf::column_view{*col}; EXPECT_TRUE(is_shallow_equivalent(col_view, col_view_new2)); } } TYPED_TEST(ColumnViewShallowTests, is_shallow_equivalent_slice) { using namespace cudf::detail; auto col = example_column<TypeParam>(); auto col_view = cudf::column_view{*col}; // column_view, sliced[0, size) = same hash (for split too) { auto col_sliced = cudf::slice(col_view, {0, col_view.size()}); EXPECT_TRUE(is_shallow_equivalent(col_view, col_sliced[0])); auto col_split = cudf::split(col_view, {0}); EXPECT_FALSE(is_shallow_equivalent(col_view, col_split[0])); EXPECT_TRUE(is_shallow_equivalent(col_view, col_split[1])); } // column_view, sliced[n:] = diff hash (for split too) { auto col_sliced = cudf::slice(col_view, {1, col_view.size()}); EXPECT_FALSE(is_shallow_equivalent(col_view, col_sliced[0])); auto col_split = cudf::split(col_view, {1}); EXPECT_FALSE(is_shallow_equivalent(col_view, col_split[0])); EXPECT_FALSE(is_shallow_equivalent(col_view, col_split[1])); } // column_view, col copy sliced[0, 0) = same hash (empty column) { auto col_new = std::make_unique<cudf::column>(*col); auto col_new_view = col_new->view(); auto col_sliced = cudf::slice(col_view, {0, 0, 1, 1, col_view.size(), col_view.size()}); auto col_new_sliced = cudf::slice(col_new_view, {0, 0, 1, 1, col_view.size(), col_view.size()}); EXPECT_TRUE(is_shallow_equivalent(col_sliced[0], col_sliced[1])); EXPECT_TRUE(is_shallow_equivalent(col_sliced[1], col_sliced[2])); EXPECT_TRUE(is_shallow_equivalent(col_sliced[0], col_new_sliced[0])); EXPECT_TRUE(is_shallow_equivalent(col_sliced[1], col_new_sliced[1])); EXPECT_TRUE(is_shallow_equivalent(col_sliced[2], col_new_sliced[2])); } // column_view, bit_cast = diff hash { if constexpr (std::is_integral_v<TypeParam> and not std::is_same_v<TypeParam, bool>) { using newType = std::conditional_t<std::is_signed_v<TypeParam>, std::make_unsigned_t<TypeParam>, std::make_signed_t<TypeParam>>; auto new_type = cudf::data_type(cudf::type_to_id<newType>()); auto col_bitcast = cudf::bit_cast(col_view, new_type); EXPECT_FALSE(is_shallow_equivalent(col_view, col_bitcast)); } } } TYPED_TEST(ColumnViewShallowTests, is_shallow_equivalent_mutable) { using namespace cudf::detail; auto col = example_column<TypeParam>(); auto col_view = cudf::column_view{*col}; // mutable_column_view, column_view = same hash { auto col_mutable = cudf::mutable_column_view{*col}; EXPECT_TRUE(is_shallow_equivalent(col_mutable, col_view)); } // mutable_column_view, modified mutable_column_view = same hash // update the children column data = same hash { auto col_mutable = cudf::mutable_column_view{*col}; if constexpr (cudf::is_fixed_width<TypeParam>()) { // Update data auto data = reinterpret_cast<cudf::bitmask_type*>(col->mutable_view().head()); cudf::set_null_mask(data, 1, 32, false); } else { // Update child(0).data auto data = reinterpret_cast<cudf::bitmask_type*>(col->child(0).mutable_view().head()); cudf::set_null_mask(data, 1, 32, false); } EXPECT_TRUE(is_shallow_equivalent(col_view, col_mutable)); auto col_mutable_new = cudf::mutable_column_view{*col}; EXPECT_TRUE(is_shallow_equivalent(col_mutable, col_mutable_new)); } // update the children column_views = diff hash { if constexpr (cudf::is_nested<TypeParam>()) { col->child(0).set_null_mask( cudf::create_null_mask(col->child(0).size(), cudf::mask_state::ALL_NULL), col->size()); auto col_child_updated = cudf::mutable_column_view{*col}; EXPECT_FALSE(is_shallow_equivalent(col_view, col_child_updated)); } } }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/column/column_device_view_test.cu
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf/column/column.hpp> #include <cudf/column/column_device_view.cuh> #include <cudf/column/column_view.hpp> #include <cudf/copying.hpp> #include <cudf/types.hpp> #include <cudf/utilities/default_stream.hpp> #include <rmm/cuda_stream_view.hpp> #include <rmm/exec_policy.hpp> #include <thrust/copy.h> struct ColumnDeviceViewTest : public cudf::test::BaseFixture {}; TEST_F(ColumnDeviceViewTest, Sample) { using T = int32_t; rmm::cuda_stream_view stream{cudf::get_default_stream()}; cudf::test::fixed_width_column_wrapper<T> input({1, 2, 3, 4, 5, 6}); auto output = cudf::allocate_like(input); auto input_device_view = cudf::column_device_view::create(input, stream); auto output_device_view = cudf::mutable_column_device_view::create(output->mutable_view(), stream); EXPECT_NO_THROW(thrust::copy(rmm::exec_policy(stream), input_device_view->begin<T>(), input_device_view->end<T>(), output_device_view->begin<T>())); CUDF_TEST_EXPECT_COLUMNS_EQUAL(input, output->view()); } TEST_F(ColumnDeviceViewTest, MismatchingType) { using T = int32_t; rmm::cuda_stream_view stream{cudf::get_default_stream()}; cudf::test::fixed_width_column_wrapper<T> input({1, 2, 3, 4, 5, 6}); auto output = cudf::allocate_like(input); auto input_device_view = cudf::column_device_view::create(input, stream); auto output_device_view = cudf::mutable_column_device_view::create(output->mutable_view(), stream); EXPECT_THROW(thrust::copy(rmm::exec_policy(stream), input_device_view->begin<T>(), input_device_view->end<T>(), output_device_view->begin<int64_t>()), cudf::logic_error); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/merge/merge_test.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/column/column_factories.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/merge.hpp> #include <cudf/sorting.hpp> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> #include <cudf/types.hpp> #include <cudf/utilities/type_dispatcher.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_list_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <thrust/iterator/counting_iterator.h> #include <thrust/merge.h> #include <vector> template <typename T> class MergeTest_ : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(MergeTest_, cudf::test::FixedWidthTypes); TYPED_TEST(MergeTest_, MergeIsZeroWhenShouldNotBeZero) { using columnFactoryT = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; columnFactoryT leftColWrap1({1, 2, 3, 4, 5}); cudf::test::fixed_width_column_wrapper<TypeParam> rightColWrap1{}; std::vector<cudf::size_type> key_cols{0}; std::vector<cudf::order> column_order; column_order.push_back(cudf::order::ASCENDING); std::vector<cudf::null_order> null_precedence(column_order.size(), cudf::null_order::AFTER); cudf::table_view left_view{{leftColWrap1}}; cudf::table_view right_view{{rightColWrap1}}; cudf::table_view expected{{leftColWrap1}}; auto result = cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence); int expected_len = 5; ASSERT_EQ(result->num_rows(), expected_len); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, result->view()); } TYPED_TEST(MergeTest_, MismatchedNumColumns) { using columnFactoryT = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; columnFactoryT leftColWrap1({0, 1, 2, 3}); columnFactoryT rightColWrap1({0, 1, 2, 3}); columnFactoryT rightColWrap2({0, 1, 2, 3}); std::vector<cudf::size_type> key_cols{0}; std::vector<cudf::order> column_order{cudf::order::ASCENDING}; std::vector<cudf::null_order> null_precedence{}; cudf::table_view left_view{{leftColWrap1}}; cudf::table_view right_view{{rightColWrap1, rightColWrap2}}; EXPECT_THROW(cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence), cudf::logic_error); } TYPED_TEST(MergeTest_, MismatchedColumnDypes) { cudf::test::fixed_width_column_wrapper<int32_t> leftColWrap1{{0, 1, 2, 3}}; cudf::test::fixed_width_column_wrapper<double> rightColWrap1{{0, 1, 2, 3}}; std::vector<cudf::size_type> key_cols{0}; std::vector<cudf::order> column_order{cudf::order::ASCENDING}; std::vector<cudf::null_order> null_precedence{}; cudf::table_view left_view{{leftColWrap1}}; cudf::table_view right_view{{rightColWrap1}}; EXPECT_THROW(cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence), cudf::logic_error); } TYPED_TEST(MergeTest_, EmptyKeyColumns) { using columnFactoryT = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; columnFactoryT leftColWrap1({0, 1, 2, 3}); columnFactoryT rightColWrap1({0, 1, 2, 3}); std::vector<cudf::size_type> key_cols{}; // empty! this should trigger exception std::vector<cudf::order> column_order{cudf::order::ASCENDING}; std::vector<cudf::null_order> null_precedence{}; cudf::table_view left_view{{leftColWrap1}}; cudf::table_view right_view{{rightColWrap1}}; EXPECT_THROW(cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence), cudf::logic_error); } TYPED_TEST(MergeTest_, TooManyKeyColumns) { using columnFactoryT = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; columnFactoryT leftColWrap1{0, 1, 2, 3}; columnFactoryT rightColWrap1{0, 1, 2, 3}; std::vector<cudf::size_type> key_cols{ 0, 1}; // more keys than columns: this should trigger exception std::vector<cudf::order> column_order{cudf::order::ASCENDING}; std::vector<cudf::null_order> null_precedence{}; cudf::table_view left_view{{leftColWrap1}}; cudf::table_view right_view{{rightColWrap1}}; EXPECT_THROW(cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence), cudf::logic_error); } TYPED_TEST(MergeTest_, EmptyOrderTypes) { using columnFactoryT = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; columnFactoryT leftColWrap1{0, 1, 2, 3}; columnFactoryT rightColWrap1{0, 1, 2, 3}; std::vector<cudf::size_type> key_cols{0}; std::vector<cudf::order> column_order{}; // empty! this should trigger exception std::vector<cudf::null_order> null_precedence{}; cudf::table_view left_view{{leftColWrap1}}; cudf::table_view right_view{{rightColWrap1}}; EXPECT_THROW(cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence), cudf::logic_error); } TYPED_TEST(MergeTest_, TooManyOrderTypes) { using columnFactoryT = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; columnFactoryT leftColWrap1{0, 1, 2, 3}; columnFactoryT rightColWrap1{0, 1, 2, 3}; std::vector<cudf::size_type> key_cols{0}; std::vector<cudf::order> column_order{ cudf::order::ASCENDING, cudf::order::DESCENDING}; // more order types than columns: this should trigger exception std::vector<cudf::null_order> null_precedence{}; cudf::table_view left_view{{leftColWrap1}}; cudf::table_view right_view{{rightColWrap1}}; EXPECT_THROW(cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence), cudf::logic_error); } TYPED_TEST(MergeTest_, MismatchedKeyColumnsAndOrderTypes) { using columnFactoryT = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; columnFactoryT leftColWrap1{0, 1, 2, 3}; columnFactoryT leftColWrap2{0, 1, 2, 3}; columnFactoryT rightColWrap1{0, 1, 2, 3}; columnFactoryT rightColWrap2{0, 1, 2, 3}; cudf::table_view left_view{{leftColWrap1, leftColWrap2}}; cudf::table_view right_view{{rightColWrap1, rightColWrap2}}; std::vector<cudf::size_type> key_cols{0, 1}; std::vector<cudf::order> column_order{cudf::order::ASCENDING}; std::vector<cudf::null_order> null_precedence{}; EXPECT_THROW(cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence), cudf::logic_error); } TYPED_TEST(MergeTest_, NoInputTables) { std::unique_ptr<cudf::table> p_outputTable; CUDF_EXPECT_NO_THROW(p_outputTable = cudf::merge({}, {}, {}, {})); EXPECT_EQ(p_outputTable->num_columns(), 0); } TYPED_TEST(MergeTest_, SingleTableInput) { cudf::size_type inputRows = 40; auto sequence = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i; }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence)::value_type> colWrap1(sequence, sequence + inputRows); std::vector<cudf::size_type> key_cols{0}; std::vector<cudf::order> column_order{cudf::order::ASCENDING}; std::vector<cudf::null_order> null_precedence{}; cudf::table_view left_view{{colWrap1}}; std::unique_ptr<cudf::table> p_outputTable; CUDF_EXPECT_NO_THROW(p_outputTable = cudf::merge({left_view}, key_cols, column_order, null_precedence)); auto input_column_view{left_view.column(0)}; auto output_column_view{p_outputTable->view().column(0)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(input_column_view, output_column_view); } TYPED_TEST(MergeTest_, MergeTwoEmptyTables) { using columnFactoryT = cudf::test::fixed_width_column_wrapper<TypeParam>; std::vector<cudf::size_type> key_cols{0}; std::vector<cudf::order> column_order{cudf::order::ASCENDING}; std::vector<cudf::null_order> null_precedence{}; columnFactoryT leftColWrap1{}; columnFactoryT rightColWrap1{}; cudf::table_view left_view{{leftColWrap1}}; cudf::table_view right_view{{rightColWrap1}}; std::unique_ptr<cudf::table> p_outputTable; CUDF_EXPECT_NO_THROW( p_outputTable = cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence)); CUDF_TEST_EXPECT_TABLES_EQUAL(left_view, p_outputTable->view()); } TYPED_TEST(MergeTest_, MergeWithEmptyColumn) { using columnFactoryT = cudf::test::fixed_width_column_wrapper<TypeParam>; cudf::size_type inputRows = 40; auto sequence = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i; }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence)::value_type> leftColWrap1(sequence, sequence + inputRows); columnFactoryT rightColWrap1{}; // wrapper of empty column <- this might require a (sequence, // sequence) generator std::vector<cudf::size_type> key_cols{0}; std::vector<cudf::order> column_order{cudf::order::ASCENDING}; std::vector<cudf::null_order> null_precedence{}; cudf::table_view left_view{{leftColWrap1}}; cudf::table_view right_view{{rightColWrap1}}; std::unique_ptr<cudf::table> p_outputTable; CUDF_EXPECT_NO_THROW( p_outputTable = cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence)); cudf::column_view const& a_left_tbl_cview{static_cast<cudf::column_view const&>(leftColWrap1)}; cudf::column_view const& a_right_tbl_cview{static_cast<cudf::column_view const&>(rightColWrap1)}; const cudf::size_type outputRows = a_left_tbl_cview.size() + a_right_tbl_cview.size(); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence)::value_type> expectedDataWrap1( sequence, sequence + outputRows); //<- confirmed I can reuse a sequence, wo/ creating overlapping columns! auto expected_column_view{static_cast<cudf::column_view const&>(expectedDataWrap1)}; auto output_column_view{p_outputTable->view().column(0)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view, output_column_view); } TYPED_TEST(MergeTest_, Merge1KeyColumns) { cudf::size_type inputRows = 40; auto sequence0 = cudf::detail::make_counting_transform_iterator(0, [](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) return 0; else return row; }); auto sequence1 = cudf::detail::make_counting_transform_iterator(0, [](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) return 1; else return 2 * row; }); auto sequence2 = cudf::detail::make_counting_transform_iterator(0, [](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) return 0; else return 2 * row + 1; }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence1)::value_type> leftColWrap1(sequence1, sequence1 + inputRows); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence0)::value_type> leftColWrap2(sequence0, sequence0 + inputRows); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence2)::value_type> rightColWrap1(sequence2, sequence2 + inputRows); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence0)::value_type> rightColWrap2( sequence0, sequence0 + inputRows); //<- confirmed I can reuse a sequence, wo/ creating overlapping columns! cudf::table_view left_view{{leftColWrap1, leftColWrap2}}; cudf::table_view right_view{{rightColWrap1, rightColWrap2}}; std::vector<cudf::size_type> key_cols{0}; std::vector<cudf::order> column_order{cudf::order::ASCENDING}; std::vector<cudf::null_order> null_precedence{}; std::unique_ptr<cudf::table> p_outputTable; CUDF_EXPECT_NO_THROW( p_outputTable = cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence)); cudf::column_view const& a_left_tbl_cview{static_cast<cudf::column_view const&>(leftColWrap1)}; cudf::column_view const& a_right_tbl_cview{static_cast<cudf::column_view const&>(rightColWrap1)}; const cudf::size_type outputRows = a_left_tbl_cview.size() + a_right_tbl_cview.size(); auto seq_out1 = cudf::detail::make_counting_transform_iterator(0, [outputRows](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { return (row >= outputRows / 2) ? 1 : 0; } else return row; }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(seq_out1)::value_type> expectedDataWrap1(seq_out1, seq_out1 + outputRows); auto seq_out2 = cudf::detail::make_counting_transform_iterator(0, [outputRows](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) return 0; else return row / 2; }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(seq_out2)::value_type> expectedDataWrap2(seq_out2, seq_out2 + outputRows); auto expected_column_view1{static_cast<cudf::column_view const&>(expectedDataWrap1)}; auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; auto output_column_view1{p_outputTable->view().column(0)}; auto output_column_view2{p_outputTable->view().column(1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view1, output_column_view1); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } TYPED_TEST(MergeTest_, Merge2KeyColumns) { cudf::size_type inputRows = 40; auto sequence1 = cudf::detail::make_counting_transform_iterator(0, [inputRows](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { return (row >= inputRows / 2) ? 1 : 0; } else return row; }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence1)::value_type> leftColWrap1(sequence1, sequence1 + inputRows); auto sequence2 = cudf::detail::make_counting_transform_iterator(0, [inputRows](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { return ((row / (inputRows / 4)) % 2 == 0) ? 1 : 0; } else { return row * 2; } }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence2)::value_type> leftColWrap2(sequence2, sequence2 + inputRows); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence1)::value_type> rightColWrap1(sequence1, sequence1 + inputRows); auto sequence3 = cudf::detail::make_counting_transform_iterator(0, [inputRows](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { return ((row / (inputRows / 4)) % 2 == 0) ? 1 : 0; } else return (2 * row + 1); }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence3)::value_type> rightColWrap2(sequence3, sequence3 + inputRows); cudf::table_view left_view{{leftColWrap1, leftColWrap2}}; cudf::table_view right_view{{rightColWrap1, rightColWrap2}}; std::vector<cudf::size_type> key_cols{0, 1}; std::vector<cudf::order> column_order{cudf::order::ASCENDING, cudf::order::DESCENDING}; std::vector<cudf::null_order> null_precedence{}; std::unique_ptr<cudf::table> p_outputTable; CUDF_EXPECT_NO_THROW( p_outputTable = cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence)); cudf::column_view const& a_left_tbl_cview{static_cast<cudf::column_view const&>(leftColWrap1)}; cudf::column_view const& a_right_tbl_cview{static_cast<cudf::column_view const&>(rightColWrap1)}; const cudf::size_type outputRows = a_left_tbl_cview.size() + a_right_tbl_cview.size(); auto seq_out1 = cudf::detail::make_counting_transform_iterator(0, [outputRows](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { return (row >= outputRows / 2) ? 1 : 0; } else return (row / 2); }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(seq_out1)::value_type> expectedDataWrap1(seq_out1, seq_out1 + outputRows); auto seq_out2 = cudf::detail::make_counting_transform_iterator(0, [outputRows](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { return ((row / (outputRows / 4)) % 2 == 0) ? 1 : 0; } else { return (row % 2 == 0 ? row + 1 : row - 1); } }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(seq_out2)::value_type> expectedDataWrap2(seq_out2, seq_out2 + outputRows); auto expected_column_view1{static_cast<cudf::column_view const&>(expectedDataWrap1)}; auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; auto output_column_view1{p_outputTable->view().column(0)}; auto output_column_view2{p_outputTable->view().column(1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view1, output_column_view1); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } TYPED_TEST(MergeTest_, Merge1KeyNullColumns) { cudf::size_type inputRows = 40; // data: 0 2 4 6 | valid: 1 1 1 0 auto sequence1 = cudf::detail::make_counting_transform_iterator(0, [inputRows](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { return 0; // <- no shortcut to this can avoid compiler errors } else { return row * 2; } }); auto valid_sequence1 = cudf::detail::make_counting_transform_iterator( 0, [inputRows](auto row) { return (row < inputRows - 1); }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence1)::value_type> leftColWrap1(sequence1, sequence1 + inputRows, valid_sequence1); // data: 1 3 5 7 | valid: 1 1 1 0 auto sequence2 = cudf::detail::make_counting_transform_iterator(0, [inputRows](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { return 1; } else return (2 * row + 1); }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence2)::value_type> rightColWrap1(sequence2, sequence2 + inputRows, valid_sequence1); // <- recycle valid_seq1, confirmed okay... std::vector<cudf::size_type> key_cols{0}; std::vector<cudf::order> column_order{cudf::order::ASCENDING}; /*Note: default behavior semantics for null_precedence has changed * wrt legacy code: * * in legacy code missing (default) nulls argument * meant nulls are greatest; i.e., null_order::AFTER (not null_order::BEFORE) * * While new semantics is (see row_operators.cuh: row_lexicographic_comparator::operator() ): * null_order null_precedence = _null_precedence == nullptr ? * null_order::BEFORE: _null_precedence[i]; * * hence missing (default) value meant nulls are smallest * null_order::BEFORE (not null_order::AFTER) (!) */ std::vector<cudf::null_order> null_precedence{cudf::null_order::AFTER}; cudf::table_view left_view{{leftColWrap1}}; cudf::table_view right_view{{rightColWrap1}}; std::unique_ptr<cudf::table> p_outputTable; CUDF_EXPECT_NO_THROW( p_outputTable = cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence)); cudf::column_view const& a_left_tbl_cview{static_cast<cudf::column_view const&>(leftColWrap1)}; cudf::column_view const& a_right_tbl_cview{static_cast<cudf::column_view const&>(rightColWrap1)}; const cudf::size_type outputRows = a_left_tbl_cview.size() + a_right_tbl_cview.size(); const cudf::size_type column1TotalNulls = a_left_tbl_cview.null_count() + a_right_tbl_cview.null_count(); // data: 0 1 2 3 4 5 6 7 | valid: 1 1 1 1 1 1 0 0 auto seq_out1 = cudf::detail::make_counting_transform_iterator(0, [outputRows, column1TotalNulls](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { return (row >= (outputRows - column1TotalNulls) / 2) ? 1 : 0; } else return (row); }); auto valid_seq_out = cudf::detail::make_counting_transform_iterator( 0, [outputRows, column1TotalNulls](auto row) { return (row < (outputRows - column1TotalNulls)); }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(seq_out1)::value_type> expectedDataWrap1(seq_out1, seq_out1 + outputRows, valid_seq_out); auto expected_column_view1{static_cast<cudf::column_view const&>(expectedDataWrap1)}; auto output_column_view1{p_outputTable->view().column(0)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view1, output_column_view1); } TYPED_TEST(MergeTest_, Merge2KeyNullColumns) { cudf::size_type inputRows = 40; // data: 0 1 2 3 | valid: 1 1 1 1 auto sequence1 = cudf::detail::make_counting_transform_iterator(0, [inputRows](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { return (row >= inputRows / 2) ? 1 : 0; } else return (row); }); auto valid_sequence1 = cudf::detail::make_counting_transform_iterator(0, [](auto row) { return true; }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence1)::value_type> leftColWrap1(sequence1, sequence1 + inputRows, valid_sequence1); // if left out: valid_sequence defaults to `false`; // data: 0 2 4 6 | valid: 1 1 1 1 auto sequence2 = cudf::detail::make_counting_transform_iterator(0, [inputRows](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { return ((row / (inputRows / 4)) % 2 == 0) ? 1 : 0; } else { return row * 2; } }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence2)::value_type> leftColWrap2(sequence2, sequence2 + inputRows, valid_sequence1); // data: 0 1 2 3 | valid: 1 1 1 1 cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence1)::value_type> rightColWrap1(sequence1, sequence1 + inputRows, valid_sequence1); // if left out: valid_sequence defaults to `false`; // data: 0 1 2 3 | valid: 0 0 0 0 auto sequence3 = cudf::detail::make_counting_transform_iterator(0, [inputRows](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { return ((row / (inputRows / 4)) % 2 == 0) ? 1 : 0; } else return (row); }); auto valid_sequence0 = cudf::detail::make_counting_transform_iterator(0, [](auto row) { return false; }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence3)::value_type> rightColWrap2(sequence3, sequence3 + inputRows, valid_sequence0); cudf::table_view left_view{{leftColWrap1, leftColWrap2}}; cudf::table_view right_view{{rightColWrap1, rightColWrap2}}; std::vector<cudf::size_type> key_cols{0, 1}; std::vector<cudf::order> column_order{cudf::order::ASCENDING, cudf::order::DESCENDING}; std::vector<cudf::null_order> null_precedence{cudf::null_order::AFTER, cudf::null_order::AFTER}; std::unique_ptr<cudf::table> p_outputTable; CUDF_EXPECT_NO_THROW( p_outputTable = cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence)); cudf::column_view const& a_left_tbl_cview{static_cast<cudf::column_view const&>(leftColWrap1)}; cudf::column_view const& a_right_tbl_cview{static_cast<cudf::column_view const&>(rightColWrap1)}; const cudf::size_type outputRows = a_left_tbl_cview.size() + a_right_tbl_cview.size(); // data: 0 0 1 1 2 2 3 3 | valid: 1 1 1 1 1 1 1 1 auto seq_out1 = cudf::detail::make_counting_transform_iterator(0, [outputRows](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { return (row >= outputRows / 2) ? 1 : 0; } else return (row / 2); }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(seq_out1)::value_type> expectedDataWrap1(seq_out1, seq_out1 + outputRows, valid_sequence1); // data: 0 0 2 1 4 2 6 3 | valid: 0 1 0 1 0 1 0 1 auto seq_out2 = cudf::detail::make_counting_transform_iterator(0, [outputRows](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { return ((row / (outputRows / 8)) % 2 == 0) ? 1 : 0; } else { return (row % 2 != 0 ? 2 * (row / 2) : (row / 2)); } }); auto valid_sequence_out = cudf::detail::make_counting_transform_iterator(0, [outputRows](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { return ((row / (outputRows / 4)) % 2 == 1) ? 1 : 0; } else { return (row % 2 != 0) ? 1 : 0; } }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(seq_out2)::value_type> expectedDataWrap2(seq_out2, seq_out2 + outputRows, valid_sequence_out); auto expected_column_view1{static_cast<cudf::column_view const&>(expectedDataWrap1)}; auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; auto output_column_view1{p_outputTable->view().column(0)}; auto output_column_view2{p_outputTable->view().column(1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view1, output_column_view1); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } TYPED_TEST(MergeTest_, NMerge1KeyColumns) { cudf::size_type inputRows = 64; auto sequence0 = cudf::detail::make_counting_transform_iterator(0, [](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) return 0; else return row; }); auto sequence1 = cudf::detail::make_counting_transform_iterator(0, [inputRows](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) return 1; else return inputRows - row; }); constexpr int num_tables = 63; using PairT0 = cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence0)::value_type>; using PairT1 = cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence1)::value_type>; std::vector<std::pair<PairT0, PairT1>> facts{}; std::vector<cudf::table_view> tables{}; for (int i = 0; i < num_tables; ++i) { facts.emplace_back(std::pair(PairT0(sequence0, sequence0 + inputRows), PairT1(sequence1, sequence1 + inputRows))); tables.push_back(cudf::table_view{{facts.back().first, facts.back().second}}); } std::vector<cudf::size_type> key_cols{0}; std::vector<cudf::order> column_order{cudf::order::ASCENDING}; std::vector<cudf::null_order> null_precedence{}; std::unique_ptr<cudf::table> p_outputTable; EXPECT_NO_THROW(p_outputTable = cudf::merge(tables, key_cols, column_order, null_precedence)); const cudf::size_type outputRows = inputRows * num_tables; auto seq_out1 = cudf::detail::make_counting_transform_iterator(0, [](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { return (0); } else return (row / num_tables); }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(seq_out1)::value_type> expectedDataWrap1(seq_out1, seq_out1 + outputRows); auto seq_out2 = cudf::detail::make_counting_transform_iterator(0, [inputRows](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) return 1; else return inputRows - row / num_tables; }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(seq_out2)::value_type> expectedDataWrap2(seq_out2, seq_out2 + outputRows); auto expected_column_view1{static_cast<cudf::column_view const&>(expectedDataWrap1)}; auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; auto output_column_view1{p_outputTable->view().column(0)}; auto output_column_view2{p_outputTable->view().column(1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view1, output_column_view1); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } class MergeTest : public cudf::test::BaseFixture {}; TEST_F(MergeTest, KeysWithNulls) { cudf::size_type nrows = 13200; // Ensures that thrust::merge uses more than one tile/block auto data_iter = thrust::make_counting_iterator<int32_t>(0); auto valids1 = cudf::detail::make_counting_transform_iterator(0, [](auto row) { return row % 10 != 0; }); cudf::test::fixed_width_column_wrapper<int32_t> data1(data_iter, data_iter + nrows, valids1); auto valids2 = cudf::detail::make_counting_transform_iterator(0, [](auto row) { return row % 15 != 0; }); cudf::test::fixed_width_column_wrapper<int32_t> data2(data_iter, data_iter + nrows, valids2); auto all_data = cudf::concatenate(std::vector<cudf::column_view>{{data1, data2}}); std::vector<cudf::order> column_orders{cudf::order::ASCENDING, cudf::order::DESCENDING}; std::vector<cudf::null_order> null_precedences{cudf::null_order::AFTER, cudf::null_order::BEFORE}; for (auto co : column_orders) for (auto np : null_precedences) { std::vector<cudf::order> column_order{co}; std::vector<cudf::null_order> null_precedence{np}; auto sorted1 = cudf::sort(cudf::table_view({data1}), column_order, null_precedence)->release(); auto col1 = sorted1.front()->view(); auto sorted2 = cudf::sort(cudf::table_view({data2}), column_order, null_precedence)->release(); auto col2 = sorted2.front()->view(); auto result = cudf::merge( {cudf::table_view({col1}), cudf::table_view({col2})}, {0}, column_order, null_precedence); auto sorted_all = cudf::sort(cudf::table_view({all_data->view()}), column_order, null_precedence); CUDF_TEST_EXPECT_COLUMNS_EQUAL(sorted_all->view().column(0), result->view().column(0)); } } TEST_F(MergeTest, Structs) { // clang-format off cudf::test::fixed_width_column_wrapper<int> t0_col0{0, 2, 4, 6, 8}; cudf::test::strings_column_wrapper t0_scol0{"abc", "def", "ghi", "jkl", "mno"}; cudf::test::fixed_width_column_wrapper<float> t0_scol1{1, 2, 3, 4, 5}; cudf::test::structs_column_wrapper t0_col1({t0_scol0, t0_scol1}); cudf::test::fixed_width_column_wrapper<int> t1_col0{1, 3, 5, 7, 9}; cudf::test::strings_column_wrapper t1_scol0{"pqr", "stu", "vwx", "yzz", "000"}; cudf::test::fixed_width_column_wrapper<float> t1_scol1{-1, -2, -3, -4, -5}; cudf::test::structs_column_wrapper t1_col1({t1_scol0, t1_scol1}); cudf::table_view t0({t0_col0, t0_col1}); cudf::table_view t1({t1_col0, t1_col1}); auto result = cudf::merge({t0, t1}, {0}, {cudf::order::ASCENDING}); cudf::test::fixed_width_column_wrapper<int> e_col0{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; cudf::test::strings_column_wrapper e_scol0{"abc", "pqr", "def", "stu", "ghi", "vwx", "jkl", "yzz", "mno", "000"}; cudf::test::fixed_width_column_wrapper<float> e_scol1{1, -1, 2, -2, 3, -3, 4, -4, 5, -5}; cudf::test::structs_column_wrapper e_col1({e_scol0, e_scol1}); cudf::table_view expected({e_col0, e_col1}); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(expected, *result); // clang-format on } TEST_F(MergeTest, StructsWithNulls) { // clang-format off cudf::test::fixed_width_column_wrapper<int> t0_col0{0, 2, 4, 6, 8}; cudf::test::strings_column_wrapper t0_scol0{{"abc", "def", "ghi", "jkl", "mno"}, {1, 1, 0, 0, 1}}; cudf::test::fixed_width_column_wrapper<float> t0_scol1{{1, 2, 3, 4, 5}, {0, 1, 0, 0, 1}}; cudf::test::structs_column_wrapper t0_col1({t0_scol0, t0_scol1}, {1, 0, 1, 0, 0}); cudf::test::fixed_width_column_wrapper<int> t1_col0{1, 3, 5, 7, 9}; cudf::test::strings_column_wrapper t1_scol0{"pqr", "stu", "vwx", "yzz", "000"}; cudf::test::fixed_width_column_wrapper<float> t1_scol1{{-1, -2, -3, -4, -5}, {1, 1, 1, 0, 0}}; cudf::test::structs_column_wrapper t1_col1({t1_scol0, t1_scol1}, {1, 1, 1, 1, 0}); cudf::table_view t0({t0_col0, t0_col1}); cudf::table_view t1({t1_col0, t1_col1}); auto result = cudf::merge({t0, t1}, {0}, {cudf::order::ASCENDING}); cudf::test::fixed_width_column_wrapper<int> e_col0{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; cudf::test::strings_column_wrapper e_scol0{{"abc", "pqr", "def", "stu", "ghi", "vwx", "jkl", "yzz", "mno", "000"}, {1, 1, 0, 1, 0, 1, 0, 1, 0, 1}}; cudf::test::fixed_width_column_wrapper<float> e_scol1{{1, -1, 2, -2, 3, -3, 4, -4, 5, -5}, {0, 1, 0, 1, 0, 1, 0, 0, 0, 0}}; cudf::test::structs_column_wrapper e_col1({e_scol0, e_scol1}, {1, 1, 0, 1, 1, 1, 0, 1, 0, 0}); cudf::table_view expected({e_col0, e_col1}); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(expected, *result); // clang-format on } TEST_F(MergeTest, StructsNested) { // clang-format off cudf::test::fixed_width_column_wrapper<int> t0_col0{8, 6, 4, 2, 0}; cudf::test::strings_column_wrapper t0_scol0{"mno", "jkl", "ghi", "def", "abc"}; cudf::test::fixed_width_column_wrapper<float> t0_scol1{5, 4, 3, 2, 1}; cudf::test::strings_column_wrapper t0_sscol0{"5555", "4444", "333", "22", "1"}; cudf::test::fixed_width_column_wrapper<float> t0_sscol1{50, 40, 30, 20, 10}; cudf::test::structs_column_wrapper t0_scol2({t0_sscol0, t0_sscol1}); cudf::test::structs_column_wrapper t0_col1({t0_scol0, t0_scol1, t0_scol2}); cudf::test::fixed_width_column_wrapper<int> t1_col0{9, 7, 5, 3, 1}; cudf::test::strings_column_wrapper t1_scol0{"000", "yzz", "vwx", "stu", "pqr"}; cudf::test::fixed_width_column_wrapper<float> t1_scol1{-5, -4, -3, -2, -1}; cudf::test::strings_column_wrapper t1_sscol0{"-5555", "-4444", "-333", "-22", "-1"}; cudf::test::fixed_width_column_wrapper<float> t1_sscol1{-50, -40, -30, -20, -10}; cudf::test::structs_column_wrapper t1_scol2({t1_sscol0, t1_sscol1}); cudf::test::structs_column_wrapper t1_col1({t1_scol0, t1_scol1, t1_scol2}); cudf::table_view t0({t0_col0 , t0_col1}); cudf::table_view t1({t1_col0 , t1_col1}); auto result = cudf::merge({t0, t1}, {0}, {cudf::order::DESCENDING}); cudf::test::fixed_width_column_wrapper<int> e_col0{9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; cudf::test::strings_column_wrapper e_scol0{"000", "mno", "yzz", "jkl", "vwx", "ghi", "stu", "def", "pqr", "abc"}; cudf::test::fixed_width_column_wrapper<float> e_scol1{-5, 5, -4, 4, -3, 3, -2, 2, -1, 1}; cudf::test::strings_column_wrapper e_sscol0{"-5555", "5555", "-4444", "4444", "-333", "333", "-22", "22", "-1", "1"}; cudf::test::fixed_width_column_wrapper<float> e_sscol1{-50, 50, -40, 40, -30, 30, -20, 20, -10, 10}; cudf::test::structs_column_wrapper e_scol2({e_sscol0, e_sscol1}); cudf::test::structs_column_wrapper e_col1({e_scol0, e_scol1, e_scol2}); cudf::table_view expected({e_col0, e_col1}); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(expected, *result); // clang-format on } TEST_F(MergeTest, StructsNestedWithNulls) { // clang-format off cudf::test::fixed_width_column_wrapper<int> t0_col0{8, 6, 4, 2, 0}; cudf::test::strings_column_wrapper t0_scol0{"mno", "jkl", "ghi", "def", "abc"}; cudf::test::fixed_width_column_wrapper<float> t0_scol1{{5, 4, 3, 2, 1}, {1, 1, 0, 1, 1}}; cudf::test::strings_column_wrapper t0_sscol0{{"5555", "4444", "333", "22", "1"}, {1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<float> t0_sscol1{50, 40, 30, 20, 10}; cudf::test::structs_column_wrapper t0_scol2({t0_sscol0, t0_sscol1}, {0, 0, 1, 1, 1}); cudf::test::structs_column_wrapper t0_col1({t0_scol0, t0_scol1, t0_scol2}, {0, 0, 1, 1, 1}); cudf::test::fixed_width_column_wrapper<int> t1_col0{9, 7, 5, 3, 1}; cudf::test::strings_column_wrapper t1_scol0{"000", "yzz", "vwx", "stu", "pqr"}; cudf::test::fixed_width_column_wrapper<float> t1_scol1{{-5, -4, -3, -2, -1}, {1, 1, 1, 0, 1}}; cudf::test::strings_column_wrapper t1_sscol0{{"-5555", "-4444", "-333", "-22", "-1"}, {1, 1, 1, 1, 1}}; cudf::test::fixed_width_column_wrapper<float> t1_sscol1{-50, -40, -30, -20, -10}; cudf::test::structs_column_wrapper t1_scol2({t1_sscol0, t1_sscol1}, {1, 1, 1, 1, 0}); cudf::test::structs_column_wrapper t1_col1({t1_scol0, t1_scol1, t1_scol2}); cudf::table_view t0({t0_col0 , t0_col1}); cudf::table_view t1({t1_col0 , t1_col1}); auto result = cudf::merge({t0, t1}, {0}, {cudf::order::DESCENDING}); cudf::test::fixed_width_column_wrapper<int> e_col0{9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; cudf::test::strings_column_wrapper e_scol0{"000", "mno", "yzz", "jkl", "vwx", "ghi", "stu", "def", "pqr", "abc"}; cudf::test::fixed_width_column_wrapper<float> e_scol1{{-5, 5, -4, 4, -3, 3, -2, 2, -1, 1}, { 1, 1, 1, 1, 1, 0, 0, 1, 1, 1}}; cudf::test::strings_column_wrapper e_sscol0{{"-5555", "5555", "-4444", "4444", "-333", "333", "-22", "22", "-1", "1"}, { 1, 0, 1, 0, 1, 1, 1, 1, 0, 0}}; cudf::test::fixed_width_column_wrapper<float> e_sscol1{-50, 50, -40, 40, -30, 30, -20, 20, -10, 10}; cudf::test::structs_column_wrapper e_scol2({e_sscol0, e_sscol1}, {1, 0, 1, 0, 1, 1, 1, 1, 0, 1}); cudf::test::structs_column_wrapper e_col1({e_scol0, e_scol1, e_scol2}, {1, 0, 1, 0, 1, 1, 1, 1, 1, 1}); cudf::table_view expected({e_col0, e_col1}); CUDF_TEST_EXPECT_TABLES_EQUIVALENT(expected, *result); // clang-format on } using lcw = cudf::test::lists_column_wrapper<int32_t>; using cudf::test::iterators::null_at; using cudf::test::iterators::nulls_at; TEST_F(MergeTest, Lists) { auto col1 = lcw{lcw{1}, lcw{3}, lcw{5}, lcw{7}}; auto col2 = lcw{lcw{2}, lcw{4}, lcw{6}, lcw{8}}; auto tbl1 = cudf::table_view{{col1}}; auto tbl2 = cudf::table_view{{col2}}; auto result = cudf::merge({tbl1, tbl2}, {0}, {cudf::order::ASCENDING}); auto expected_col = lcw{lcw{1}, lcw{2}, lcw{3}, lcw{4}, lcw{5}, lcw{6}, lcw{7}, lcw{8}}; auto expected_tbl = cudf::table_view{{expected_col}}; CUDF_TEST_EXPECT_TABLES_EQUIVALENT(expected_tbl, *result); } TEST_F(MergeTest, NestedListsWithNulls) { auto col1 = lcw{{lcw{lcw{1}}, lcw{lcw{3}}, lcw{lcw{5}}, lcw{lcw{7}}}, null_at(3)}; auto col2 = lcw{{lcw{lcw{2}}, lcw{lcw{4}}, lcw{lcw{6}}, lcw{lcw{8}}}, null_at(3)}; auto tbl1 = cudf::table_view{{col1}}; auto tbl2 = cudf::table_view{{col2}}; auto result = cudf::merge({tbl1, tbl2}, {0}, {cudf::order::ASCENDING}, {cudf::null_order::AFTER}); auto expected_col = lcw{{lcw{lcw{1}}, lcw{lcw{2}}, lcw{lcw{3}}, lcw{lcw{4}}, lcw{lcw{5}}, lcw{lcw{6}}, lcw{lcw{7}}, lcw{lcw{8}}}, nulls_at({6, 7})}; auto expected_tbl = cudf::table_view{{expected_col}}; CUDF_TEST_EXPECT_TABLES_EQUIVALENT(expected_tbl, *result); } TEST_F(MergeTest, NestedListsofStructs) { // [ {1}, {2}, {3} ] // [ {5} ] // [ {7}, {8} ] // [ {10} ] auto const col1 = [] { auto const get_structs = [] { auto child0 = cudf::test::fixed_width_column_wrapper<int32_t>{1, 2, 3, 5, 7, 8, 10}; return cudf::test::structs_column_wrapper{{child0}}; }; return cudf::make_lists_column( 4, cudf::test::fixed_width_column_wrapper<int32_t>{0, 3, 4, 6, 7}.release(), get_structs().release(), 0, {}); }(); // [ {4} ] // [ {6} ] // [ {9} ] // [ {11} ] auto const col2 = [] { auto const get_structs = [] { auto child0 = cudf::test::fixed_width_column_wrapper<int32_t>{4, 6, 9, 11}; return cudf::test::structs_column_wrapper{{child0}}; }; return cudf::make_lists_column( 4, cudf::test::fixed_width_column_wrapper<int32_t>{0, 1, 2, 3, 4}.release(), get_structs().release(), 0, {}); }(); auto tbl1 = cudf::table_view{{*col1}}; auto tbl2 = cudf::table_view{{*col2}}; auto result = cudf::merge({tbl1, tbl2}, {0}, {cudf::order::ASCENDING}, {cudf::null_order::AFTER}); // [ {1}, {2}, {3} ] // [ {4} ] // [ {5} ] // [ {6} ] // [ {7}, {8} ] // [ {9} ] // [ {10} ] // [ {11} ] auto const expected_col = [] { auto const get_structs = [] { auto child0 = cudf::test::fixed_width_column_wrapper<int32_t>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; return cudf::test::structs_column_wrapper{{child0}}; }; return cudf::make_lists_column( 8, cudf::test::fixed_width_column_wrapper<int32_t>{0, 3, 4, 5, 6, 8, 9, 10, 11}.release(), get_structs().release(), 0, {}); }(); auto expected_tbl = cudf::table_view{{*expected_col}}; CUDF_TEST_EXPECT_TABLES_EQUIVALENT(expected_tbl, *result); } template <typename T> struct FixedPointTestAllReps : public cudf::test::BaseFixture {}; template <typename T> using fp_wrapper = cudf::test::fixed_point_column_wrapper<T>; TYPED_TEST_SUITE(FixedPointTestAllReps, cudf::test::FixedPointTypes); TYPED_TEST(FixedPointTestAllReps, FixedPointMerge) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; auto const a = fp_wrapper<RepType>{{4, 22, 33, 44, 55}, scale_type{-1}}; auto const b = fp_wrapper<RepType>{{5, 7, 10}, scale_type{-1}}; auto const table_a = cudf::table_view(std::vector<cudf::column_view>{a}); auto const table_b = cudf::table_view(std::vector<cudf::column_view>{b}); auto const tables = std::vector<cudf::table_view>{table_a, table_b}; auto const key_cols = std::vector<cudf::size_type>{0}; auto const order = std::vector<cudf::order>{cudf::order::ASCENDING}; auto const exp = fp_wrapper<RepType>{{4, 5, 7, 10, 22, 33, 44, 55}, scale_type{-1}}; auto const exp_table = cudf::table_view(std::vector<cudf::column_view>{exp}); auto const result = cudf::merge(tables, key_cols, order); CUDF_TEST_EXPECT_COLUMNS_EQUAL(exp_table.column(0), result->view().column(0)); } CUDF_TEST_PROGRAM_MAIN()
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/merge/merge_dictionary_test.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/dictionary/dictionary_column_view.hpp> #include <cudf/dictionary/encode.hpp> #include <cudf/merge.hpp> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <vector> struct MergeDictionaryTest : public cudf::test::BaseFixture {}; TEST_F(MergeDictionaryTest, Merge1Column) { cudf::test::strings_column_wrapper left_w({"ab", "ab", "cd", "de", "de", "fg", "gh", "gh"}); auto left = cudf::dictionary::encode(left_w); cudf::test::strings_column_wrapper right_w({"ab", "cd", "de", "fg", "gh"}); auto right = cudf::dictionary::encode(right_w); cudf::table_view left_view{{left->view()}}; cudf::table_view right_view{{right->view()}}; std::vector<cudf::size_type> key_cols{0}; std::vector<cudf::order> column_order{cudf::order::ASCENDING}; std::vector<cudf::null_order> null_precedence{}; auto result = cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence); cudf::test::strings_column_wrapper expected_w( {"ab", "ab", "ab", "cd", "cd", "de", "de", "de", "fg", "fg", "gh", "gh", "gh"}); auto expected = cudf::dictionary::encode(expected_w); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected->view(), result->get_column(0).view()); } TEST_F(MergeDictionaryTest, Merge2Columns) { cudf::test::strings_column_wrapper left_w1({"ab", "bc", "cd", "de", "de", "fg", "fg"}); auto left1 = cudf::dictionary::encode(left_w1); cudf::test::strings_column_wrapper left_w2({"zy", "zy", "xw", "xw", "vu", "vu", "ts"}); auto left2 = cudf::dictionary::encode(left_w2); cudf::table_view left_view{{left1->view(), left2->view()}}; cudf::test::strings_column_wrapper right_w1({"ab", "ab", "bc", "cd", "de", "fg"}); auto right1 = cudf::dictionary::encode(right_w1); cudf::test::strings_column_wrapper right_w2({"zy", "xw", "xw", "vu", "ts", "ts"}); auto right2 = cudf::dictionary::encode(right_w2); cudf::table_view right_view{{right1->view(), right2->view()}}; std::vector<cudf::size_type> key_cols{0, 1}; std::vector<cudf::order> column_order{cudf::order::ASCENDING, cudf::order::DESCENDING}; std::vector<cudf::null_order> null_precedence{}; auto result = cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence); auto decoded1 = cudf::dictionary::decode(result->get_column(0).view()); auto decoded2 = cudf::dictionary::decode(result->get_column(1).view()); cudf::test::strings_column_wrapper expected_1( {"ab", "ab", "ab", "bc", "bc", "cd", "cd", "de", "de", "de", "fg", "fg", "fg"}); cudf::test::strings_column_wrapper expected_2( {"zy", "zy", "xw", "zy", "xw", "xw", "vu", "xw", "vu", "ts", "vu", "ts", "ts"}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_1, decoded1->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_2, decoded2->view()); left_view = cudf::table_view{{left1->view(), left_w2}}; right_view = cudf::table_view{{right1->view(), right_w2}}; result = cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence); decoded1 = cudf::dictionary::decode(result->get_column(0).view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_1, decoded1->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_2, result->get_column(1).view()); left_view = cudf::table_view{{left_w1, left2->view()}}; right_view = cudf::table_view{{right_w1, right2->view()}}; result = cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence); decoded2 = cudf::dictionary::decode(result->get_column(1).view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_1, result->get_column(0).view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_2, decoded2->view()); } TEST_F(MergeDictionaryTest, WithNulls) { cudf::test::fixed_width_column_wrapper<int8_t> left_w1({1, 2, 2, 4, 4, 5, 0}, {1, 1, 1, 1, 1, 1, 0}); auto left1 = cudf::dictionary::encode(left_w1); cudf::test::fixed_width_column_wrapper<int64_t> left_w2({1000, 1000, 800, 500, 500, 100, 0}, {1, 1, 1, 1, 1, 1, 0}); auto left2 = cudf::dictionary::encode(left_w2); cudf::table_view left_view{{left1->view(), left2->view()}}; cudf::test::fixed_width_column_wrapper<int8_t> right_w1({1, 1, 2, 4, 5, 0}, {1, 1, 1, 1, 1, 0}); auto right1 = cudf::dictionary::encode(right_w1); cudf::test::fixed_width_column_wrapper<int64_t> right_w2({1000, 800, 800, 400, 100, 0}, {1, 1, 1, 1, 1, 0}); auto right2 = cudf::dictionary::encode(right_w2); cudf::table_view right_view{{right1->view(), right2->view()}}; std::vector<cudf::size_type> key_cols{0, 1}; std::vector<cudf::order> column_order{cudf::order::ASCENDING, cudf::order::DESCENDING}; std::vector<cudf::null_order> null_precedence{cudf::null_order::AFTER, cudf::null_order::BEFORE}; auto result = cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence); auto decoded1 = cudf::dictionary::decode(result->get_column(0).view()); auto decoded2 = cudf::dictionary::decode(result->get_column(1).view()); cudf::test::fixed_width_column_wrapper<int8_t> expected_1( {1, 1, 1, 2, 2, 2, 4, 4, 4, 5, 5, 0, 0}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0}); cudf::test::fixed_width_column_wrapper<int64_t> expected_2( {1000, 1000, 800, 1000, 800, 800, 500, 500, 400, 100, 100, 0, 0}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_1, decoded1->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_2, decoded2->view()); left_view = cudf::table_view{{left1->view(), left_w2}}; right_view = cudf::table_view{{right1->view(), right_w2}}; result = cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence); decoded1 = cudf::dictionary::decode(result->get_column(0).view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_1, decoded1->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_2, result->get_column(1).view()); left_view = cudf::table_view{{left_w1, left2->view()}}; right_view = cudf::table_view{{right_w1, right2->view()}}; result = cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence); decoded2 = cudf::dictionary::decode(result->get_column(1).view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_1, result->get_column(0).view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_2, decoded2->view()); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/merge/merge_string_test.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/column/column_factories.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/merge.hpp> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> #include <cudf/types.hpp> #include <cudf/utilities/type_dispatcher.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/type_lists.hpp> #include <algorithm> #include <cassert> #include <initializer_list> #include <limits> #include <memory> #include <vector> #include <gtest/gtest.h> using cudf::test::fixed_width_column_wrapper; using cudf::test::strings_column_wrapper; template <typename T> class MergeStringTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(MergeStringTest, cudf::test::FixedWidthTypes); TYPED_TEST(MergeStringTest, Merge1StringKeyColumns) { strings_column_wrapper leftColWrap1({"ab", "bc", "cd", "de", "ef", "fg", "gh", "hi"}); cudf::size_type inputRows1 = static_cast<cudf::column_view const&>(leftColWrap1).size(); auto sequence0 = cudf::detail::make_counting_transform_iterator(0, [](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) return 0; else return row; }); fixed_width_column_wrapper<TypeParam, typename decltype(sequence0)::value_type> leftColWrap2( sequence0, sequence0 + inputRows1); strings_column_wrapper rightColWrap1({"ac", "bd", "ce", "df", "eg", "fh", "gi", "hj"}); cudf::size_type inputRows2 = static_cast<cudf::column_view const&>(rightColWrap1).size(); fixed_width_column_wrapper<TypeParam, typename decltype(sequence0)::value_type> rightColWrap2( sequence0, sequence0 + inputRows2); cudf::table_view left_view{{leftColWrap1, leftColWrap2}}; cudf::table_view right_view{{rightColWrap1, rightColWrap2}}; std::vector<cudf::size_type> key_cols{0}; std::vector<cudf::order> column_order{cudf::order::ASCENDING}; std::vector<cudf::null_order> null_precedence{}; std::unique_ptr<cudf::table> p_outputTable; EXPECT_NO_THROW(p_outputTable = cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence)); cudf::column_view const& a_left_tbl_cview{static_cast<cudf::column_view const&>(leftColWrap1)}; cudf::column_view const& a_right_tbl_cview{static_cast<cudf::column_view const&>(rightColWrap1)}; const cudf::size_type outputRows = a_left_tbl_cview.size() + a_right_tbl_cview.size(); strings_column_wrapper expectedDataWrap1({"ab", "ac", "bc", "bd", "cd", "ce", "de", "df", "ef", "eg", "fg", "fh", "gh", "gi", "hi", "hj"}); auto seq_out2 = cudf::detail::make_counting_transform_iterator(0, [outputRows](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) return 0; else return row / 2; }); fixed_width_column_wrapper<TypeParam, typename decltype(seq_out2)::value_type> expectedDataWrap2( seq_out2, seq_out2 + outputRows); auto expected_column_view1{static_cast<cudf::column_view const&>(expectedDataWrap1)}; auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; auto output_column_view1{p_outputTable->view().column(0)}; auto output_column_view2{p_outputTable->view().column(1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view1, output_column_view1); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } // rename test <TestName> as DISABLED_<TestName> to disable: // Example: TYPED_TEST(MergeStringTest, DISABLED_Merge2StringKeyColumns) // TYPED_TEST(MergeStringTest, Merge2StringKeyColumns) { strings_column_wrapper leftColWrap1({"ab", "bc", "cd", "de", "ef", "fg", "gh", "hi"}); strings_column_wrapper leftColWrap3({"zy", "yx", "xw", "wv", "vu", "ut", "ts", "sr"}); cudf::size_type inputRows = static_cast<cudf::column_view const&>(leftColWrap1).size(); EXPECT_EQ(inputRows, static_cast<cudf::column_view const&>(leftColWrap3).size()); auto sequence_l = cudf::detail::make_counting_transform_iterator(0, [](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) return 1; else return 2 * row; }); fixed_width_column_wrapper<TypeParam, typename decltype(sequence_l)::value_type> leftColWrap2( sequence_l, sequence_l + inputRows); cudf::table_view left_view{{leftColWrap1, leftColWrap2, leftColWrap3}}; strings_column_wrapper rightColWrap1({"ac", "bd", "ce", "df", "eg", "fh", "gi", "hj"}); EXPECT_EQ(inputRows, static_cast<cudf::column_view const&>(rightColWrap1).size()); auto sequence_r = cudf::detail::make_counting_transform_iterator(0, [](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) return 0; else return 2 * row + 1; }); fixed_width_column_wrapper<TypeParam, typename decltype(sequence_r)::value_type> rightColWrap2( sequence_r, sequence_r + inputRows); strings_column_wrapper rightColWrap3({"zx", "yw", "xv", "wu", "vt", "us", "tr", "sp"}); EXPECT_EQ(inputRows, static_cast<cudf::column_view const&>(rightColWrap3).size()); cudf::table_view right_view{{rightColWrap1, rightColWrap2, rightColWrap3}}; std::vector<cudf::size_type> key_cols{0, 2}; std::vector<cudf::order> column_order{cudf::order::ASCENDING, cudf::order::DESCENDING}; std::vector<cudf::null_order> null_precedence{}; std::unique_ptr<cudf::table> p_outputTable; EXPECT_NO_THROW(p_outputTable = cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence)); cudf::column_view const& a_left_tbl_cview{static_cast<cudf::column_view const&>(leftColWrap1)}; cudf::column_view const& a_right_tbl_cview{static_cast<cudf::column_view const&>(rightColWrap1)}; const cudf::size_type outputRows = a_left_tbl_cview.size() + a_right_tbl_cview.size(); strings_column_wrapper expectedDataWrap1({"ab", "ac", "bc", "bd", "cd", "ce", "de", "df", "ef", "eg", "fg", "fh", "gh", "gi", "hi", "hj"}); auto seq_out2 = cudf::detail::make_counting_transform_iterator( 0, [bool8 = (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8)](auto row) { return bool8 ? static_cast<decltype(row)>(row % 2 == 0) : row; }); fixed_width_column_wrapper<TypeParam, typename decltype(seq_out2)::value_type> expectedDataWrap2( seq_out2, seq_out2 + outputRows); strings_column_wrapper expectedDataWrap3({"zy", "zx", "yx", "yw", "xw", "xv", "wv", "wu", "vu", "vt", "ut", "us", "ts", "tr", "sr", "sp"}); auto expected_column_view1{static_cast<cudf::column_view const&>(expectedDataWrap1)}; auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; auto expected_column_view3{static_cast<cudf::column_view const&>(expectedDataWrap3)}; auto output_column_view1{p_outputTable->view().column(0)}; auto output_column_view2{p_outputTable->view().column(1)}; auto output_column_view3{p_outputTable->view().column(2)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view1, output_column_view1); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view3, output_column_view3); } TYPED_TEST(MergeStringTest, Merge1StringKeyNullColumns) { // data: "ab", "bc", "cd", "de" | valid: 1 1 1 0 strings_column_wrapper leftColWrap1({"ab", "bc", "cd", "de", "ef", "fg", "gh", "hi"}, {1, 1, 1, 1, 1, 1, 1, 0}); cudf::size_type inputRows = static_cast<cudf::column_view const&>(leftColWrap1).size(); auto sequence0 = cudf::detail::make_counting_transform_iterator(0, [](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) return 0; else return row; }); fixed_width_column_wrapper<TypeParam, typename decltype(sequence0)::value_type> leftColWrap2( sequence0, sequence0 + inputRows); cudf::table_view left_view{{leftColWrap1, leftColWrap2}}; // data: "ac", "bd", "ce", "df" | valid: 1 1 1 0 strings_column_wrapper rightColWrap1({"ac", "bd", "ce", "df", "eg", "fh", "gi", "hj"}, {1, 1, 1, 1, 1, 1, 1, 0}); fixed_width_column_wrapper<TypeParam, typename decltype(sequence0)::value_type> rightColWrap2( sequence0, sequence0 + inputRows); cudf::table_view right_view{{rightColWrap1, rightColWrap2}}; std::vector<cudf::size_type> key_cols{0}; std::vector<cudf::order> column_order{cudf::order::ASCENDING}; std::vector<cudf::null_order> null_precedence{cudf::null_order::AFTER}; std::unique_ptr<cudf::table> p_outputTable; EXPECT_NO_THROW(p_outputTable = cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence)); cudf::column_view const& a_left_tbl_cview{static_cast<cudf::column_view const&>(leftColWrap1)}; cudf::column_view const& a_right_tbl_cview{static_cast<cudf::column_view const&>(rightColWrap1)}; const cudf::size_type outputRows = a_left_tbl_cview.size() + a_right_tbl_cview.size(); // data: "ab", "ac", "bc", "bd", "cd", "ce", "de", "df" | valid: 1 1 1 1 1 1 0 0 strings_column_wrapper expectedDataWrap1({"ab", "ac", "bc", "bd", "cd", "ce", "de", "df", "ef", "eg", "fg", "fh", "gh", "gi", "hi", "hj"}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0}); auto seq_out2 = cudf::detail::make_counting_transform_iterator(0, [outputRows](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) return 0; else return row / 2; }); fixed_width_column_wrapper<TypeParam, typename decltype(seq_out2)::value_type> expectedDataWrap2( seq_out2, seq_out2 + outputRows); auto expected_column_view1{static_cast<cudf::column_view const&>(expectedDataWrap1)}; auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; auto output_column_view1{p_outputTable->view().column(0)}; auto output_column_view2{p_outputTable->view().column(1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view1, output_column_view1); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } TYPED_TEST(MergeStringTest, Merge2StringKeyNullColumns) { strings_column_wrapper leftColWrap1({"ab", "bc", "cd", "de", "ef", "fg", "gh", "hi"}, {1, 1, 1, 1, 1, 1, 1, 0}); strings_column_wrapper leftColWrap3({"zy", "yx", "xw", "wv", "vu", "ut", "ts", "sr"}, {1, 1, 1, 1, 1, 1, 1, 0}); cudf::size_type inputRows = static_cast<cudf::column_view const&>(leftColWrap1).size(); EXPECT_EQ(inputRows, static_cast<cudf::column_view const&>(leftColWrap3).size()); auto sequence_l = cudf::detail::make_counting_transform_iterator(0, [](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) return 1; else return 2 * row; }); fixed_width_column_wrapper<TypeParam, typename decltype(sequence_l)::value_type> leftColWrap2( sequence_l, sequence_l + inputRows); cudf::table_view left_view{{leftColWrap1, leftColWrap2, leftColWrap3}}; strings_column_wrapper rightColWrap1({"ac", "bd", "ce", "df", "eg", "fh", "gi", "hj"}, {1, 1, 1, 1, 1, 1, 1, 0}); EXPECT_EQ(inputRows, static_cast<cudf::column_view const&>(rightColWrap1).size()); auto sequence_r = cudf::detail::make_counting_transform_iterator(0, [](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) return 0; else return 2 * row + 1; }); fixed_width_column_wrapper<TypeParam, typename decltype(sequence_r)::value_type> rightColWrap2( sequence_r, sequence_r + inputRows); strings_column_wrapper rightColWrap3({"zx", "yw", "xv", "wu", "vt", "us", "tr", "sp"}, {1, 1, 1, 1, 1, 1, 1, 0}); EXPECT_EQ(inputRows, static_cast<cudf::column_view const&>(rightColWrap3).size()); cudf::table_view right_view{{rightColWrap1, rightColWrap2, rightColWrap3}}; std::vector<cudf::size_type> key_cols{0, 2}; std::vector<cudf::order> column_order{cudf::order::ASCENDING, cudf::order::DESCENDING}; std::vector<cudf::null_order> null_precedence{cudf::null_order::AFTER, cudf::null_order::BEFORE}; std::unique_ptr<cudf::table> p_outputTable; EXPECT_NO_THROW(p_outputTable = cudf::merge({left_view, right_view}, key_cols, column_order, null_precedence)); cudf::column_view const& a_left_tbl_cview{static_cast<cudf::column_view const&>(leftColWrap1)}; cudf::column_view const& a_right_tbl_cview{static_cast<cudf::column_view const&>(rightColWrap1)}; const cudf::size_type outputRows = a_left_tbl_cview.size() + a_right_tbl_cview.size(); strings_column_wrapper expectedDataWrap1({"ab", "ac", "bc", "bd", "cd", "ce", "de", "df", "ef", "eg", "fg", "fh", "gh", "gi", "hi", "hj"}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0}); auto seq_out2 = cudf::detail::make_counting_transform_iterator( 0, [bool8 = (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8)](auto row) { return bool8 ? static_cast<decltype(row)>(row % 2 == 0) : row; }); fixed_width_column_wrapper<TypeParam, typename decltype(seq_out2)::value_type> expectedDataWrap2( seq_out2, seq_out2 + outputRows); strings_column_wrapper expectedDataWrap3({"zy", "zx", "yx", "yw", "xw", "xv", "wv", "wu", "vu", "vt", "ut", "us", "ts", "tr", "sr", "sp"}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0}); auto expected_column_view1{static_cast<cudf::column_view const&>(expectedDataWrap1)}; auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; auto expected_column_view3{static_cast<cudf::column_view const&>(expectedDataWrap3)}; auto output_column_view1{p_outputTable->view().column(0)}; auto output_column_view2{p_outputTable->view().column(1)}; auto output_column_view3{p_outputTable->view().column(2)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view1, output_column_view1); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view3, output_column_view3); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/datetime/datetime_ops_test.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/column/column_factories.hpp> #include <cudf/column/column_view.hpp> #include <cudf/datetime.hpp> #include <cudf/scalar/scalar_factories.hpp> #include <cudf/types.hpp> #include <cudf/wrappers/timestamps.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/timestamp_utilities.cuh> #include <cudf_test/type_lists.hpp> #include <thrust/transform.h> #define XXX false // stub for null values constexpr cudf::test::debug_output_level verbosity{cudf::test::debug_output_level::ALL_ERRORS}; template <typename T> struct NonTimestampTest : public cudf::test::BaseFixture { cudf::data_type type() { return cudf::data_type{cudf::type_to_id<T>()}; } }; using NonTimestampTypes = cudf::test::Concat<cudf::test::NumericTypes, cudf::test::StringTypes, cudf::test::DurationTypes>; TYPED_TEST_SUITE(NonTimestampTest, NonTimestampTypes); TYPED_TEST(NonTimestampTest, TestThrowsOnNonTimestamp) { using T = TypeParam; using namespace cudf::test; using namespace cudf::datetime; using namespace cuda::std::chrono; cudf::data_type dtype{cudf::type_to_id<T>()}; cudf::column col{dtype, 0, rmm::device_buffer{}, rmm::device_buffer{}, 0}; EXPECT_THROW(extract_year(col), cudf::logic_error); EXPECT_THROW(extract_month(col), cudf::logic_error); EXPECT_THROW(extract_day(col), cudf::logic_error); EXPECT_THROW(extract_weekday(col), cudf::logic_error); EXPECT_THROW(extract_hour(col), cudf::logic_error); EXPECT_THROW(extract_minute(col), cudf::logic_error); EXPECT_THROW(extract_second(col), cudf::logic_error); EXPECT_THROW(extract_millisecond_fraction(col), cudf::logic_error); EXPECT_THROW(extract_microsecond_fraction(col), cudf::logic_error); EXPECT_THROW(extract_nanosecond_fraction(col), cudf::logic_error); EXPECT_THROW(last_day_of_month(col), cudf::logic_error); EXPECT_THROW(day_of_year(col), cudf::logic_error); EXPECT_THROW(add_calendrical_months(col, *cudf::make_empty_column(cudf::type_id::INT16)), cudf::logic_error); } struct BasicDatetimeOpsTest : public cudf::test::BaseFixture {}; TEST_F(BasicDatetimeOpsTest, TestExtractingDatetimeComponents) { using namespace cudf::test; using namespace cudf::datetime; using namespace cuda::std::chrono; auto timestamps_D = cudf::test::fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ -1528, // 1965-10-26 GMT 17716, // 2018-07-04 GMT 19382 // 2023-01-25 GMT }; auto timestamps_s = cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep>{ -131968728, // 1965-10-26 14:01:12 GMT 1530705600, // 2018-07-04 12:00:00 GMT 1674631932 // 2023-01-25 07:32:12 GMT }; auto timestamps_ms = cudf::test::fixed_width_column_wrapper<cudf::timestamp_ms, cudf::timestamp_ms::rep>{ -131968727238, // 1965-10-26 14:01:12.762 GMT 1530705600000, // 2018-07-04 12:00:00.000 GMT 1674631932929 // 2023-01-25 07:32:12.929 GMT }; auto timestamps_ns = cudf::test::fixed_width_column_wrapper<cudf::timestamp_ns, cudf::timestamp_ns::rep>{ -23324234, // 1969-12-31 23:59:59.976675766 GMT 23432424, // 1970-01-01 00:00:00.023432424 GMT 987234623 // 1970-01-01 00:00:00.987234623 GMT }; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_year(timestamps_D), fixed_width_column_wrapper<int16_t>{1965, 2018, 2023}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_year(timestamps_s), fixed_width_column_wrapper<int16_t>{1965, 2018, 2023}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_year(timestamps_ms), fixed_width_column_wrapper<int16_t>{1965, 2018, 2023}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_year(timestamps_ns), fixed_width_column_wrapper<int16_t>{1969, 1970, 1970}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_month(timestamps_D), fixed_width_column_wrapper<int16_t>{10, 7, 1}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_month(timestamps_s), fixed_width_column_wrapper<int16_t>{10, 7, 1}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_month(timestamps_ms), fixed_width_column_wrapper<int16_t>{10, 7, 1}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_month(timestamps_ns), fixed_width_column_wrapper<int16_t>{12, 1, 1}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_day(timestamps_D), fixed_width_column_wrapper<int16_t>{26, 4, 25}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_day(timestamps_s), fixed_width_column_wrapper<int16_t>{26, 4, 25}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_day(timestamps_ms), fixed_width_column_wrapper<int16_t>{26, 4, 25}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_day(timestamps_ns), fixed_width_column_wrapper<int16_t>{31, 1, 1}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_weekday(timestamps_D), fixed_width_column_wrapper<int16_t>{2, 3, 3}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_weekday(timestamps_s), fixed_width_column_wrapper<int16_t>{2, 3, 3}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_weekday(timestamps_ms), fixed_width_column_wrapper<int16_t>{2, 3, 3}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_weekday(timestamps_ms), fixed_width_column_wrapper<int16_t>{2, 3, 3}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_hour(timestamps_D), fixed_width_column_wrapper<int16_t>{0, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_hour(timestamps_s), fixed_width_column_wrapper<int16_t>{14, 12, 7}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_hour(timestamps_ms), fixed_width_column_wrapper<int16_t>{14, 12, 7}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_hour(timestamps_ns), fixed_width_column_wrapper<int16_t>{23, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_minute(timestamps_D), fixed_width_column_wrapper<int16_t>{0, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_minute(timestamps_s), fixed_width_column_wrapper<int16_t>{1, 0, 32}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_minute(timestamps_ms), fixed_width_column_wrapper<int16_t>{1, 0, 32}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_minute(timestamps_ns), fixed_width_column_wrapper<int16_t>{59, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_second(timestamps_D), fixed_width_column_wrapper<int16_t>{0, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_second(timestamps_s), fixed_width_column_wrapper<int16_t>{12, 0, 12}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_second(timestamps_ms), fixed_width_column_wrapper<int16_t>{12, 0, 12}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_minute(timestamps_ns), fixed_width_column_wrapper<int16_t>{59, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_millisecond_fraction(timestamps_D), fixed_width_column_wrapper<int16_t>{0, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_millisecond_fraction(timestamps_s), fixed_width_column_wrapper<int16_t>{0, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_millisecond_fraction(timestamps_ms), fixed_width_column_wrapper<int16_t>{762, 0, 929}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_millisecond_fraction(timestamps_ns), fixed_width_column_wrapper<int16_t>{976, 23, 987}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_microsecond_fraction(timestamps_D), fixed_width_column_wrapper<int16_t>{0, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_microsecond_fraction(timestamps_s), fixed_width_column_wrapper<int16_t>{0, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_microsecond_fraction(timestamps_ms), fixed_width_column_wrapper<int16_t>{0, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_microsecond_fraction(timestamps_ns), fixed_width_column_wrapper<int16_t>{675, 432, 234}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_nanosecond_fraction(timestamps_D), fixed_width_column_wrapper<int16_t>{0, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_nanosecond_fraction(timestamps_s), fixed_width_column_wrapper<int16_t>{0, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_nanosecond_fraction(timestamps_ms), fixed_width_column_wrapper<int16_t>{0, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_nanosecond_fraction(timestamps_ns), fixed_width_column_wrapper<int16_t>{766, 424, 623}); } template <typename T> struct TypedDatetimeOpsTest : public cudf::test::BaseFixture { cudf::size_type size() { return cudf::size_type(10); } cudf::data_type type() { return cudf::data_type{cudf::type_to_id<T>()}; } }; TYPED_TEST_SUITE(TypedDatetimeOpsTest, cudf::test::TimestampTypes); TYPED_TEST(TypedDatetimeOpsTest, TestEmptyColumns) { using T = TypeParam; using namespace cudf::test; using namespace cudf::datetime; using namespace cuda::std::chrono; auto int16s_dtype = cudf::data_type{cudf::type_to_id<int16_t>()}; auto timestamps_dtype = cudf::data_type{cudf::type_to_id<T>()}; cudf::column int16s{int16s_dtype, 0, rmm::device_buffer{}, rmm::device_buffer{}, 0}; cudf::column timestamps{timestamps_dtype, 0, rmm::device_buffer{}, rmm::device_buffer{}, 0}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_year(timestamps), int16s); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_month(timestamps), int16s); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_day(timestamps), int16s); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_weekday(timestamps), int16s); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_hour(timestamps), int16s); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_minute(timestamps), int16s); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_second(timestamps), int16s); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_millisecond_fraction(timestamps), int16s); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_microsecond_fraction(timestamps), int16s); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_nanosecond_fraction(timestamps), int16s); } TYPED_TEST(TypedDatetimeOpsTest, TestExtractingGeneratedDatetimeComponents) { using T = TypeParam; using namespace cudf::test; using namespace cudf::datetime; using namespace cuda::std::chrono; auto start = milliseconds(-2500000000000); // Sat, 11 Oct 1890 19:33:20 GMT auto stop = milliseconds(2500000000000); // Mon, 22 Mar 2049 04:26:40 GMT auto timestamps = generate_timestamps<T>(this->size(), time_point_ms(start), time_point_ms(stop)); auto expected_years = fixed_width_column_wrapper<int16_t>{1890, 1906, 1922, 1938, 1954, 1970, 1985, 2001, 2017, 2033}; auto expected_months = fixed_width_column_wrapper<int16_t>{10, 8, 6, 4, 2, 1, 11, 9, 7, 5}; auto expected_days = fixed_width_column_wrapper<int16_t>{11, 16, 20, 24, 26, 1, 5, 9, 14, 18}; auto expected_weekdays = fixed_width_column_wrapper<int16_t>{6, 4, 2, 7, 5, 4, 2, 7, 5, 3}; auto expected_hours = fixed_width_column_wrapper<int16_t>{19, 20, 21, 22, 23, 0, 0, 1, 2, 3}; auto expected_minutes = fixed_width_column_wrapper<int16_t>{33, 26, 20, 13, 6, 0, 53, 46, 40, 33}; auto expected_seconds = fixed_width_column_wrapper<int16_t>{20, 40, 0, 20, 40, 0, 20, 40, 0, 20}; // Special cases for timestamp_D: zero out the expected hh/mm/ss cols if (std::is_same_v<TypeParam, cudf::timestamp_D>) { expected_hours = fixed_width_column_wrapper<int16_t>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; expected_minutes = fixed_width_column_wrapper<int16_t>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; expected_seconds = fixed_width_column_wrapper<int16_t>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; } CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_year(timestamps), expected_years); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_month(timestamps), expected_months); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_day(timestamps), expected_days); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_weekday(timestamps), expected_weekdays); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_hour(timestamps), expected_hours); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_minute(timestamps), expected_minutes); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_second(timestamps), expected_seconds); } TYPED_TEST(TypedDatetimeOpsTest, TestExtractingGeneratedNullableDatetimeComponents) { using T = TypeParam; using namespace cudf::test; using namespace cudf::datetime; using namespace cuda::std::chrono; auto start = milliseconds(-2500000000000); // Sat, 11 Oct 1890 19:33:20 GMT auto stop = milliseconds(2500000000000); // Mon, 22 Mar 2049 04:26:40 GMT auto timestamps = generate_timestamps<T, true>(this->size(), time_point_ms(start), time_point_ms(stop)); auto expected_years = fixed_width_column_wrapper<int16_t>{ {1890, 1906, 1922, 1938, 1954, 1970, 1985, 2001, 2017, 2033}, {true, false, true, false, true, false, true, false, true, false}}; auto expected_months = fixed_width_column_wrapper<int16_t>{ {10, 8, 6, 4, 2, 1, 11, 9, 7, 5}, {true, false, true, false, true, false, true, false, true, false}}; auto expected_days = fixed_width_column_wrapper<int16_t>{ {11, 16, 20, 24, 26, 1, 5, 9, 14, 18}, {true, false, true, false, true, false, true, false, true, false}}; auto expected_weekdays = fixed_width_column_wrapper<int16_t>{ {6, 4, 2, 7, 5, 4, 2, 7, 5, 3}, {true, false, true, false, true, false, true, false, true, false}}; auto expected_hours = fixed_width_column_wrapper<int16_t>{ {19, 20, 21, 22, 23, 0, 0, 1, 2, 3}, {true, false, true, false, true, false, true, false, true, false}}; auto expected_minutes = fixed_width_column_wrapper<int16_t>{ {33, 26, 20, 13, 6, 0, 53, 46, 40, 33}, {true, false, true, false, true, false, true, false, true, false}}; auto expected_seconds = fixed_width_column_wrapper<int16_t>{ {20, 40, 0, 20, 40, 0, 20, 40, 0, 20}, {true, false, true, false, true, false, true, false, true, false}}; // Special cases for timestamp_D: zero out the expected hh/mm/ss cols if (std::is_same_v<TypeParam, cudf::timestamp_D>) { expected_hours = fixed_width_column_wrapper<int16_t>{ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {true, false, true, false, true, false, true, false, true, false}}; expected_minutes = fixed_width_column_wrapper<int16_t>{ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {true, false, true, false, true, false, true, false, true, false}}; expected_seconds = fixed_width_column_wrapper<int16_t>{ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {true, false, true, false, true, false, true, false, true, false}}; } CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_year(timestamps), expected_years); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_month(timestamps), expected_months); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_day(timestamps), expected_days); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_weekday(timestamps), expected_weekdays); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_hour(timestamps), expected_hours); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_minute(timestamps), expected_minutes); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_second(timestamps), expected_seconds); } TEST_F(BasicDatetimeOpsTest, TestLastDayOfMonthWithSeconds) { using namespace cudf::test; using namespace cudf::datetime; using namespace cuda::std::chrono; // Time in seconds since epoch // Dates converted using epochconverter.com auto timestamps_s = fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep>{ 662688000L, // 1991-01-01 00:00:00 GMT 949496401L, // 2000-02-02 13:00:01 GMT - leap year 4106854801L, // 2100-02-21 01:00:01 GMT - not a leap year 1582391837L, // 2020-02-22 17:17:17 GMT - leap year 1363046401L, // 2013-03-12 00:00:01 GMT 1302696000L, // 2011-04-13 12:00:00 GMT 1495800001L, // 2017-05-26 12:00:01 GMT 1056931201L, // 2003-06-30 00:00:01 GMT - already last day 1031961599L, // 2002-09-13 23:59:59 GMT 0L, // This is the UNIX epoch - 1970-01-01 -131968728L, // 1965-10-26 14:01:12 GMT }; CUDF_TEST_EXPECT_COLUMNS_EQUAL( *last_day_of_month(timestamps_s), fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ 7700, // 1991-01-31 11016, // 2000-02-29 47540, // 2100-02-28 18321, // 2020-02-29 15795, // 2013-03-31 15094, // 2011-04-30 17317, // 2017-05-31 12233, // 2003-06-30 11960, // 2002-09-30 30, // This is the UNIX epoch - when rounded up becomes 1970-01-31 -1523 // 1965-10-31 }, verbosity); } TEST_F(BasicDatetimeOpsTest, TestLastDayOfMonthWithDate) { using namespace cudf::test; using namespace cudf::datetime; using namespace cuda::std::chrono; // Time in days since epoch // Dates converted using epochconverter.com // Make some nullable fields as well auto timestamps_d = fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ { 999, // Random nullable field 0, // This is the UNIX epoch - 1970-01-01 44376, // 2091-07-01 00:00:00 GMT 47695, // 2100-08-02 00:00:00 GMT 3, // Random nullable field 66068, // 2150-11-21 00:00:00 GMT 22270, // 2030-12-22 00:00:00 GMT 111, // Random nullable field }, {false, true, true, true, false, true, true, false}, }; CUDF_TEST_EXPECT_COLUMNS_EQUAL( *last_day_of_month(timestamps_d), fixed_width_column_wrapper<cudf::timestamp_D, cudf::timestamp_D::rep>{ { 999, // Random nullable field 30, // This is the UNIX epoch - when rounded up becomes 1970-01-31 44406, // 2091-07-31 47724, // 2100-08-31 3, // Random nullable field 66077, // 2150-11-30 22279, // 2030-12-31 111 // Random nullable field }, {false, true, true, true, false, true, true, false}}, verbosity); } TEST_F(BasicDatetimeOpsTest, TestDayOfYearWithDate) { using namespace cudf::test; using namespace cudf::datetime; using namespace cuda::std::chrono; // Day number in the year // Dates converted using epochconverter.com // Make some nullable fields as well auto timestamps_d = cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep>{ { 999L, // Random nullable field 0L, // This is the UNIX epoch - 1970-01-01 1577865600L, // 2020-01-01 00:00:00 GMT 1581667200L, // 2020-02-14 00:00:00 GMT 3L, // Random nullable field 1609401600L, // 2020-12-31 00:00:00 GMT 4133923200L, // 2100-12-31 00:00:00 GMT 111L, // Random nullable field -2180188800L // 1900-11-30 00:00:00 GMT }, {false, true, true, true, false, true, true, false, true}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*day_of_year(timestamps_d), fixed_width_column_wrapper<int16_t>{ { 999, // Random nullable field 1, // Number of year days until UNIX epoch time 1, // Number of year days until 2020-01-01 45, // Number of year days until 2020-02-14 3, // Random nullable field 366, // Number of year days until 2020-12-31 365, // Number of year days until 2100-12-31 111, // Random nullable field 334 // Number of year days until 1900-11-30 }, {false, true, true, true, false, true, true, false, true}, }, verbosity); } TEST_F(BasicDatetimeOpsTest, TestDayOfYearWithEmptyColumn) { using namespace cudf::test; using namespace cudf::datetime; using namespace cuda::std::chrono; // Create an empty column auto timestamps_d = fixed_width_column_wrapper<cudf::timestamp_s>{}; auto out_col = day_of_year(timestamps_d); EXPECT_EQ(out_col->size(), 0); } TEST_F(BasicDatetimeOpsTest, TestAddMonthsWithInvalidColType) { using namespace cudf::test; using namespace cudf::datetime; using namespace cuda::std::chrono; // Time in seconds since epoch // Dates converted using epochconverter.com auto timestamps_s = cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep>{ 662688000L // 1991-01-01 00:00:00 GMT }; // Months has to be an INT16 or INT32 type EXPECT_NO_THROW( add_calendrical_months(timestamps_s, cudf::test::fixed_width_column_wrapper<int32_t>{-2})); EXPECT_NO_THROW( add_calendrical_months(timestamps_s, cudf::test::fixed_width_column_wrapper<int16_t>{-2})); EXPECT_THROW( add_calendrical_months(timestamps_s, cudf::test::fixed_width_column_wrapper<int8_t>{-2}), cudf::logic_error); EXPECT_THROW( add_calendrical_months(timestamps_s, cudf::test::fixed_width_column_wrapper<int64_t>{-2}), cudf::logic_error); } TEST_F(BasicDatetimeOpsTest, TestAddMonthsWithInvalidScalarType) { using namespace cudf::test; using namespace cudf::datetime; using namespace cuda::std::chrono; // Time in seconds since epoch // Dates converted using epochconverter.com auto timestamps_s = fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep>{ 662688000L // 1991-01-01 00:00:00 GMT }; // Months has to be an INT16 or INT32 type EXPECT_NO_THROW(add_calendrical_months(timestamps_s, *cudf::make_fixed_width_scalar<int32_t>(5))); EXPECT_NO_THROW( add_calendrical_months(timestamps_s, *cudf::make_fixed_width_scalar<int16_t>(-3))); EXPECT_THROW(add_calendrical_months(timestamps_s, *cudf::make_fixed_width_scalar<int8_t>(-3)), cudf::logic_error); EXPECT_THROW(add_calendrical_months(timestamps_s, *cudf::make_fixed_width_scalar<int64_t>(-3)), cudf::logic_error); } TEST_F(BasicDatetimeOpsTest, TestAddMonthsWithIncorrectColSizes) { using namespace cudf::test; using namespace cudf::datetime; using namespace cuda::std::chrono; // Time in seconds since epoch // Dates converted using epochconverter.com auto timestamps_s = cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep>{ 662688000L // 1991-01-01 00:00:00 GMT }; // Provide more number of months rows than timestamp rows auto months = cudf::test::fixed_width_column_wrapper<int16_t>{-2, 3}; EXPECT_THROW(add_calendrical_months(timestamps_s, months), cudf::logic_error); } using ValidMonthIntegerType = cudf::test::Types<int16_t, int32_t>; template <typename T> struct TypedAddMonthsTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(TypedAddMonthsTest, ValidMonthIntegerType); TYPED_TEST(TypedAddMonthsTest, TestAddMonthsWithSeconds) { using namespace cudf::test; using namespace cudf::datetime; using namespace cuda::std::chrono; // Time in seconds since epoch // Dates converted using epochconverter.com auto timestamps_s = cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep>{ 662688000L, // 1991-01-01 00:00:00 GMT 949496401L, // 2000-02-02 13:00:01 GMT - leap year 1056931201L, // 2003-06-30 00:00:01 GMT - last day of month 1056964201L, // 2003-06-30 09:10:01 GMT - last day of month 1056974401L, // 2003-06-30 12:00:01 GMT - last day of month 1056994021L, // 2003-06-30 17:27:01 GMT - last day of month 0L, // This is the UNIX epoch - 1970-01-01 0L, // This is the UNIX epoch - 1970-01-01 -131586588L, // 1965-10-31 00:10:12 GMT -131550590L, // 1965-10-31 10:10:10 GMT -131544000L, // 1965-10-31 12:00:00 GMT -131536728L // 1965-10-31 14:01:12 GMT }; auto const months = cudf::test::fixed_width_column_wrapper<TypeParam>{-2, 6, -1, 1, -4, 8, -2, 10, 4, -20, 1, 3}; auto const expected = cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep>{ 657417600L, // 1990-11-01 00:00:00 GMT 965221201L, // 2000-08-02 13:00:01 GMT 1054252801L, // 2003-05-30 00:00:01 GMT 1059556201L, // 2003-07-30 09:10:01 GMT 1046433601L, // 2003-02-28 12:00:01 GMT 1078075621L, // 2004-02-29 17:27:01 GMT -5270400L, // 1969-11-01 26265600L, // 1970-11-01 -121218588L, // 1966-02-28 00:10:12 GMT -184254590L, // 1964-02-29 10:10:10 GMT -128952000L, // 1965-11-30 12:00:00 GMT -123587928L // 1966-01-31 14:01:12 GMT }; CUDF_TEST_EXPECT_COLUMNS_EQUAL( *add_calendrical_months(timestamps_s, months), expected, verbosity); } TYPED_TEST(TypedAddMonthsTest, TestAddScalarMonthsWithSeconds) { using namespace cudf::test; using namespace cudf::datetime; using namespace cuda::std::chrono; // Time in seconds since epoch // Dates converted using epochconverter.com auto timestamps_s = fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep>{ 662688000L, // 1991-01-01 00:00:00 GMT 949496401L, // 2000-02-02 13:00:01 GMT - leap year 1056964201L, // 2003-06-30 09:10:01 GMT - last day of month 0L, // This is the UNIX epoch - 1970-01-01 -131536728L // 1965-10-31 14:01:12 GMT - last day of month }; // add auto const months1 = cudf::make_fixed_width_scalar<TypeParam>(11); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *add_calendrical_months(timestamps_s, *months1), fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep>{ 691545600L, // 1991-12-01 00:00:00 GMT 978440401L, // 2001-01-02 13:00:01 GMT 1085908201L, // 2004-05-30 09:10:01 GMT 28857600L, // 1970-12-01 00:00:00 GMT -102679128L, // 1966-09-30 14:01:12 GMT }, verbosity); // subtract auto const months2 = cudf::make_fixed_width_scalar<TypeParam>(-20); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *add_calendrical_months(timestamps_s, *months2), fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep>{ 609984000L, // 1989-05-01 00:00:00 GMT 896792401L, // 1998-06-02 13:00:01 GMT 1004433001L, // 2001-10-30 09:10:01 GMT -52704000L, // 1968-05-01 00:00:00 GMT -184240728L, // 1964-02-29 14:01:12 GMT - lands on a leap year february }, verbosity); } TYPED_TEST(TypedAddMonthsTest, TestAddMonthsWithSecondsAndNullValues) { using namespace cudf::test; using namespace cudf::datetime; using namespace cuda::std::chrono; // Time in seconds since epoch // Dates converted using epochconverter.com auto timestamps_s = cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep>{ { 662688000L, // 1991-01-01 00:00:00 GMT 949496401L, // 2000-02-02 13:00:01 GMT - leap year 1056931201L, // 2003-06-30 00:00:01 GMT - last day of month 1056964201L, // 2003-06-30 09:10:01 GMT - last day of month 1056974401L, // 2003-06-30 12:00:01 GMT - last day of month 1056994021L, // 2003-06-30 17:27:01 GMT - last day of month 0L, // This is the UNIX epoch - 1970-01-01 0L, // This is the UNIX epoch - 1970-01-01 -131586588L, // 1965-10-31 00:10:12 GMT -131550590L, // 1965-10-31 10:10:10 GMT -131544000L, // 1965-10-31 12:00:00 GMT -131536728L // 1965-10-31 14:01:12 GMT }, {true, false, true, false, true, false, true, false, true, true, true, true}}; auto const months = cudf::test::fixed_width_column_wrapper<TypeParam>{ {-2, 6, -1, 1, -4, 8, -2, 10, 4, -20, 1, 3}, {false, true, true, false, true, true, true, true, true, true, true, true}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL( *add_calendrical_months(timestamps_s, months), cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep>{ { 0L, // null value 0L, // null value 1054252801L, // 2003-05-30 00:00:01 GMT 0L, // null value 1046433601L, // 2003-02-28 12:00:01 GMT 0L, // null value -5270400L, // 1969-11-01 0L, // null value -121218588L, // 1966-02-28 00:10:12 GMT -184254590L, // 1964-02-29 10:10:10 GMT -128952000L, // 1965-11-30 12:00:00 GMT -123587928L // 1966-01-31 14:01:12 GMT }, {false, false, true, false, true, false, true, false, true, true, true, true}}, verbosity); } TYPED_TEST(TypedAddMonthsTest, TestAddScalarMonthsWithSecondsWithNulls) { using namespace cudf::test; using namespace cudf::datetime; using namespace cuda::std::chrono; // Time in seconds since epoch // Dates converted using epochconverter.com auto timestamps_s = fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep>( { 662688000L, // 1991-01-01 00:00:00 GMT 0L, // NULL 1056964201L, // 2003-06-30 09:10:01 GMT - last day of month 0L, // This is the UNIX epoch - 1970-01-01 0L // NULL }, iterators::nulls_at({1, 4})); // valid scalar auto const months1 = cudf::make_fixed_width_scalar<TypeParam>(11); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *add_calendrical_months(timestamps_s, *months1), fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep>( { 691545600L, // 1991-12-01 00:00:00 GMT 0L, // NULL 1085908201L, // 2004-05-30 09:10:01 GMT 28857600L, // 1970-12-01 00:00:00 GMT 0L, // NULL }, iterators::nulls_at({1, 4})), verbosity); // null scalar auto const months2 = cudf::make_default_constructed_scalar(cudf::data_type{cudf::type_to_id<TypeParam>()}); CUDF_TEST_EXPECT_COLUMNS_EQUAL( *add_calendrical_months(timestamps_s, *months2), fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep>({0L, 0L, 0L, 0L, 0L}, iterators::all_nulls()), verbosity); } TEST_F(BasicDatetimeOpsTest, TestIsLeapYear) { using namespace cudf::test; using namespace cudf::datetime; using namespace cuda::std::chrono; // Time in seconds since epoch // Dates converted using epochconverter.com auto timestamps_s = cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep>{ { 1594332839L, // 2020-07-09 10:13:59 GMT - leap year 0L, // null 915148800L, // 1999-01-01 00:00:00 GMT - non leap year -11663029161L, // 1600-5-31 05:40:39 GMT - leap year 707904541L, // 1992-06-07 08:09:01 GMT - leap year -2181005247L, // 1900-11-20 09:12:33 GMT - non leap year 0L, // UNIX EPOCH 1970-01-01 00:00:00 GMT - non leap year -12212553600L, // First full year of Gregorian Calendar 1583-01-01 00:00:00 - non-leap-year 0L, // null 13591632822L, // 2400-09-13 13:33:42 GMT - leap year 4539564243L, // 2113-11-08 06:04:03 GMT - non leap year 0L // null }, {true, false, true, true, true, true, true, true, false, true, true, false}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL( *is_leap_year(timestamps_s), cudf::test::fixed_width_column_wrapper<bool>{ {true, XXX, false, true, true, false, false, false, XXX, true, false, XXX}, {true, false, true, true, true, true, true, true, false, true, true, false}}); } TEST_F(BasicDatetimeOpsTest, TestDaysInMonths) { using namespace cudf::test; using namespace cudf::datetime; using namespace cuda::std::chrono; auto timestamps_s = cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep>{ { 0L, // NULL -1887541682L, // 1910-03-10 10:51:58 0L, // NULL -1251006943L, // 1930-05-11 18:04:17 -932134638L, // 1940-06-18 09:42:42 -614354877L, // 1950-07-14 09:52:03 -296070394L, // 1960-08-14 06:13:26 22840404L, // 1970-09-22 08:33:24 339817190L, // 1980-10-08 01:39:50 657928062L, // 1990-11-06 21:47:42 976630837L, // 2000-12-12 14:20:37 1294699018L, // 2011-01-10 22:36:58 1613970182L, // 2021-02-22 05:03:02 - non leap year February 1930963331L, // 2031-03-11 02:42:11 2249867102L, // 2041-04-18 03:05:02 951426858L, // 2000-02-24 21:14:18 - leap year February }, iterators::nulls_at({0, 2})}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*days_in_month(timestamps_s), cudf::test::fixed_width_column_wrapper<int16_t>{ {-1, 31, -1, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28, 31, 30, 29}, iterators::nulls_at({0, 2})}); } TEST_F(BasicDatetimeOpsTest, TestQuarter) { using namespace cudf::test; using namespace cudf::datetime; using namespace cuda::std::chrono; using namespace cudf::test::iterators; // Time in seconds since epoch // Dates converted using epochconverter.com auto timestamps_s = cudf::test::fixed_width_column_wrapper<cudf::timestamp_s, cudf::timestamp_s::rep>{ { 1594332839L, // 2020-07-09 10:13:59 GMT 0L, // null 915148800L, // 1999-01-01 00:00:00 GMT -11663029161L, // 1600-5-31 05:40:39 GMT 707904541L, // 1992-06-07 08:09:01 GMT -2181005247L, // 1900-11-20 09:12:33 GMT 0L, // UNIX EPOCH 1970-01-01 00:00:00 GMT -12212553600L, // First full year of Gregorian Calendar 1583-01-01 00:00:00 0L, // null 13591632822L, // 2400-09-13 13:33:42 GMT 4539564243L, // 2113-11-08 06:04:03 GMT 0L, // null 1608581568L, // 2020-12-21 08:12:48 GMT 1584821568L, // 2020-03-21 08:12:48 GMT }, nulls_at({1, 8, 11})}; auto quarter = cudf::test::fixed_width_column_wrapper<int16_t>{ {3, 0 /*null*/, 1, 2, 2, 4, 1, 1, 0 /*null*/, 3, 4, 0 /*null*/, 4, 1}, nulls_at({1, 8, 11})}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*extract_quarter(timestamps_s), quarter); } TYPED_TEST(TypedDatetimeOpsTest, TestCeilDatetime) { using T = TypeParam; using namespace cudf::test; using namespace cudf::datetime; using namespace cuda::std::chrono; auto start = milliseconds(-2500000000000); // Sat, 11 Oct 1890 19:33:20 GMT auto stop = milliseconds(2500000000000); // Mon, 22 Mar 2049 04:26:40 GMT auto const input = generate_timestamps<T>(this->size(), time_point_ms(start), time_point_ms(stop)); auto const timestamps = to_host<T>(input).first; std::vector<T> ceiled_day(timestamps.size()); thrust::transform(timestamps.begin(), timestamps.end(), ceiled_day.begin(), [](auto i) { return time_point_cast<typename T::duration>(ceil<days>(i)); }); auto expected_day = fixed_width_column_wrapper<T, typename T::duration::rep>(ceiled_day.begin(), ceiled_day.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*ceil_datetimes(input, rounding_frequency::DAY), expected_day); std::vector<T> ceiled_hour(timestamps.size()); thrust::transform(timestamps.begin(), timestamps.end(), ceiled_hour.begin(), [](auto i) { return time_point_cast<typename T::duration>(ceil<hours>(i)); }); auto expected_hour = fixed_width_column_wrapper<T, typename T::duration::rep>(ceiled_hour.begin(), ceiled_hour.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*ceil_datetimes(input, rounding_frequency::HOUR), expected_hour); std::vector<T> ceiled_minute(timestamps.size()); std::transform(timestamps.begin(), timestamps.end(), ceiled_minute.begin(), [](auto i) { return time_point_cast<typename T::duration>(ceil<minutes>(i)); }); auto expected_minute = fixed_width_column_wrapper<T, typename T::duration::rep>( ceiled_minute.begin(), ceiled_minute.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*ceil_datetimes(input, rounding_frequency::MINUTE), expected_minute); std::vector<T> ceiled_second(timestamps.size()); std::transform(timestamps.begin(), timestamps.end(), ceiled_second.begin(), [](auto i) { return time_point_cast<typename T::duration>(ceil<seconds>(i)); }); auto expected_second = fixed_width_column_wrapper<T, typename T::duration::rep>( ceiled_second.begin(), ceiled_second.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*ceil_datetimes(input, rounding_frequency::SECOND), expected_second); std::vector<T> ceiled_millisecond(timestamps.size()); std::transform(timestamps.begin(), timestamps.end(), ceiled_millisecond.begin(), [](auto i) { return time_point_cast<typename T::duration>(ceil<milliseconds>(i)); }); auto expected_millisecond = fixed_width_column_wrapper<T, typename T::duration::rep>( ceiled_millisecond.begin(), ceiled_millisecond.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*ceil_datetimes(input, rounding_frequency::MILLISECOND), expected_millisecond); std::vector<T> ceiled_microsecond(timestamps.size()); std::transform(timestamps.begin(), timestamps.end(), ceiled_microsecond.begin(), [](auto i) { return time_point_cast<typename T::duration>(ceil<microseconds>(i)); }); auto expected_microsecond = fixed_width_column_wrapper<T, typename T::duration::rep>( ceiled_microsecond.begin(), ceiled_microsecond.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*ceil_datetimes(input, rounding_frequency::MICROSECOND), expected_microsecond); std::vector<T> ceiled_nanosecond(timestamps.size()); std::transform(timestamps.begin(), timestamps.end(), ceiled_nanosecond.begin(), [](auto i) { return time_point_cast<typename T::duration>(ceil<nanoseconds>(i)); }); auto expected_nanosecond = fixed_width_column_wrapper<T, typename T::duration::rep>( ceiled_nanosecond.begin(), ceiled_nanosecond.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*ceil_datetimes(input, rounding_frequency::NANOSECOND), expected_nanosecond); } TYPED_TEST(TypedDatetimeOpsTest, TestFloorDatetime) { using T = TypeParam; using namespace cudf::test; using namespace cudf::datetime; using namespace cuda::std::chrono; auto start = milliseconds(-2500000000000); // Sat, 11 Oct 1890 19:33:20 GMT auto stop = milliseconds(2500000000000); // Mon, 22 Mar 2049 04:26:40 GMT auto const input = generate_timestamps<T>(this->size(), time_point_ms(start), time_point_ms(stop)); auto const timestamps = to_host<T>(input).first; std::vector<T> floored_day(timestamps.size()); std::transform(timestamps.begin(), timestamps.end(), floored_day.begin(), [](auto i) { return time_point_cast<typename T::duration>(floor<days>(i)); }); auto expected_day = fixed_width_column_wrapper<T, typename T::duration::rep>(floored_day.begin(), floored_day.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*floor_datetimes(input, rounding_frequency::DAY), expected_day); std::vector<T> floored_hour(timestamps.size()); std::transform(timestamps.begin(), timestamps.end(), floored_hour.begin(), [](auto i) { return time_point_cast<typename T::duration>(floor<hours>(i)); }); auto expected_hour = fixed_width_column_wrapper<T, typename T::duration::rep>( floored_hour.begin(), floored_hour.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*floor_datetimes(input, rounding_frequency::HOUR), expected_hour); std::vector<T> floored_minute(timestamps.size()); std::transform(timestamps.begin(), timestamps.end(), floored_minute.begin(), [](auto i) { return time_point_cast<typename T::duration>(floor<minutes>(i)); }); auto expected_minute = fixed_width_column_wrapper<T, typename T::duration::rep>( floored_minute.begin(), floored_minute.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*floor_datetimes(input, rounding_frequency::MINUTE), expected_minute); std::vector<T> floored_second(timestamps.size()); std::transform(timestamps.begin(), timestamps.end(), floored_second.begin(), [](auto i) { return time_point_cast<typename T::duration>(floor<seconds>(i)); }); auto expected_second = fixed_width_column_wrapper<T, typename T::duration::rep>( floored_second.begin(), floored_second.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*floor_datetimes(input, rounding_frequency::SECOND), expected_second); std::vector<T> floored_millisecond(timestamps.size()); std::transform(timestamps.begin(), timestamps.end(), floored_millisecond.begin(), [](auto i) { return time_point_cast<typename T::duration>(floor<milliseconds>(i)); }); auto expected_millisecond = fixed_width_column_wrapper<T, typename T::duration::rep>( floored_millisecond.begin(), floored_millisecond.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*floor_datetimes(input, rounding_frequency::MILLISECOND), expected_millisecond); std::vector<T> floored_microsecond(timestamps.size()); std::transform(timestamps.begin(), timestamps.end(), floored_microsecond.begin(), [](auto i) { return time_point_cast<typename T::duration>(floor<microseconds>(i)); }); auto expected_microsecond = fixed_width_column_wrapper<T, typename T::duration::rep>( floored_microsecond.begin(), floored_microsecond.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*floor_datetimes(input, rounding_frequency::MICROSECOND), expected_microsecond); std::vector<T> floored_nanosecond(timestamps.size()); std::transform(timestamps.begin(), timestamps.end(), floored_nanosecond.begin(), [](auto i) { return time_point_cast<typename T::duration>(floor<nanoseconds>(i)); }); auto expected_nanosecond = fixed_width_column_wrapper<T, typename T::duration::rep>( floored_nanosecond.begin(), floored_nanosecond.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*floor_datetimes(input, rounding_frequency::NANOSECOND), expected_nanosecond); } TYPED_TEST(TypedDatetimeOpsTest, TestRoundDatetime) { using T = TypeParam; using namespace cudf::test; using namespace cudf::datetime; using namespace cuda::std::chrono; auto start = milliseconds(-2500000000000); // Sat, 11 Oct 1890 19:33:20 GMT auto stop = milliseconds(2500000000000); // Mon, 22 Mar 2049 04:26:40 GMT auto const input = generate_timestamps<T>(this->size(), time_point_ms(start), time_point_ms(stop)); auto const timestamps = to_host<T>(input).first; std::vector<T> rounded_day(timestamps.size()); std::transform(timestamps.begin(), timestamps.end(), rounded_day.begin(), [](auto i) { return time_point_cast<typename T::duration>(round<days>(i)); }); auto expected_day = fixed_width_column_wrapper<T, typename T::duration::rep>(rounded_day.begin(), rounded_day.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*round_datetimes(input, rounding_frequency::DAY), expected_day); std::vector<T> rounded_hour(timestamps.size()); std::transform(timestamps.begin(), timestamps.end(), rounded_hour.begin(), [](auto i) { return time_point_cast<typename T::duration>(round<hours>(i)); }); auto expected_hour = fixed_width_column_wrapper<T, typename T::duration::rep>( rounded_hour.begin(), rounded_hour.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*round_datetimes(input, rounding_frequency::HOUR), expected_hour); std::vector<T> rounded_minute(timestamps.size()); std::transform(timestamps.begin(), timestamps.end(), rounded_minute.begin(), [](auto i) { return time_point_cast<typename T::duration>(round<minutes>(i)); }); auto expected_minute = fixed_width_column_wrapper<T, typename T::duration::rep>( rounded_minute.begin(), rounded_minute.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*round_datetimes(input, rounding_frequency::MINUTE), expected_minute); std::vector<T> rounded_second(timestamps.size()); std::transform(timestamps.begin(), timestamps.end(), rounded_second.begin(), [](auto i) { return time_point_cast<typename T::duration>(round<seconds>(i)); }); auto expected_second = fixed_width_column_wrapper<T, typename T::duration::rep>( rounded_second.begin(), rounded_second.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*round_datetimes(input, rounding_frequency::SECOND), expected_second); std::vector<T> rounded_millisecond(timestamps.size()); std::transform(timestamps.begin(), timestamps.end(), rounded_millisecond.begin(), [](auto i) { return time_point_cast<typename T::duration>(round<milliseconds>(i)); }); auto expected_millisecond = fixed_width_column_wrapper<T, typename T::duration::rep>( rounded_millisecond.begin(), rounded_millisecond.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*round_datetimes(input, rounding_frequency::MILLISECOND), expected_millisecond); std::vector<T> rounded_microsecond(timestamps.size()); std::transform(timestamps.begin(), timestamps.end(), rounded_microsecond.begin(), [](auto i) { return time_point_cast<typename T::duration>(round<microseconds>(i)); }); auto expected_microsecond = fixed_width_column_wrapper<T, typename T::duration::rep>( rounded_microsecond.begin(), rounded_microsecond.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*round_datetimes(input, rounding_frequency::MICROSECOND), expected_microsecond); std::vector<T> rounded_nanosecond(timestamps.size()); std::transform(timestamps.begin(), timestamps.end(), rounded_nanosecond.begin(), [](auto i) { return time_point_cast<typename T::duration>(round<nanoseconds>(i)); }); auto expected_nanosecond = fixed_width_column_wrapper<T, typename T::duration::rep>( rounded_nanosecond.begin(), rounded_nanosecond.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*round_datetimes(input, rounding_frequency::NANOSECOND), expected_nanosecond); } CUDF_TEST_PROGRAM_MAIN()
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/structs/structs_column_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/column/column_factories.hpp> #include <cudf/copying.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/detail/utilities/device_operators.cuh> #include <cudf/lists/lists_column_view.hpp> #include <cudf/null_mask.hpp> #include <cudf/structs/structs_column_view.hpp> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> #include <cudf/types.hpp> #include <cudf/utilities/error.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/type_lists.hpp> #include <thrust/host_vector.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/scan.h> #include <thrust/sequence.h> #include <rmm/device_buffer.hpp> #include <algorithm> #include <functional> #include <initializer_list> #include <iterator> #include <memory> using vector_of_columns = std::vector<std::unique_ptr<cudf::column>>; using cudf::size_type; struct StructColumnWrapperTest : public cudf::test::BaseFixture {}; template <typename T> struct TypedStructColumnWrapperTest : public cudf::test::BaseFixture {}; using FixedWidthTypesNotBool = cudf::test::Concat<cudf::test::IntegralTypesNotBool, cudf::test::FloatingPointTypes, cudf::test::DurationTypes, cudf::test::TimestampTypes>; TYPED_TEST_SUITE(TypedStructColumnWrapperTest, FixedWidthTypesNotBool); // Test simple struct construction without nullmask, through column factory. // Columns must retain their originally set values. TYPED_TEST(TypedStructColumnWrapperTest, TestColumnFactoryConstruction) { auto names_col = cudf::test::strings_column_wrapper{ "Samuel Vimes", "Carrot Ironfoundersson", "Angua von Überwald"} .release(); int num_rows{names_col->size()}; auto ages_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>{{48, 27, 25}}.release(); auto is_human_col = cudf::test::fixed_width_column_wrapper<bool>{{true, true, false}}.release(); vector_of_columns cols; cols.push_back(std::move(names_col)); cols.push_back(std::move(ages_col)); cols.push_back(std::move(is_human_col)); auto struct_col = cudf::make_structs_column(num_rows, std::move(cols), 0, {}); EXPECT_EQ(num_rows, struct_col->size()); auto struct_col_view{struct_col->view()}; EXPECT_TRUE(std::all_of(struct_col_view.child_begin(), struct_col_view.child_end(), [&](auto const& child) { return child.size() == num_rows; })); // Check child columns for exactly correct values. vector_of_columns expected_children; expected_children.emplace_back(cudf::test::strings_column_wrapper{ "Samuel Vimes", "Carrot Ironfoundersson", "Angua von Überwald"} .release()); expected_children.emplace_back( cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>{48, 27, 25}.release()); expected_children.emplace_back( cudf::test::fixed_width_column_wrapper<bool>{true, true, false}.release()); std::for_each(thrust::make_counting_iterator(0), thrust::make_counting_iterator(0) + expected_children.size(), [&](auto idx) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(struct_col_view.child(idx), expected_children[idx]->view()); }); } // Test simple struct construction with nullmasks, through column wrappers. // When the struct row is null, the child column value must be null. TYPED_TEST(TypedStructColumnWrapperTest, TestColumnWrapperConstruction) { std::initializer_list<std::string> names = {"Samuel Vimes", "Carrot Ironfoundersson", "Angua von Überwald", "Cheery Littlebottom", "Detritus", "Mr Slant"}; auto num_rows{std::distance(names.begin(), names.end())}; auto names_col = cudf::test::strings_column_wrapper{names.begin(), names.end()}; auto ages_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>{ {48, 27, 25, 31, 351, 351}, {1, 1, 1, 1, 1, 0}}; auto is_human_col = cudf::test::fixed_width_column_wrapper<bool>{ {true, true, false, false, false, false}, {1, 1, 0, 1, 1, 0}}; auto struct_col = cudf::test::structs_column_wrapper{{names_col, ages_col, is_human_col}, {1, 1, 1, 0, 1, 1}} .release(); EXPECT_EQ(num_rows, struct_col->size()); auto struct_col_view{struct_col->view()}; EXPECT_TRUE(std::all_of(struct_col_view.child_begin(), struct_col_view.child_end(), [&](auto const& child) { return child.size() == num_rows; })); // Check child columns for exactly correct values. vector_of_columns expected_children; expected_children.emplace_back( cudf::test::strings_column_wrapper{names, {1, 1, 1, 0, 1, 1}}.release()); expected_children.emplace_back(cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>{ {48, 27, 25, 31, 351, 351}, {1, 1, 1, 0, 1, 0}}.release()); expected_children.emplace_back(cudf::test::fixed_width_column_wrapper<bool>{ {true, true, false, false, false, false}, {1, 1, 0, 0, 1, 0}}.release()); std::for_each(thrust::make_counting_iterator(0), thrust::make_counting_iterator(0) + expected_children.size(), [&](auto idx) { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(struct_col_view.child(idx), expected_children[idx]->view()); }); auto expected_struct_col = cudf::test::structs_column_wrapper{std::move(expected_children), {1, 1, 1, 0, 1, 1}}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(struct_col_view, expected_struct_col->view()); } TYPED_TEST(TypedStructColumnWrapperTest, TestStructsContainingLists) { // Test structs with two members: // 1. Name: String // 2. List: List<TypeParam> std::initializer_list<std::string> names = {"Samuel Vimes", "Carrot Ironfoundersson", "Angua von Überwald", "Cheery Littlebottom", "Detritus", "Mr Slant"}; auto num_rows{std::distance(names.begin(), names.end())}; // `Name` column has all valid values. auto names_col = cudf::test::strings_column_wrapper{names.begin(), names.end()}; // `List` member. auto lists_col = cudf::test::lists_column_wrapper<TypeParam, int32_t>{{1, 2, 3}, {4}, {5, 6}, {}, {7, 8}, {9}}; // Construct a Struct column of 6 rows, with the last two values set to null. auto struct_col = cudf::test::structs_column_wrapper{{names_col, lists_col}, {1, 1, 1, 1, 0, 0}}.release(); EXPECT_EQ(struct_col->size(), num_rows); EXPECT_EQ(struct_col->view().child(0).size(), num_rows); EXPECT_EQ(struct_col->view().child(1).size(), num_rows); // Check that the last two rows are null for all members. // For `Name` member, indices 4 and 5 are null. auto expected_names_col = cudf::test::strings_column_wrapper{ names.begin(), names.end(), cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i < 4; })}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(struct_col->view().child(0), expected_names_col->view()); // For the `List` member, indices 4, 5 should be null. auto expected_last_two_lists_col = cudf::test::lists_column_wrapper<TypeParam, int32_t>{ { {1, 2, 3}, {4}, {5, 6}, {}, {7, 8}, // Null. {9} // Null. }, cudf::detail::make_counting_transform_iterator( 0, [](auto i) { return i < 4; })}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(struct_col->view().child(1), expected_last_two_lists_col->view()); } TYPED_TEST(TypedStructColumnWrapperTest, StructOfStructs) { // Struct<is_human:bool, Struct<names:string, ages:int>> auto names = {"Samuel Vimes", "Carrot Ironfoundersson", "Angua von Überwald", "Cheery Littlebottom", "Detritus", "Mr Slant"}; auto num_rows{std::distance(names.begin(), names.end())}; // `Name` column has all valid values. auto names_col = cudf::test::strings_column_wrapper{names.begin(), names.end()}; auto ages_col = cudf::test::fixed_width_column_wrapper<int32_t>{{48, 27, 25, 31, 351, 351}, {1, 1, 1, 1, 1, 0}}; auto struct_1 = cudf::test::structs_column_wrapper{{names_col, ages_col}, {1, 1, 1, 1, 0, 1}}; auto is_human_col = cudf::test::fixed_width_column_wrapper<bool>{ {true, true, false, false, false, false}, {1, 1, 0, 1, 1, 0}}; auto struct_2 = cudf::test::structs_column_wrapper{{is_human_col, struct_1}, {0, 1, 1, 1, 1, 1}}.release(); EXPECT_EQ(struct_2->size(), num_rows); EXPECT_EQ(struct_2->view().child(0).size(), num_rows); EXPECT_EQ(struct_2->view().child(1).size(), num_rows); // Verify that the child/grandchild columns are as expected. auto expected_names_col = cudf::test::strings_column_wrapper( names.begin(), names.end(), cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 0 && i != 4; })) .release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected_names_col, struct_2->child(1).child(0)); auto expected_ages_col = cudf::test::fixed_width_column_wrapper<int32_t>{ {48, 27, 25, 31, 351, 351}, {0, 1, 1, 1, 0, 0}}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected_ages_col, struct_2->child(1).child(1)); auto expected_bool_col = cudf::test::fixed_width_column_wrapper<bool>{ {true, true, false, false, false, false}, {0, 1, 0, 1, 1, 0}}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected_bool_col, struct_2->child(0)); // Verify that recursive struct columns may be compared // using expect_columns_equivalent. vector_of_columns expected_cols_1; expected_cols_1.emplace_back(std::move(expected_names_col)); expected_cols_1.emplace_back(std::move(expected_ages_col)); auto expected_struct_1 = cudf::test::structs_column_wrapper(std::move(expected_cols_1), {1, 1, 1, 1, 0, 1}).release(); vector_of_columns expected_cols_2; expected_cols_2.emplace_back(std::move(expected_bool_col)); expected_cols_2.emplace_back(std::move(expected_struct_1)); auto expected_struct_2 = cudf::test::structs_column_wrapper(std::move(expected_cols_2), {0, 1, 1, 1, 1, 1}).release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected_struct_2, *struct_2); } TYPED_TEST(TypedStructColumnWrapperTest, TestNullMaskPropagationForNonNullStruct) { // Struct<is_human:bool, Struct<names:string, ages:int>> auto names = {"Samuel Vimes", "Carrot Ironfoundersson", "Angua von Überwald", "Cheery Littlebottom", "Detritus", "Mr Slant"}; auto num_rows{std::distance(names.begin(), names.end())}; // `Name` column has all valid values. auto names_col = cudf::test::strings_column_wrapper{names.begin(), names.end()}; auto ages_col = cudf::test::fixed_width_column_wrapper<int32_t>{ {48, 27, 25, 31, 351, 351}, {1, 1, 1, 1, 1, 1} // <-- No nulls in ages_col either. }; auto struct_1 = cudf::test::structs_column_wrapper{ {names_col, ages_col}, {1, 1, 1, 1, 1, 1} // <-- Non-null, bottom level struct. }; auto is_human_col = cudf::test::fixed_width_column_wrapper<bool>{ {true, true, false, false, false, false}, {1, 1, 0, 1, 1, 0}}; auto struct_2 = cudf::test::structs_column_wrapper{ {is_human_col, struct_1}, {0, 1, 1, 1, 1, 1} // <-- First row is null, for top-level struct. } .release(); EXPECT_EQ(struct_2->size(), num_rows); EXPECT_EQ(struct_2->view().child(0).size(), num_rows); EXPECT_EQ(struct_2->view().child(1).size(), num_rows); // Verify that the child/grandchild columns are as expected. // Top-struct has 1 null (at index 0). // Bottom-level struct had no nulls, but must now report nulls auto expected_names_col = cudf::test::strings_column_wrapper( names.begin(), names.end(), cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 0; })) .release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected_names_col, struct_2->child(1).child(0)); auto expected_ages_col = cudf::test::fixed_width_column_wrapper<int32_t>{ {48, 27, 25, 31, 351, 351}, {0, 1, 1, 1, 1, 1}}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected_ages_col, struct_2->child(1).child(1)); auto expected_bool_col = cudf::test::fixed_width_column_wrapper<bool>{ {true, true, false, false, false, false}, {0, 1, 0, 1, 1, 0}}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected_bool_col, struct_2->child(0)); // Verify that recursive struct columns may be compared // using expect_columns_equivalent. vector_of_columns expected_cols_1; expected_cols_1.emplace_back(std::move(expected_names_col)); expected_cols_1.emplace_back(std::move(expected_ages_col)); auto expected_struct_1 = cudf::test::structs_column_wrapper(std::move(expected_cols_1), {1, 1, 1, 1, 1, 1}).release(); vector_of_columns expected_cols_2; expected_cols_2.emplace_back(std::move(expected_bool_col)); expected_cols_2.emplace_back(std::move(expected_struct_1)); auto expected_struct_2 = cudf::test::structs_column_wrapper(std::move(expected_cols_2), {0, 1, 1, 1, 1, 1}).release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected_struct_2, *struct_2); } TEST_F(StructColumnWrapperTest, StructWithNoMembers) { auto struct_col{cudf::test::structs_column_wrapper{}.release()}; EXPECT_TRUE(struct_col->num_children() == 0); EXPECT_TRUE(struct_col->null_count() == 0); EXPECT_TRUE(struct_col->size() == 0); } TYPED_TEST(TypedStructColumnWrapperTest, StructsWithMembersWithDifferentRowCounts) { auto numeric_col_5 = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>{{1, 2, 3, 4, 5}}; auto bool_col_4 = cudf::test::fixed_width_column_wrapper<bool>{1, 0, 1, 0}; EXPECT_THROW(cudf::test::structs_column_wrapper({numeric_col_5, bool_col_4}), cudf::logic_error); } TYPED_TEST(TypedStructColumnWrapperTest, TestListsOfStructs) { // Test list containing structs with two members // 1. Name: String // 2. Age: TypeParam std::initializer_list<std::string> names = {"Samuel Vimes", "Carrot Ironfoundersson", "Angua von Überwald", "Cheery Littlebottom", "Detritus", "Mr Slant"}; auto num_struct_rows{std::distance(names.begin(), names.end())}; // `Name` column has all valid values. auto names_col = cudf::test::strings_column_wrapper{names.begin(), names.end()}; // Numeric column has some nulls. auto ages_col = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>{ {48, 27, 25, 31, 351, 351}, {1, 1, 1, 1, 1, 0}}; auto struct_col = cudf::test::structs_column_wrapper({names_col, ages_col}, {1, 1, 1, 0, 0, 1}).release(); EXPECT_EQ(struct_col->size(), num_struct_rows); EXPECT_EQ(struct_col->view().child(0).size(), num_struct_rows); auto expected_unchanged_struct_col = cudf::column(*struct_col); auto list_offsets_column = cudf::test::fixed_width_column_wrapper<size_type>{0, 2, 3, 5, 6}.release(); auto num_list_rows = list_offsets_column->size() - 1; auto list_col = cudf::make_lists_column( num_list_rows, std::move(list_offsets_column), std::move(struct_col), 0, {}); // List of structs was constructed successfully. No exceptions. // Verify that child columns is as it was set. CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_unchanged_struct_col, cudf::lists_column_view(*list_col).child()); } TYPED_TEST(TypedStructColumnWrapperTest, ListOfStructOfList) { using namespace cudf::test; auto list_col = lists_column_wrapper<TypeParam, int32_t>{ {{0}, {1}, {}, {3}, {4}, {5, 5}, {6}, {}, {8}, {9}}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2; })}; // TODO: Struct<List> cannot be compared with expect_columns_equal(), // if the struct has null values. After lists support "equivalence" // comparisons, the structs column needs to be modified to add nulls. auto struct_of_lists_col = structs_column_wrapper{{list_col}}.release(); auto list_of_struct_of_list_validity = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 3; }); auto [null_mask, null_count] = detail::make_null_mask(list_of_struct_of_list_validity, list_of_struct_of_list_validity + 5); auto list_of_struct_of_list = cudf::make_lists_column( 5, std::move(fixed_width_column_wrapper<size_type>{0, 2, 4, 6, 8, 10}.release()), std::move(struct_of_lists_col), null_count, std::move(null_mask)); // Compare with expected values. auto expected_level0_list = lists_column_wrapper<TypeParam, int32_t>{ {{}, {3}, {}, {5, 5}, {}, {9}}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2; })}; auto expected_level2_struct = structs_column_wrapper{{expected_level0_list}}.release(); CUDF_TEST_EXPECT_COLUMNS_EQUAL(cudf::lists_column_view(*list_of_struct_of_list).child(), *expected_level2_struct); std::tie(null_mask, null_count) = detail::make_null_mask(list_of_struct_of_list_validity, list_of_struct_of_list_validity + 5); auto expected_level3_list = cudf::make_lists_column( 5, std::move(fixed_width_column_wrapper<size_type>{0, 0, 2, 4, 4, 6}.release()), std::move(expected_level2_struct), null_count, std::move(null_mask)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*list_of_struct_of_list, *expected_level3_list); } TYPED_TEST(TypedStructColumnWrapperTest, StructOfListOfStruct) { using namespace cudf::test; auto ints_col = fixed_width_column_wrapper<TypeParam, int32_t>{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2; })}; auto structs_col = structs_column_wrapper{ {ints_col}, cudf::detail::make_counting_transform_iterator( 0, [](auto i) { return i < 6; }) // Last 4 structs are null. } .release(); auto list_validity = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 3; }); auto [null_mask, null_count] = detail::make_null_mask(list_validity, list_validity + 5); auto lists_col = cudf::make_lists_column( 5, std::move(fixed_width_column_wrapper<size_type>{0, 2, 4, 6, 8, 10}.release()), std::move(structs_col), null_count, std::move(null_mask)); std::vector<std::unique_ptr<cudf::column>> cols; cols.push_back(std::move(lists_col)); auto struct_of_list_of_struct = structs_column_wrapper{std::move(cols)}.release(); // Check that the struct is constructed as expected. auto expected_ints_col = fixed_width_column_wrapper<TypeParam, int32_t>{ {0, 1, 0, 3, 0, 5, 0, 0, 0, 0}, {0, 1, 0, 1, 0, 1, 0, 0, 0, 0}}; auto expected_structs_col = structs_column_wrapper{{expected_ints_col}, {1, 1, 1, 1, 1, 1, 0, 0, 0, 0}}.release(); std::tie(null_mask, null_count) = detail::make_null_mask(list_validity, list_validity + 5); auto expected_lists_col = cudf::make_lists_column( 5, std::move(fixed_width_column_wrapper<size_type>{0, 2, 4, 6, 8, 10}.release()), std::move(expected_structs_col), null_count, std::move(null_mask)); // Test that the lists child column is as expected. CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected_lists_col, struct_of_list_of_struct->child(0)); // Test that the outer struct column is as expected. cols.clear(); cols.push_back(std::move(expected_lists_col)); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*(structs_column_wrapper{std::move(cols)}.release()), *struct_of_list_of_struct); } TYPED_TEST(TypedStructColumnWrapperTest, EmptyColumnsOfStructs) { using namespace cudf::test; { // Empty struct column. auto empty_struct_column = structs_column_wrapper{}.release(); EXPECT_TRUE(empty_struct_column->num_children() == 0); EXPECT_TRUE(empty_struct_column->size() == 0); EXPECT_TRUE(empty_struct_column->null_count() == 0); } { // Empty struct<list> column. auto empty_list_column = lists_column_wrapper<TypeParam>{}; auto struct_column = structs_column_wrapper{{empty_list_column}}.release(); EXPECT_TRUE(struct_column->num_children() == 1); EXPECT_TRUE(struct_column->size() == 0); EXPECT_TRUE(struct_column->null_count() == 0); auto empty_list_of_structs = cudf::make_lists_column( 0, fixed_width_column_wrapper<size_type>{0}.release(), std::move(struct_column), 0, {}); EXPECT_TRUE(empty_list_of_structs->size() == 0); EXPECT_TRUE(empty_list_of_structs->null_count() == 0); auto child_struct_column = cudf::lists_column_view(*empty_list_of_structs).child(); EXPECT_TRUE(child_struct_column.num_children() == 1); EXPECT_TRUE(child_struct_column.size() == 0); EXPECT_TRUE(child_struct_column.null_count() == 0); } // TODO: Uncomment test after adding support to compare empty // lists whose child columns may not be empty. // { // auto non_empty_column_of_numbers = // fixed_width_column_wrapper<TypeParam>{1,2,3,4,5}.release(); // // auto list_offsets = // fixed_width_column_wrapper<size_type>{0}.release(); // // auto empty_list_column = // cudf::make_lists_column( // 0, std::move(list_offsets), std::move(non_empty_column_of_numbers), 0, {}); // // CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*lists_column_wrapper<TypeParam>{}.release(), // *empty_list_column); auto struct_column = // structs_column_wrapper{{empty_list_column}}.release(); // EXPECT_TRUE(struct_column->num_children() == 1); // EXPECT_TRUE(struct_column->size() == 0); // EXPECT_TRUE(struct_column->null_count() == 0); // } } TYPED_TEST(TypedStructColumnWrapperTest, CopyColumnFromView) { // Testing deep-copying structs from column-views. using namespace cudf::test; using T = TypeParam; auto numeric_column = fixed_width_column_wrapper<T, int32_t>{{0, 1, 2, 3, 4, 5}, {1, 1, 1, 1, 1, 0}}; auto lists_column = lists_column_wrapper<T, int32_t>{ {{0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 4; })}; auto structs_column = structs_column_wrapper{ {numeric_column, lists_column}, cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i != 3; })}; auto clone_structs_column = cudf::column(structs_column); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(clone_structs_column, structs_column); auto list_of_structs_column = cudf::make_lists_column( 3, fixed_width_column_wrapper<int32_t>{0, 2, 4, 6}.release(), structs_column.release(), 0, {}) .release(); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(list_of_structs_column->view(), cudf::column(list_of_structs_column->view())); } TEST_F(StructColumnWrapperTest, TestStructsColumnWithEmptyChild) { // structs_column_views should not superimpose their null mask onto any EMPTY children, // because EMPTY columns cannot have a null mask. This test ensures that // we can construct a structs column with a parent null mask and an EMPTY // child and then view it. auto empty_col = std::make_unique<cudf::column>( cudf::data_type(cudf::type_id::EMPTY), 3, rmm::device_buffer{}, rmm::device_buffer{}, 0); int num_rows{empty_col->size()}; vector_of_columns cols; cols.push_back(std::move(empty_col)); auto mask_vec = std::vector<bool>{true, false, false}; auto [null_mask, null_count] = cudf::test::detail::make_null_mask(mask_vec.begin(), mask_vec.end()); auto structs_col = cudf::make_structs_column(num_rows, std::move(cols), null_count, std::move(null_mask)); EXPECT_NO_THROW(structs_col->view()); } CUDF_TEST_PROGRAM_MAIN()
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/structs/utilities_tests.cpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed 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 "cudf_test/default_stream.hpp" #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/column/column_factories.hpp> #include <cudf/detail/aggregation/aggregation.hpp> #include <cudf/detail/null_mask.hpp> #include <cudf/detail/structs/utilities.hpp> #include <cudf/null_mask.hpp> #include <cudf/utilities/default_stream.hpp> template <typename T> using nums = cudf::test::fixed_width_column_wrapper<T, int32_t>; template <typename T> using lists = cudf::test::lists_column_wrapper<T, int32_t>; struct StructUtilitiesTest : cudf::test::BaseFixture {}; template <typename T> struct TypedStructUtilitiesTest : StructUtilitiesTest {}; TYPED_TEST_SUITE(TypedStructUtilitiesTest, cudf::test::FixedWidthTypes); TYPED_TEST(TypedStructUtilitiesTest, ListsAtTopLevel) { using T = TypeParam; using lists = cudf::test::lists_column_wrapper<T, int32_t>; using nums = cudf::test::fixed_width_column_wrapper<T, int32_t>; auto lists_col = lists{{0, 1}, {22, 33}, {44, 55, 66}}; auto nums_col = nums{{0, 1, 2}, cudf::test::iterators::null_at(6)}; auto table = cudf::table_view{{lists_col, nums_col}}; auto flattened_table = cudf::structs::detail::flatten_nested_columns(table, {}, {}, cudf::structs::detail::column_nullability::FORCE, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); CUDF_TEST_EXPECT_TABLES_EQUAL(table, flattened_table->flattened_columns()); } TYPED_TEST(TypedStructUtilitiesTest, NoStructs) { using T = TypeParam; using nums = cudf::test::fixed_width_column_wrapper<T, int32_t>; auto nums_col = nums{{0, 1, 22, 33, 44, 55, 66}, cudf::test::iterators::null_at(0)}; auto strings_col = cudf::test::strings_column_wrapper{ {"", "1", "22", "333", "4444", "55555", "666666"}, cudf::test::iterators::null_at(1)}; auto nuther_nums_col = nums{{0, 1, 2, 3, 4, 5, 6}, cudf::test::iterators::null_at(6)}; auto table = cudf::table_view{{nums_col, strings_col, nuther_nums_col}}; auto flattened_table = cudf::structs::detail::flatten_nested_columns(table, {}, {}, cudf::structs::detail::column_nullability::FORCE, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); CUDF_TEST_EXPECT_TABLES_EQUAL(table, flattened_table->flattened_columns()); } TYPED_TEST(TypedStructUtilitiesTest, SingleLevelStruct) { using T = TypeParam; using nums = cudf::test::fixed_width_column_wrapper<T, int32_t>; auto nums_member = nums{{0, 1, 22, 333, 44, 55, 66}, cudf::test::iterators::null_at(0)}; auto strings_member = cudf::test::strings_column_wrapper{ {"", "1", "22", "333", "4444", "55555", "666666"}, cudf::test::iterators::null_at(1)}; auto structs_col = cudf::test::structs_column_wrapper{{nums_member, strings_member}}; auto nums_col = nums{{0, 1, 2, 3, 4, 5, 6}, cudf::test::iterators::null_at(6)}; auto table = cudf::table_view{{nums_col, structs_col}}; auto expected_nums_col_1 = cudf::column(nums_col); auto expected_structs_col = cudf::test::fixed_width_column_wrapper<bool>{{1, 1, 1, 1, 1, 1, 1}}; auto expected_nums_col_2 = cudf::column(static_cast<cudf::structs_column_view>(structs_col) .get_sliced_child(0, cudf::get_default_stream())); auto expected_strings_col = cudf::column(static_cast<cudf::structs_column_view>(structs_col) .get_sliced_child(1, cudf::get_default_stream())); auto expected = cudf::table_view{ {expected_nums_col_1, expected_structs_col, expected_nums_col_2, expected_strings_col}}; auto flattened_table = cudf::structs::detail::flatten_nested_columns(table, {}, {}, cudf::structs::detail::column_nullability::FORCE, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, flattened_table->flattened_columns()); } TYPED_TEST(TypedStructUtilitiesTest, SingleLevelStructWithNulls) { using T = TypeParam; using nums = cudf::test::fixed_width_column_wrapper<T, int32_t>; auto nums_member = nums{{0, 1, 22, 333, 44, 55, 66}, cudf::test::iterators::null_at(0)}; auto strings_member = cudf::test::strings_column_wrapper{ {"", "1", "22", "333", "4444", "55555", "666666"}, cudf::test::iterators::null_at(1)}; auto structs_col = cudf::test::structs_column_wrapper{{nums_member, strings_member}, cudf::test::iterators::null_at(2)}; auto nums_col = nums{{0, 1, 2, 3, 4, 5, 6}, cudf::test::iterators::null_at(6)}; auto table = cudf::table_view{{nums_col, structs_col}}; auto expected_nums_col_1 = cudf::column(nums_col); auto expected_structs_col = cudf::test::fixed_width_column_wrapper<bool>{ {1, 1, 0, 1, 1, 1, 1}, cudf::test::iterators::null_at(2)}; auto expected_nums_col_2 = cudf::column(static_cast<cudf::structs_column_view>(structs_col) .get_sliced_child(0, cudf::get_default_stream())); auto expected_strings_col = cudf::column(static_cast<cudf::structs_column_view>(structs_col) .get_sliced_child(1, cudf::get_default_stream())); auto expected = cudf::table_view{ {expected_nums_col_1, expected_structs_col, expected_nums_col_2, expected_strings_col}}; auto flattened_table = cudf::structs::detail::flatten_nested_columns(table, {}, {}, cudf::structs::detail::column_nullability::FORCE, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, flattened_table->flattened_columns()); } TYPED_TEST(TypedStructUtilitiesTest, StructOfStruct) { using T = TypeParam; using nums = cudf::test::fixed_width_column_wrapper<T, int32_t>; auto nums_col = nums{{0, 1, 2, 3, 4, 5, 6}, cudf::test::iterators::null_at(6)}; auto struct_0_nums_member = nums{{0, 1, 22, 33, 44, 55, 66}, cudf::test::iterators::null_at(0)}; auto struct_0_strings_member = cudf::test::strings_column_wrapper{ {"", "1", "22", "333", "4444", "55555", "666666"}, cudf::test::iterators::null_at(1)}; auto structs_1_structs_member = cudf::test::structs_column_wrapper{{struct_0_nums_member, struct_0_strings_member}}; auto struct_1_nums_member = nums{{0, 1, 22, 33, 44, 55, 66}, cudf::test::iterators::null_at(3)}; auto struct_of_structs_col = cudf::test::structs_column_wrapper{{struct_1_nums_member, structs_1_structs_member}}; auto table = cudf::table_view{{nums_col, struct_of_structs_col}}; auto expected_nums_col_1 = cudf::column(nums_col); auto expected_structs_col_1 = cudf::test::fixed_width_column_wrapper<bool>{{1, 1, 1, 1, 1, 1, 1}}; auto expected_nums_col_2 = cudf::column(static_cast<cudf::structs_column_view>(struct_of_structs_col) .get_sliced_child(0, cudf::get_default_stream())); auto expected_structs_col_2 = cudf::test::fixed_width_column_wrapper<bool>{{1, 1, 1, 1, 1, 1, 1}}; auto expected_nums_col_3 = cudf::column(static_cast<cudf::structs_column_view>(struct_of_structs_col) .get_sliced_child(1, cudf::get_default_stream()) .child(0)); auto expected_strings_col = cudf::column(static_cast<cudf::structs_column_view>(struct_of_structs_col) .get_sliced_child(1, cudf::get_default_stream()) .child(1)); auto expected = cudf::table_view{{expected_nums_col_1, expected_structs_col_1, expected_nums_col_2, expected_structs_col_2, expected_nums_col_3, expected_strings_col}}; auto flattened_table = cudf::structs::detail::flatten_nested_columns(table, {}, {}, cudf::structs::detail::column_nullability::FORCE, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, flattened_table->flattened_columns()); } TYPED_TEST(TypedStructUtilitiesTest, StructOfStructWithNullsAtLeafLevel) { using T = TypeParam; using nums = cudf::test::fixed_width_column_wrapper<T, int32_t>; auto nums_col = nums{{0, 1, 2, 3, 4, 5, 6}, cudf::test::iterators::null_at(6)}; auto struct_0_nums_member = nums{{0, 1, 22, 33, 44, 55, 66}, cudf::test::iterators::null_at(0)}; auto struct_0_strings_member = cudf::test::strings_column_wrapper{ {"", "1", "22", "333", "4444", "55555", "666666"}, cudf::test::iterators::null_at(1)}; auto structs_1_structs_member = cudf::test::structs_column_wrapper{ {struct_0_nums_member, struct_0_strings_member}, cudf::test::iterators::null_at(2)}; auto struct_1_nums_member = nums{{0, 1, 22, 33, 44, 55, 66}, cudf::test::iterators::null_at(3)}; auto struct_of_structs_col = cudf::test::structs_column_wrapper{{struct_1_nums_member, structs_1_structs_member}}; auto table = cudf::table_view{{nums_col, struct_of_structs_col}}; auto expected_nums_col_1 = cudf::column(nums_col); auto expected_structs_col_1 = cudf::test::fixed_width_column_wrapper<bool>{{1, 1, 1, 1, 1, 1, 1}}; auto expected_nums_col_2 = cudf::column(static_cast<cudf::structs_column_view>(struct_of_structs_col) .get_sliced_child(0, cudf::get_default_stream())); auto expected_structs_col_2 = cudf::test::fixed_width_column_wrapper<bool>{ {1, 1, 0, 1, 1, 1, 1}, cudf::test::iterators::null_at(2)}; auto expected_nums_col_3 = cudf::column(static_cast<cudf::structs_column_view>(struct_of_structs_col) .get_sliced_child(1, cudf::get_default_stream()) .child(0)); auto expected_strings_col = cudf::column(static_cast<cudf::structs_column_view>(struct_of_structs_col) .get_sliced_child(1, cudf::get_default_stream()) .child(1)); auto expected = cudf::table_view{{expected_nums_col_1, expected_structs_col_1, expected_nums_col_2, expected_structs_col_2, expected_nums_col_3, expected_strings_col}}; auto flattened_table = cudf::structs::detail::flatten_nested_columns(table, {}, {}, cudf::structs::detail::column_nullability::FORCE, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, flattened_table->flattened_columns()); } TYPED_TEST(TypedStructUtilitiesTest, StructOfStructWithNullsAtTopLevel) { using T = TypeParam; using nums = cudf::test::fixed_width_column_wrapper<T, int32_t>; auto nums_col = nums{{0, 1, 2, 3, 4, 5, 6}, cudf::test::iterators::null_at(6)}; auto struct_0_nums_member = nums{{0, 1, 22, 33, 44, 55, 66}, cudf::test::iterators::null_at(0)}; auto struct_0_strings_member = cudf::test::strings_column_wrapper{ {"", "1", "22", "333", "4444", "55555", "666666"}, cudf::test::iterators::null_at(1)}; auto structs_1_structs_member = cudf::test::structs_column_wrapper{{struct_0_nums_member, struct_0_strings_member}}; auto struct_1_nums_member = nums{{0, 1, 22, 33, 44, 55, 66}, cudf::test::iterators::null_at(3)}; auto struct_of_structs_col = cudf::test::structs_column_wrapper{ {struct_1_nums_member, structs_1_structs_member}, cudf::test::iterators::null_at(4)}; auto table = cudf::table_view{{nums_col, struct_of_structs_col}}; auto expected_nums_col_1 = cudf::column(nums_col); auto expected_structs_col_1 = cudf::test::fixed_width_column_wrapper<bool>{ {1, 1, 1, 1, 0, 1, 1}, cudf::test::iterators::null_at(4)}; auto expected_nums_col_2 = cudf::column(static_cast<cudf::structs_column_view>(struct_of_structs_col) .get_sliced_child(0, cudf::get_default_stream())); auto expected_structs_col_2 = cudf::test::fixed_width_column_wrapper<bool>{ {1, 1, 1, 1, 0, 1, 1}, cudf::test::iterators::null_at(4)}; auto expected_nums_col_3 = cudf::column(static_cast<cudf::structs_column_view>(struct_of_structs_col) .get_sliced_child(1, cudf::get_default_stream()) .child(0)); auto expected_strings_col = cudf::column(static_cast<cudf::structs_column_view>(struct_of_structs_col) .get_sliced_child(1, cudf::get_default_stream()) .child(1)); auto expected = cudf::table_view{{expected_nums_col_1, expected_structs_col_1, expected_nums_col_2, expected_structs_col_2, expected_nums_col_3, expected_strings_col}}; auto flattened_table = cudf::structs::detail::flatten_nested_columns(table, {}, {}, cudf::structs::detail::column_nullability::FORCE, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, flattened_table->flattened_columns()); } TYPED_TEST(TypedStructUtilitiesTest, StructOfStructWithNullsAtAllLevels) { using T = TypeParam; using nums = cudf::test::fixed_width_column_wrapper<T, int32_t>; auto nums_col = nums{{0, 1, 2, 3, 4, 5, 6}, cudf::test::iterators::null_at(6)}; auto struct_0_nums_member = nums{{0, 1, 22, 33, 44, 55, 66}, cudf::test::iterators::null_at(0)}; auto struct_0_strings_member = cudf::test::strings_column_wrapper{ {"", "1", "22", "333", "4444", "55555", "666666"}, cudf::test::iterators::null_at(1)}; auto structs_1_structs_member = cudf::test::structs_column_wrapper{ {struct_0_nums_member, struct_0_strings_member}, cudf::test::iterators::null_at(2)}; auto struct_1_nums_member = nums{{0, 1, 22, 33, 44, 55, 66}, cudf::test::iterators::null_at(3)}; auto struct_of_structs_col = cudf::test::structs_column_wrapper{ {struct_1_nums_member, structs_1_structs_member}, cudf::test::iterators::null_at(4)}; auto table = cudf::table_view{{nums_col, struct_of_structs_col}}; auto expected_nums_col_1 = cudf::column(nums_col); auto expected_structs_col_1 = cudf::test::fixed_width_column_wrapper<bool>{ {1, 1, 1, 1, 0, 1, 1}, cudf::test::iterators::null_at(4)}; auto expected_nums_col_2 = cudf::column(static_cast<cudf::structs_column_view>(struct_of_structs_col) .get_sliced_child(0, cudf::get_default_stream())); auto expected_structs_col_2 = cudf::test::fixed_width_column_wrapper<bool>{{1, 1, 0, 1, 0, 1, 1}, {1, 1, 0, 1, 0, 1, 1}}; auto expected_nums_col_3 = cudf::column(static_cast<cudf::structs_column_view>(struct_of_structs_col) .get_sliced_child(1, cudf::get_default_stream()) .child(0)); auto expected_strings_col = cudf::column(static_cast<cudf::structs_column_view>(struct_of_structs_col) .get_sliced_child(1, cudf::get_default_stream()) .child(1)); auto expected = cudf::table_view{{expected_nums_col_1, expected_structs_col_1, expected_nums_col_2, expected_structs_col_2, expected_nums_col_3, expected_strings_col}}; auto flattened_table = cudf::structs::detail::flatten_nested_columns(table, {}, {}, cudf::structs::detail::column_nullability::FORCE, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, flattened_table->flattened_columns()); } struct SuperimposeTest : StructUtilitiesTest {}; template <typename T> struct TypedSuperimposeTest : StructUtilitiesTest {}; TYPED_TEST_SUITE(TypedSuperimposeTest, cudf::test::FixedWidthTypes); void test_non_struct_columns(cudf::column_view const& input) { // push_down_nulls() on non-struct columns should return the input column, unchanged. auto [superimposed, backing_data] = cudf::structs::detail::push_down_nulls( input, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(input, superimposed); EXPECT_TRUE(backing_data.new_null_masks.empty()); if (input.type().id() != cudf::type_id::STRING && input.type().id() != cudf::type_id::LIST) { EXPECT_TRUE(backing_data.new_columns.empty()); } } TYPED_TEST(TypedSuperimposeTest, NoStructInput) { using T = TypeParam; test_non_struct_columns(cudf::test::fixed_width_column_wrapper<T>{ {6, 5, 4, 3, 2, 1, 0}, cudf::test::iterators::null_at(3)}); test_non_struct_columns(cudf::test::lists_column_wrapper<T, int32_t>{ {{6, 5}, {4, 3}, {2, 1}, {0}}, cudf::test::iterators::null_at(3)}); test_non_struct_columns(cudf::test::strings_column_wrapper{ {"All", "The", "Leaves", "Are", "Brown"}, cudf::test::iterators::null_at(3)}); test_non_struct_columns(cudf::test::dictionary_column_wrapper<std::string>{ {"All", "The", "Leaves", "Are", "Brown"}, cudf::test::iterators::null_at(3)}); } /** * @brief Helper to construct a numeric member of a struct column. */ template <typename T, typename NullIter> nums<T> make_nums_member(NullIter null_iter = cudf::test::iterators::no_nulls()) { return nums<T>{{10, 11, 12, 13, 14, 15, 16}, null_iter}; } /** * @brief Helper to construct a lists member of a struct column. */ template <typename T, typename NullIter> lists<T> make_lists_member(NullIter null_iter = cudf::test::iterators::no_nulls()) { return lists<T>{{{20, 20}, {21, 21}, {22, 22}, {23, 23}, {24, 24}, {25, 25}, {26, 26}}, null_iter}; } TYPED_TEST(TypedSuperimposeTest, BasicStruct) { using T = TypeParam; auto nums_member = make_nums_member<T>(cudf::test::iterators::nulls_at({3, 6})); auto lists_member = make_lists_member<T>(cudf::test::iterators::nulls_at({4, 5})); auto structs_input = cudf::test::structs_column_wrapper{{nums_member, lists_member}, cudf::test::iterators::no_nulls()} .release(); // Reset STRUCTs' null-mask. Mark first STRUCT row as null. auto structs_view = structs_input->mutable_view(); cudf::detail::set_null_mask(structs_view.null_mask(), 0, 1, false, cudf::get_default_stream()); // At this point, the STRUCT nulls aren't pushed down to members, // even though the parent null-mask was modified. CUDF_TEST_EXPECT_COLUMNS_EQUAL(structs_view.child(0), make_nums_member<T>(cudf::test::iterators::nulls_at({3, 6}))); CUDF_TEST_EXPECT_COLUMNS_EQUAL(structs_view.child(1), make_lists_member<T>(cudf::test::iterators::nulls_at({4, 5}))); auto [output, backing_data] = cudf::structs::detail::push_down_nulls( structs_view, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); // After push_down_nulls(), the struct nulls (i.e. at index-0) should have been pushed // down to the children. All members should have nulls at row-index 0. auto expected_nums_member = make_nums_member<T>(cudf::test::iterators::nulls_at({0, 3, 6})); auto expected_lists_member = make_lists_member<T>(cudf::test::iterators::nulls_at({0, 4, 5})); auto expected_structs_output = cudf::test::structs_column_wrapper{ {expected_nums_member, expected_lists_member}, cudf::test::iterators::null_at(0)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(output, expected_structs_output); } TYPED_TEST(TypedSuperimposeTest, NonNullableParentStruct) { // Test that if the parent struct is not nullable, non-struct members should // remain unchanged. using T = TypeParam; auto nums_member = make_nums_member<T>(cudf::test::iterators::nulls_at({3, 6})); auto lists_member = make_lists_member<T>(cudf::test::iterators::nulls_at({4, 5})); auto structs_input = cudf::test::structs_column_wrapper{{nums_member, lists_member}, cudf::test::iterators::no_nulls()} .release(); auto [output, backing_data] = cudf::structs::detail::push_down_nulls( structs_input->view(), cudf::get_default_stream(), rmm::mr::get_current_device_resource()); // After push_down_nulls(), none of the child structs should have changed, // because the parent had no nulls to begin with. auto expected_nums_member = make_nums_member<T>(cudf::test::iterators::nulls_at({3, 6})); auto expected_lists_member = make_lists_member<T>(cudf::test::iterators::nulls_at({4, 5})); auto expected_structs_output = cudf::test::structs_column_wrapper{ {expected_nums_member, expected_lists_member}, cudf::test::iterators::no_nulls()}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(output, expected_structs_output); } TYPED_TEST(TypedSuperimposeTest, NestedStruct_ChildNullable_ParentNonNullable) { // Test with Struct<Struct>. If the parent struct is not nullable: // 1. Non-struct members should remain unchanged. // 2. Member-structs should have their respective nulls pushed down into grandchildren. using T = TypeParam; auto nums_member = make_nums_member<T>(cudf::test::iterators::nulls_at({3, 6})); auto lists_member = make_lists_member<T>(cudf::test::iterators::nulls_at({4, 5})); auto outer_struct_members = std::vector<std::unique_ptr<cudf::column>>{}; outer_struct_members.push_back(cudf::test::structs_column_wrapper{ {nums_member, lists_member}, cudf::test::iterators::no_nulls()} .release()); // Reset STRUCTs' null-mask. Mark first STRUCT row as null. auto structs_view = outer_struct_members.back()->mutable_view(); cudf::detail::set_null_mask(structs_view.null_mask(), 0, 1, false, cudf::get_default_stream()); auto structs_of_structs = cudf::test::structs_column_wrapper{std::move(outer_struct_members)}.release(); auto [output, backing_data] = cudf::structs::detail::push_down_nulls( structs_of_structs->view(), cudf::get_default_stream(), rmm::mr::get_current_device_resource()); // After push_down_nulls(), outer-struct column should not have pushed nulls to child // structs. But the child struct column must push its nulls to its own children. auto expected_nums_member = make_nums_member<T>(cudf::test::iterators::nulls_at({0, 3, 6})); auto expected_lists_member = make_lists_member<T>(cudf::test::iterators::nulls_at({0, 4, 5})); auto expected_structs = cudf::test::structs_column_wrapper{ {expected_nums_member, expected_lists_member}, cudf::test::iterators::null_at(0)}; auto expected_structs_of_structs = cudf::test::structs_column_wrapper{{expected_structs}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(output, expected_structs_of_structs); } TYPED_TEST(TypedSuperimposeTest, NestedStruct_ChildNullable_ParentNullable) { // Test with Struct<Struct>. // If both the parent struct and the child are nullable, the leaf nodes should // have a 3-way ANDed null-mask. using T = TypeParam; auto nums_member = make_nums_member<T>(cudf::test::iterators::nulls_at({3, 6})); auto lists_member = make_lists_member<T>(cudf::test::iterators::nulls_at({4, 5})); auto outer_struct_members = std::vector<std::unique_ptr<cudf::column>>{}; outer_struct_members.push_back(cudf::test::structs_column_wrapper{ {nums_member, lists_member}, cudf::test::iterators::no_nulls()} .release()); // Reset STRUCTs' null-mask. Mark first STRUCT row as null. auto structs_view = outer_struct_members.back()->mutable_view(); auto num_rows = structs_view.size(); cudf::detail::set_null_mask(structs_view.null_mask(), 0, 1, false, cudf::get_default_stream()); auto structs_of_structs = cudf::test::structs_column_wrapper{std::move(outer_struct_members), std::vector<bool>(num_rows, true)} .release(); // Modify STRUCT-of-STRUCT's null-mask. Mark second STRUCT row as null. auto structs_of_structs_view = structs_of_structs->mutable_view(); cudf::detail::set_null_mask( structs_of_structs_view.null_mask(), 1, 2, false, cudf::get_default_stream()); auto [output, backing_data] = cudf::structs::detail::push_down_nulls( structs_of_structs->view(), cudf::get_default_stream(), rmm::mr::get_current_device_resource()); // After push_down_nulls(), outer-struct column should not have pushed nulls to child // structs. But the child struct column must push its nulls to its own children. auto expected_nums_member = make_nums_member<T>(cudf::test::iterators::nulls_at({0, 1, 3, 6})); auto expected_lists_member = make_lists_member<T>(cudf::test::iterators::nulls_at({0, 1, 4, 5})); auto expected_structs = cudf::test::structs_column_wrapper{ {expected_nums_member, expected_lists_member}, cudf::test::iterators::nulls_at({0, 1})}; auto expected_structs_of_structs = cudf::test::structs_column_wrapper{{expected_structs}, cudf::test::iterators::null_at(1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(output, expected_structs_of_structs); } cudf::column_view slice_off_first_and_last_rows(cudf::column_view const& col) { return cudf::slice(col, {1, col.size() - 1})[0]; } void mark_row_as_null(cudf::mutable_column_view const& col, cudf::size_type row_index) { cudf::detail::set_null_mask( col.null_mask(), row_index, row_index + 1, false, cudf::get_default_stream()); } TYPED_TEST(TypedSuperimposeTest, Struct_Sliced) { // Test with a sliced STRUCT column. // Ensure that push_down_nulls() produces the right results, even when the input is // sliced. using T = TypeParam; auto nums_member = make_nums_member<T>(cudf::test::iterators::nulls_at({3, 6})); auto lists_member = make_lists_member<T>(cudf::test::iterators::nulls_at({4, 5})); auto structs_column = cudf::test::structs_column_wrapper{{nums_member, lists_member}, cudf::test::iterators::no_nulls()} .release(); // Reset STRUCTs' null-mask. Mark second STRUCT row as null. mark_row_as_null(structs_column->mutable_view(), 1); // The null masks should now look as follows, with the STRUCT null mask *not* pushed down: // STRUCT: 1111101 // nums_member: 0110111 // lists_member: 1001111 // Slice off the first and last rows. auto sliced_structs = slice_off_first_and_last_rows(structs_column->view()); // After slice(), the null masks will be: // STRUCT: 11110 // nums_member: 11011 // lists_member: 00111 auto [output, backing_data] = cudf::structs::detail::push_down_nulls( sliced_structs, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); // After push_down_nulls(), the null masks should be: // STRUCT: 11110 // nums_member: 11010 // lists_member: 00110 // Construct expected columns using structs_column_wrapper, which should push the parent nulls // down automatically. Then, slice() off the ends. auto expected_nums = make_nums_member<T>(cudf::test::iterators::nulls_at({1, 3, 6})); auto expected_lists = make_lists_member<T>(cudf::test::iterators::nulls_at({1, 4, 5})); auto expected_unsliced_structs = cudf::test::structs_column_wrapper{ {expected_nums, expected_lists}, cudf::test::iterators::nulls_at({1})}; auto expected_structs = slice_off_first_and_last_rows(expected_unsliced_structs); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output, expected_structs); } TYPED_TEST(TypedSuperimposeTest, NestedStruct_Sliced) { // Test with a sliced STRUCT<STRUCT> column. // Ensure that push_down_nulls() produces the right results, even when the input is // sliced. using T = TypeParam; auto nums_member = make_nums_member<T>(cudf::test::iterators::nulls_at({3, 6})); auto lists_member = make_lists_member<T>(cudf::test::iterators::nulls_at({4, 5})); auto structs_column = cudf::test::structs_column_wrapper{{nums_member, lists_member}, cudf::test::iterators::null_at(1)}; auto struct_structs_column = cudf::test::structs_column_wrapper{{structs_column}, cudf::test::iterators::no_nulls()} .release(); // Reset STRUCT<STRUCT>'s null-mask. Mark third row as null. mark_row_as_null(struct_structs_column->mutable_view(), 2); // The null masks should now look as follows, with the STRUCT<STRUCT> null mask *not* pushed down: // STRUCT<STRUCT>: 1111011 // STRUCT: 1111101 // nums_member: 0110101 // lists_member: 1001101 // Slice off the first and last rows. auto sliced_structs = slice_off_first_and_last_rows(struct_structs_column->view()); // After slice(), the null masks will be: // STRUCT<STRUCT>: 11101 // STRUCT: 11110 // nums_member: 11010 // lists_member: 00110 auto [output, backing_data] = cudf::structs::detail::push_down_nulls( sliced_structs, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); // After push_down_nulls(), the null masks will be: // STRUCT<STRUCT>: 11101 // STRUCT: 11100 // nums_member: 11000 // lists_member: 00100 // Construct expected columns using structs_column_wrapper, which should push the parent nulls // down automatically. Then, slice() off the ends. auto expected_nums = make_nums_member<T>(cudf::test::iterators::nulls_at({3, 6})); auto expected_lists = make_lists_member<T>(cudf::test::iterators::nulls_at({4, 5})); auto expected_structs = cudf::test::structs_column_wrapper{{expected_nums, expected_lists}, cudf::test::iterators::nulls_at({1})}; auto expected_struct_structs = cudf::test::structs_column_wrapper{{expected_structs}, cudf::test::iterators::null_at(2)}; auto expected_sliced_structs = slice_off_first_and_last_rows(expected_struct_structs); CUDF_TEST_EXPECT_COLUMNS_EQUAL(output, expected_sliced_structs); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/ast/transform_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/ast/expressions.hpp> #include <cudf/column/column.hpp> #include <cudf/column/column_view.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/scalar/scalar.hpp> #include <cudf/scalar/scalar_device_view.cuh> #include <cudf/scalar/scalar_factories.hpp> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> #include <cudf/transform.hpp> #include <cudf/types.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/table_utilities.hpp> #include <rmm/device_uvector.hpp> #include <thrust/iterator/counting_iterator.h> #include <algorithm> #include <limits> #include <random> #include <type_traits> #include <vector> template <typename T> using column_wrapper = cudf::test::fixed_width_column_wrapper<T>; constexpr cudf::test::debug_output_level verbosity{cudf::test::debug_output_level::ALL_ERRORS}; struct TransformTest : public cudf::test::BaseFixture {}; TEST_F(TransformTest, ColumnReference) { auto c_0 = column_wrapper<int32_t>{3, 20, 1, 50}; auto c_1 = column_wrapper<int32_t>{10, 7, 20, 0}; auto table = cudf::table_view{{c_0, c_1}}; auto col_ref_0 = cudf::ast::column_reference(0); auto const& expected = c_0; auto result = cudf::compute_column(table, col_ref_0); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, Literal) { auto c_0 = column_wrapper<int32_t>{3, 20, 1, 50}; auto c_1 = column_wrapper<int32_t>{10, 7, 20, 0}; auto table = cudf::table_view{{c_0, c_1}}; auto literal_value = cudf::numeric_scalar<int32_t>(42); auto literal = cudf::ast::literal(literal_value); auto expected = column_wrapper<int32_t>{42, 42, 42, 42}; auto result = cudf::compute_column(table, literal); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, NullLiteral) { auto c_0 = column_wrapper<int32_t>{0, 0, 0, 0}; auto table = cudf::table_view{{c_0}}; auto literal_value = cudf::numeric_scalar<int32_t>(-123); literal_value.set_valid_async(false); auto literal = cudf::ast::literal(literal_value); auto expression = cudf::ast::operation(cudf::ast::ast_operator::IDENTITY, literal); auto result = cudf::compute_column(table, expression); auto expected = column_wrapper<int32_t>({-123, -123, -123, -123}, {0, 0, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, IsNull) { auto c_0 = column_wrapper<int32_t>{{0, 1, 2, 0}, {0, 1, 1, 0}}; auto table = cudf::table_view{{c_0}}; // result of IS_NULL on literal, will be a column of table size, with all values set to // !literal.is_valid(). The table values are irrelevant. auto literal_value = cudf::numeric_scalar<int32_t>(-123); auto literal = cudf::ast::literal(literal_value); auto expression = cudf::ast::operation(cudf::ast::ast_operator::IS_NULL, literal); auto result = cudf::compute_column(table, expression); auto expected1 = column_wrapper<bool>({0, 0, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected1, result->view(), verbosity); literal_value.set_valid_async(false); result = cudf::compute_column(table, expression); auto expected2 = column_wrapper<bool>({1, 1, 1, 1}, cudf::test::iterators::no_nulls()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected2, result->view(), verbosity); auto col_ref_0 = cudf::ast::column_reference(0); auto expression2 = cudf::ast::operation(cudf::ast::ast_operator::IS_NULL, col_ref_0); result = cudf::compute_column(table, expression2); auto expected3 = column_wrapper<bool>({1, 0, 0, 1}, cudf::test::iterators::no_nulls()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected3, result->view(), verbosity); } TEST_F(TransformTest, BasicAddition) { auto c_0 = column_wrapper<int32_t>{3, 20, 1, 50}; auto c_1 = column_wrapper<int32_t>{10, 7, 20, 0}; auto table = cudf::table_view{{c_0, c_1}}; auto col_ref_0 = cudf::ast::column_reference(0); auto col_ref_1 = cudf::ast::column_reference(1); auto expression = cudf::ast::operation(cudf::ast::ast_operator::ADD, col_ref_0, col_ref_1); auto expected = column_wrapper<int32_t>{13, 27, 21, 50}; auto result = cudf::compute_column(table, expression); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, BasicAdditionEmptyTable) { auto c_0 = column_wrapper<int32_t>{}; auto c_1 = column_wrapper<int32_t>{}; auto table = cudf::table_view{{c_0, c_1}}; auto col_ref_0 = cudf::ast::column_reference(0); auto col_ref_1 = cudf::ast::column_reference(1); auto expression = cudf::ast::operation(cudf::ast::ast_operator::ADD, col_ref_0, col_ref_1); auto expected = column_wrapper<int32_t>{}; auto result = cudf::compute_column(table, expression); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, BasicAdditionCast) { auto c_0 = column_wrapper<int64_t>{3, 20, 1, 50}; auto c_1 = column_wrapper<int8_t>{10, 7, 20, 0}; auto table = cudf::table_view{{c_0, c_1}}; auto col_ref_0 = cudf::ast::column_reference(0); auto col_ref_1 = cudf::ast::column_reference(1); auto cast = cudf::ast::operation(cudf::ast::ast_operator::CAST_TO_INT64, col_ref_1); auto expression = cudf::ast::operation(cudf::ast::ast_operator::ADD, col_ref_0, cast); auto expected = column_wrapper<int64_t>{13, 27, 21, 50}; auto result = cudf::compute_column(table, expression); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, BasicEquality) { auto c_0 = column_wrapper<int32_t>{3, 20, 1, 50}; auto c_1 = column_wrapper<int32_t>{3, 7, 1, 0}; auto table = cudf::table_view{{c_0, c_1}}; auto col_ref_0 = cudf::ast::column_reference(0); auto col_ref_1 = cudf::ast::column_reference(1); auto expression = cudf::ast::operation(cudf::ast::ast_operator::EQUAL, col_ref_0, col_ref_1); auto expected = column_wrapper<bool>{true, false, true, false}; auto result = cudf::compute_column(table, expression); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, BasicAdditionLarge) { auto a = thrust::make_counting_iterator(0); auto col = column_wrapper<int32_t>(a, a + 2000); auto table = cudf::table_view{{col, col}}; auto col_ref = cudf::ast::column_reference(0); auto expression = cudf::ast::operation(cudf::ast::ast_operator::ADD, col_ref, col_ref); auto b = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i * 2; }); auto expected = column_wrapper<int32_t>(b, b + 2000); auto result = cudf::compute_column(table, expression); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, LessComparator) { auto c_0 = column_wrapper<int32_t>{3, 20, 1, 50}; auto c_1 = column_wrapper<int32_t>{10, 7, 20, 0}; auto table = cudf::table_view{{c_0, c_1}}; auto col_ref_0 = cudf::ast::column_reference(0); auto col_ref_1 = cudf::ast::column_reference(1); auto expression = cudf::ast::operation(cudf::ast::ast_operator::LESS, col_ref_0, col_ref_1); auto expected = column_wrapper<bool>{true, false, true, false}; auto result = cudf::compute_column(table, expression); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, LessComparatorLarge) { auto a = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i * 2; }); auto b = thrust::make_counting_iterator(500); auto c_0 = column_wrapper<int32_t>(a, a + 2000); auto c_1 = column_wrapper<int32_t>(b, b + 2000); auto table = cudf::table_view{{c_0, c_1}}; auto col_ref_0 = cudf::ast::column_reference(0); auto col_ref_1 = cudf::ast::column_reference(1); auto expression = cudf::ast::operation(cudf::ast::ast_operator::LESS, col_ref_0, col_ref_1); auto c = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i < 500; }); auto expected = column_wrapper<bool>(c, c + 2000); auto result = cudf::compute_column(table, expression); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, MultiLevelTreeArithmetic) { auto c_0 = column_wrapper<int32_t>{3, 20, 1, 50}; auto c_1 = column_wrapper<int32_t>{10, 7, 20, 0}; auto c_2 = column_wrapper<int32_t>{-3, 66, 2, -99}; auto table = cudf::table_view{{c_0, c_1, c_2}}; auto col_ref_0 = cudf::ast::column_reference(0); auto col_ref_1 = cudf::ast::column_reference(1); auto col_ref_2 = cudf::ast::column_reference(2); auto expression_left_subtree = cudf::ast::operation(cudf::ast::ast_operator::ADD, col_ref_0, col_ref_1); auto expression_right_subtree = cudf::ast::operation(cudf::ast::ast_operator::SUB, col_ref_2, col_ref_0); auto expression_tree = cudf::ast::operation( cudf::ast::ast_operator::ADD, expression_left_subtree, expression_right_subtree); auto result = cudf::compute_column(table, expression_tree); auto expected = column_wrapper<int32_t>{7, 73, 22, -99}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, MultiLevelTreeArithmeticLarge) { auto a = thrust::make_counting_iterator(0); auto b = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i + 1; }); auto c = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i * 2; }); auto c_0 = column_wrapper<int32_t>(a, a + 2000); auto c_1 = column_wrapper<int32_t>(b, b + 2000); auto c_2 = column_wrapper<int32_t>(c, c + 2000); auto table = cudf::table_view{{c_0, c_1, c_2}}; auto col_ref_0 = cudf::ast::column_reference(0); auto col_ref_1 = cudf::ast::column_reference(1); auto col_ref_2 = cudf::ast::column_reference(2); auto expr_left_subtree = cudf::ast::operation(cudf::ast::ast_operator::MUL, col_ref_0, col_ref_1); auto expr_right_subtree = cudf::ast::operation(cudf::ast::ast_operator::ADD, col_ref_2, col_ref_0); auto expr_tree = cudf::ast::operation(cudf::ast::ast_operator::SUB, expr_left_subtree, expr_right_subtree); auto result = cudf::compute_column(table, expr_tree); auto calc = [](auto i) { return (i * (i + 1)) - (i + (i * 2)); }; auto d = cudf::detail::make_counting_transform_iterator(0, [&](auto i) { return calc(i); }); auto expected = column_wrapper<int32_t>(d, d + 2000); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, ImbalancedTreeArithmetic) { auto c_0 = column_wrapper<double>{0.15, 0.37, 4.2, 21.3}; auto c_1 = column_wrapper<double>{0.0, -42.0, 1.0, 98.6}; auto c_2 = column_wrapper<double>{0.6, std::numeric_limits<double>::infinity(), 0.999, 1.0}; auto table = cudf::table_view{{c_0, c_1, c_2}}; auto col_ref_0 = cudf::ast::column_reference(0); auto col_ref_1 = cudf::ast::column_reference(1); auto col_ref_2 = cudf::ast::column_reference(2); auto expression_right_subtree = cudf::ast::operation(cudf::ast::ast_operator::MUL, col_ref_0, col_ref_1); auto expression_tree = cudf::ast::operation(cudf::ast::ast_operator::SUB, col_ref_2, expression_right_subtree); auto result = cudf::compute_column(table, expression_tree); auto expected = column_wrapper<double>{0.6, std::numeric_limits<double>::infinity(), -3.201, -2099.18}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, ImbalancedTreeArithmeticDeep) { auto c_0 = column_wrapper<int64_t>{4, 5, 6}; auto table = cudf::table_view{{c_0}}; auto col_ref_0 = cudf::ast::column_reference(0); // expression: (c0 < c0) == (c0 < (c0 + c0)) // {false, false, false} == (c0 < {8, 10, 12}) // {false, false, false} == {true, true, true} // {false, false, false} auto expression_left_subtree = cudf::ast::operation(cudf::ast::ast_operator::LESS, col_ref_0, col_ref_0); auto expression_right_inner_subtree = cudf::ast::operation(cudf::ast::ast_operator::ADD, col_ref_0, col_ref_0); auto expression_right_subtree = cudf::ast::operation(cudf::ast::ast_operator::LESS, col_ref_0, expression_right_inner_subtree); auto expression_tree = cudf::ast::operation( cudf::ast::ast_operator::EQUAL, expression_left_subtree, expression_right_subtree); auto result = cudf::compute_column(table, expression_tree); auto expected = column_wrapper<bool>{false, false, false}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, DeeplyNestedArithmeticLogicalExpression) { // Test logic for deeply nested arithmetic and logical expressions. constexpr int64_t left_depth_level = 100; constexpr int64_t right_depth_level = 75; auto generate_ast_expr = [](int64_t depth_level, cudf::ast::column_reference col_ref, cudf::ast::ast_operator root_operator, cudf::ast::ast_operator arithmetic_operator, bool nested_left_tree) { // Note that a std::list is required here because of its guarantees against reference // invalidation when items are added or removed. References to items in a std::vector are not // safe if the vector must re-allocate. auto expressions = std::list<cudf::ast::operation>(); auto op = arithmetic_operator; expressions.push_back(cudf::ast::operation(op, col_ref, col_ref)); for (int64_t i = 0; i < depth_level - 1; i++) { if (i == depth_level - 2) { op = root_operator; } else { op = arithmetic_operator; } if (nested_left_tree) { expressions.push_back(cudf::ast::operation(op, expressions.back(), col_ref)); } else { expressions.push_back(cudf::ast::operation(op, col_ref, expressions.back())); } } return expressions; }; auto c_0 = column_wrapper<int64_t>{0, 0, 0}; auto c_1 = column_wrapper<int32_t>{0, 0, 0}; auto table = cudf::table_view{{c_0, c_1}}; auto col_ref_0 = cudf::ast::column_reference(0); auto col_ref_1 = cudf::ast::column_reference(1); auto left_expression = generate_ast_expr(left_depth_level, col_ref_0, cudf::ast::ast_operator::LESS, cudf::ast::ast_operator::ADD, false); auto right_expression = generate_ast_expr(right_depth_level, col_ref_1, cudf::ast::ast_operator::EQUAL, cudf::ast::ast_operator::SUB, true); auto expression_tree = cudf::ast::operation( cudf::ast::ast_operator::LOGICAL_OR, left_expression.back(), right_expression.back()); // Expression: // OR(<(+(+(+(+($0, $0), $0), $0), $0), $0), ==($1, -($1, -($1, -($1, -($1, $1)))))) // ... // OR(<($L, $0), ==($1, $R)) // true // // Breakdown: // - Left Operand ($L): (+(+(+(+($0, $0), $0), $0), $0), $0) // - Right Operand ($R): -($1, -($1, -($1, -($1, $1)))) // Explanation: // If all $1 values and $R values are zeros, the result is true because of the equality check // combined with the OR operator in OR(<($L, $0), ==($1, $R)). auto result = cudf::compute_column(table, expression_tree); auto expected = column_wrapper<bool>{true, true, true}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, MultiLevelTreeComparator) { auto c_0 = column_wrapper<int32_t>{3, 20, 1, 50}; auto c_1 = column_wrapper<int32_t>{10, 7, 20, 0}; auto c_2 = column_wrapper<int32_t>{-3, 66, 2, -99}; auto table = cudf::table_view{{c_0, c_1, c_2}}; auto col_ref_0 = cudf::ast::column_reference(0); auto col_ref_1 = cudf::ast::column_reference(1); auto col_ref_2 = cudf::ast::column_reference(2); auto expression_left_subtree = cudf::ast::operation(cudf::ast::ast_operator::GREATER_EQUAL, col_ref_0, col_ref_1); auto expression_right_subtree = cudf::ast::operation(cudf::ast::ast_operator::GREATER, col_ref_2, col_ref_0); auto expression_tree = cudf::ast::operation( cudf::ast::ast_operator::LOGICAL_AND, expression_left_subtree, expression_right_subtree); auto result = cudf::compute_column(table, expression_tree); auto expected = column_wrapper<bool>{false, true, false, false}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, MultiTypeOperationFailure) { auto c_0 = column_wrapper<int32_t>{3, 20, 1, 50}; auto c_1 = column_wrapper<double>{0.15, 0.77, 4.2, 21.3}; auto table = cudf::table_view{{c_0, c_1}}; auto col_ref_0 = cudf::ast::column_reference(0); auto col_ref_1 = cudf::ast::column_reference(1); auto expression_0_plus_1 = cudf::ast::operation(cudf::ast::ast_operator::ADD, col_ref_0, col_ref_1); auto expression_1_plus_0 = cudf::ast::operation(cudf::ast::ast_operator::ADD, col_ref_1, col_ref_0); // Operations on different types are not allowed EXPECT_THROW(cudf::compute_column(table, expression_0_plus_1), cudf::logic_error); EXPECT_THROW(cudf::compute_column(table, expression_1_plus_0), cudf::logic_error); } TEST_F(TransformTest, LiteralComparison) { auto c_0 = column_wrapper<int32_t>{3, 20, 1, 50}; auto table = cudf::table_view{{c_0}}; auto col_ref_0 = cudf::ast::column_reference(0); auto literal_value = cudf::numeric_scalar<int32_t>(41); auto literal = cudf::ast::literal(literal_value); auto expression = cudf::ast::operation(cudf::ast::ast_operator::GREATER, col_ref_0, literal); auto result = cudf::compute_column(table, expression); auto expected = column_wrapper<bool>{false, false, false, true}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, UnaryNot) { auto c_0 = column_wrapper<int32_t>{3, 0, 1, 50}; auto table = cudf::table_view{{c_0}}; auto col_ref_0 = cudf::ast::column_reference(0); auto expression = cudf::ast::operation(cudf::ast::ast_operator::NOT, col_ref_0); auto result = cudf::compute_column(table, expression); auto expected = column_wrapper<bool>{false, true, false, false}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, UnaryTrigonometry) { auto c_0 = column_wrapper<double>{0.0, M_PI / 4, M_PI / 3}; auto table = cudf::table_view{{c_0}}; auto col_ref_0 = cudf::ast::column_reference(0); auto expected_sin = column_wrapper<double>{0.0, std::sqrt(2) / 2, std::sqrt(3.0) / 2.0}; auto expression_sin = cudf::ast::operation(cudf::ast::ast_operator::SIN, col_ref_0); auto result_sin = cudf::compute_column(table, expression_sin); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_sin, result_sin->view(), verbosity); auto expected_cos = column_wrapper<double>{1.0, std::sqrt(2) / 2, 0.5}; auto expression_cos = cudf::ast::operation(cudf::ast::ast_operator::COS, col_ref_0); auto result_cos = cudf::compute_column(table, expression_cos); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_cos, result_cos->view(), verbosity); auto expected_tan = column_wrapper<double>{0.0, 1.0, std::sqrt(3.0)}; auto expression_tan = cudf::ast::operation(cudf::ast::ast_operator::TAN, col_ref_0); auto result_tan = cudf::compute_column(table, expression_tan); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_tan, result_tan->view(), verbosity); } TEST_F(TransformTest, ArityCheckFailure) { auto col_ref_0 = cudf::ast::column_reference(0); EXPECT_THROW(cudf::ast::operation(cudf::ast::ast_operator::ADD, col_ref_0), cudf::logic_error); EXPECT_THROW(cudf::ast::operation(cudf::ast::ast_operator::ABS, col_ref_0, col_ref_0), cudf::logic_error); } TEST_F(TransformTest, StringComparison) { auto c_0 = cudf::test::strings_column_wrapper({"a", "bb", "ccc", "dddd"}); auto c_1 = cudf::test::strings_column_wrapper({"aa", "b", "cccc", "ddd"}); auto table = cudf::table_view{{c_0, c_1}}; auto col_ref_0 = cudf::ast::column_reference(0); auto col_ref_1 = cudf::ast::column_reference(1); auto expression = cudf::ast::operation(cudf::ast::ast_operator::LESS, col_ref_0, col_ref_1); auto expected = column_wrapper<bool>{true, false, true, false}; auto result = cudf::compute_column(table, expression); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, StringScalarComparison) { auto c_0 = cudf::test::strings_column_wrapper({"1", "12", "123", "23"}, {true, true, false, true}); auto table = cudf::table_view{{c_0}}; auto literal_value = cudf::string_scalar("2"); auto literal = cudf::ast::literal(literal_value); auto col_ref_0 = cudf::ast::column_reference(0); auto expression = cudf::ast::operation(cudf::ast::ast_operator::LESS, col_ref_0, literal); auto expected = column_wrapper<bool>{{true, true, true, false}, {true, true, false, true}}; auto result = cudf::compute_column(table, expression); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); // compare with null literal literal_value.set_valid_async(false); auto expected2 = column_wrapper<bool>{{false, false, false, false}, {false, false, false, false}}; auto result2 = cudf::compute_column(table, expression); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, NumericScalarComparison) { auto c_0 = column_wrapper<int32_t>{1, 12, 123, 23}; auto table = cudf::table_view{{c_0}}; auto literal_value = cudf::numeric_scalar<int32_t>(2); auto literal = cudf::ast::literal(literal_value); auto col_ref_0 = cudf::ast::column_reference(0); auto expression = cudf::ast::operation(cudf::ast::ast_operator::LESS, col_ref_0, literal); auto expected = column_wrapper<bool>{true, false, false, false}; auto result = cudf::compute_column(table, expression); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, CopyColumn) { auto c_0 = column_wrapper<int32_t>{3, 0, 1, 50}; auto table = cudf::table_view{{c_0}}; auto col_ref_0 = cudf::ast::column_reference(0); auto expression = cudf::ast::operation(cudf::ast::ast_operator::IDENTITY, col_ref_0); auto result = cudf::compute_column(table, expression); auto expected = column_wrapper<int32_t>{3, 0, 1, 50}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, CopyLiteral) { auto c_0 = column_wrapper<int32_t>{0, 0, 0, 0}; auto table = cudf::table_view{{c_0}}; auto literal_value = cudf::numeric_scalar<int32_t>(-123); auto literal = cudf::ast::literal(literal_value); auto expression = cudf::ast::operation(cudf::ast::ast_operator::IDENTITY, literal); auto result = cudf::compute_column(table, expression); auto expected = column_wrapper<int32_t>{-123, -123, -123, -123}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, TrueDiv) { auto c_0 = column_wrapper<int32_t>{3, 0, 1, 50}; auto table = cudf::table_view{{c_0}}; auto col_ref_0 = cudf::ast::column_reference(0); auto literal_value = cudf::numeric_scalar<int32_t>(2); auto literal = cudf::ast::literal(literal_value); auto expression = cudf::ast::operation(cudf::ast::ast_operator::TRUE_DIV, col_ref_0, literal); auto result = cudf::compute_column(table, expression); auto expected = column_wrapper<double>{1.5, 0.0, 0.5, 25.0}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, FloorDiv) { auto c_0 = column_wrapper<double>{3.0, 0.0, 1.0, 50.0}; auto table = cudf::table_view{{c_0}}; auto col_ref_0 = cudf::ast::column_reference(0); auto literal_value = cudf::numeric_scalar<double>(2.0); auto literal = cudf::ast::literal(literal_value); auto expression = cudf::ast::operation(cudf::ast::ast_operator::FLOOR_DIV, col_ref_0, literal); auto result = cudf::compute_column(table, expression); auto expected = column_wrapper<double>{1.0, 0.0, 0.0, 25.0}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, Mod) { auto c_0 = column_wrapper<double>{3.0, 0.0, -1.0, -50.0}; auto table = cudf::table_view{{c_0}}; auto col_ref_0 = cudf::ast::column_reference(0); auto literal_value = cudf::numeric_scalar<double>(2.0); auto literal = cudf::ast::literal(literal_value); auto expression = cudf::ast::operation(cudf::ast::ast_operator::MOD, col_ref_0, literal); auto result = cudf::compute_column(table, expression); auto expected = column_wrapper<double>{1.0, 0.0, -1.0, 0.0}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, PyMod) { auto c_0 = column_wrapper<double>{3.0, 0.0, -1.0, -50.0}; auto table = cudf::table_view{{c_0}}; auto col_ref_0 = cudf::ast::column_reference(0); auto literal_value = cudf::numeric_scalar<double>(2.0); auto literal = cudf::ast::literal(literal_value); auto expression = cudf::ast::operation(cudf::ast::ast_operator::PYMOD, col_ref_0, literal); auto result = cudf::compute_column(table, expression); auto expected = column_wrapper<double>{1.0, 0.0, 1.0, 0.0}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, BasicEqualityNullEqualNoNulls) { auto c_0 = column_wrapper<int32_t>{3, 20, 1, 50}; auto c_1 = column_wrapper<int32_t>{3, 7, 1, 0}; auto table = cudf::table_view{{c_0, c_1}}; auto col_ref_0 = cudf::ast::column_reference(0); auto col_ref_1 = cudf::ast::column_reference(1); auto expression = cudf::ast::operation(cudf::ast::ast_operator::NULL_EQUAL, col_ref_0, col_ref_1); auto expected = column_wrapper<bool>{true, false, true, false}; auto result = cudf::compute_column(table, expression); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, BasicEqualityNormalEqualWithNulls) { auto c_0 = column_wrapper<int32_t>{{3, 20, 1, 50}, {1, 1, 0, 0}}; auto c_1 = column_wrapper<int32_t>{{3, 7, 1, 0}, {1, 1, 0, 0}}; auto table = cudf::table_view{{c_0, c_1}}; auto col_ref_0 = cudf::ast::column_reference(0); auto col_ref_1 = cudf::ast::column_reference(1); auto expression = cudf::ast::operation(cudf::ast::ast_operator::EQUAL, col_ref_0, col_ref_1); auto expected = column_wrapper<bool>{{true, false, true, true}, {1, 1, 0, 0}}; auto result = cudf::compute_column(table, expression); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, BasicEqualityNulls) { auto c_0 = column_wrapper<int32_t>{{3, 20, 1, 2, 50}, {1, 1, 0, 1, 0}}; auto c_1 = column_wrapper<int32_t>{{3, 7, 1, 2, 0}, {1, 1, 1, 0, 0}}; auto table = cudf::table_view{{c_0, c_1}}; auto col_ref_0 = cudf::ast::column_reference(0); auto col_ref_1 = cudf::ast::column_reference(1); auto expression = cudf::ast::operation(cudf::ast::ast_operator::NULL_EQUAL, col_ref_0, col_ref_1); auto expected = column_wrapper<bool>{{true, false, false, false, true}, {1, 1, 1, 1, 1}}; auto result = cudf::compute_column(table, expression); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, UnaryNotNulls) { auto c_0 = column_wrapper<int32_t>{{3, 0, 0, 50}, {0, 0, 1, 1}}; auto table = cudf::table_view{{c_0}}; auto col_ref_0 = cudf::ast::column_reference(0); auto expression = cudf::ast::operation(cudf::ast::ast_operator::NOT, col_ref_0); auto result = cudf::compute_column(table, expression); auto expected = column_wrapper<bool>{{false, true, true, false}, {0, 0, 1, 1}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, BasicAdditionNulls) { auto c_0 = column_wrapper<int32_t>{{3, 20, 1, 50}, {0, 0, 1, 1}}; auto c_1 = column_wrapper<int32_t>{{10, 7, 20, 0}, {0, 1, 0, 1}}; auto table = cudf::table_view{{c_0, c_1}}; auto col_ref_0 = cudf::ast::column_reference(0); auto col_ref_1 = cudf::ast::column_reference(1); auto expression = cudf::ast::operation(cudf::ast::ast_operator::ADD, col_ref_0, col_ref_1); auto expected = column_wrapper<int32_t>{{0, 0, 0, 50}, {0, 0, 0, 1}}; auto result = cudf::compute_column(table, expression); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, BasicAdditionLargeNulls) { auto N = 2000; auto a = thrust::make_counting_iterator(0); auto validities = std::vector<int32_t>(N); std::fill(validities.begin(), validities.begin() + N / 2, 0); std::fill(validities.begin() + (N / 2), validities.end(), 0); std::random_device rd; std::mt19937 gen(rd()); std::shuffle(validities.begin(), validities.end(), gen); auto col = column_wrapper<int32_t>(a, a + N, validities.begin()); auto table = cudf::table_view{{col}}; auto col_ref = cudf::ast::column_reference(0); auto expression = cudf::ast::operation(cudf::ast::ast_operator::ADD, col_ref, col_ref); auto b = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i * 2; }); auto expected = column_wrapper<int32_t>(b, b + N, validities.begin()); auto result = cudf::compute_column(table, expression); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, NullLogicalAnd) { auto c_0 = column_wrapper<bool>{{false, false, true, true, false, false, true, true}, {1, 1, 1, 1, 1, 0, 0, 0}}; auto c_1 = column_wrapper<bool>{{false, true, false, true, true, true, false, true}, {1, 1, 1, 1, 0, 1, 1, 0}}; auto table = cudf::table_view{{c_0, c_1}}; auto col_ref_0 = cudf::ast::column_reference(0); auto col_ref_1 = cudf::ast::column_reference(1); auto expression = cudf::ast::operation(cudf::ast::ast_operator::NULL_LOGICAL_AND, col_ref_0, col_ref_1); auto expected = column_wrapper<bool>{{false, false, false, true, false, false, false, true}, {1, 1, 1, 1, 1, 0, 1, 0}}; auto result = cudf::compute_column(table, expression); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } TEST_F(TransformTest, NullLogicalOr) { auto c_0 = column_wrapper<bool>{{false, false, true, true, false, false, true, true}, {1, 1, 1, 1, 1, 0, 1, 0}}; auto c_1 = column_wrapper<bool>{{false, true, false, true, true, true, false, true}, {1, 1, 1, 1, 0, 1, 0, 0}}; auto table = cudf::table_view{{c_0, c_1}}; auto col_ref_0 = cudf::ast::column_reference(0); auto col_ref_1 = cudf::ast::column_reference(1); auto expression = cudf::ast::operation(cudf::ast::ast_operator::NULL_LOGICAL_OR, col_ref_0, col_ref_1); auto expected = column_wrapper<bool>{{false, true, true, true, false, true, true, true}, {1, 1, 1, 1, 0, 1, 1, 0}}; auto result = cudf::compute_column(table, expression); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view(), verbosity); } CUDF_TEST_PROGRAM_MAIN()
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/reductions/scan_tests.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <tests/reductions/scan_tests.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf/detail/aggregation/aggregation.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/detail/utilities/device_operators.cuh> #include <cudf/reduction.hpp> #include <thrust/host_vector.h> #include <thrust/iterator/zip_iterator.h> #include <thrust/tuple.h> #include <algorithm> #include <numeric> using aggregation = cudf::aggregation; using scan_aggregation = cudf::scan_aggregation; using cudf::null_policy; using cudf::scan_type; // This is the main test feature template <typename T> struct ScanTest : public BaseScanTest<T> { using HostType = typename BaseScanTest<T>::HostType; void scan_test(cudf::host_span<HostType const> v, cudf::host_span<bool const> b, scan_aggregation const& agg, scan_type inclusive, null_policy null_handling, numeric::scale_type scale) { auto col_in = this->make_column(v, b, scale); if (not this->params_supported(agg, inclusive)) { EXPECT_THROW(scan(*col_in, agg, inclusive, null_handling), cudf::logic_error); } else { auto expected_col_out = this->make_expected(v, b, agg, inclusive, null_handling, scale); auto col_out = scan(*col_in, agg, inclusive, null_handling); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*expected_col_out, *col_out); EXPECT_FALSE(cudf::has_nonempty_nulls(col_out->view())); } } // Overload to iterate the test over a few different scales for fixed-point tests void scan_test(cudf::host_span<HostType const> v, cudf::host_span<bool const> b, scan_aggregation const& agg, scan_type inclusive, null_policy null_handling = null_policy::EXCLUDE) { if constexpr (cudf::is_fixed_point<T>()) { for (auto scale : {0, -1, -2, -3}) { scan_test(v, b, agg, inclusive, null_handling, numeric::scale_type{scale}); } } else { scan_test(v, b, agg, inclusive, null_handling, numeric::scale_type{0}); } } bool params_supported(scan_aggregation const& agg, scan_type inclusive) { bool supported = [&] { switch (agg.kind) { case aggregation::SUM: return std::is_invocable_v<cudf::DeviceSum, T, T>; case aggregation::PRODUCT: return std::is_invocable_v<cudf::DeviceProduct, T, T>; case aggregation::MIN: return std::is_invocable_v<cudf::DeviceMin, T, T>; case aggregation::MAX: return std::is_invocable_v<cudf::DeviceMax, T, T>; case aggregation::RANK: return std::is_invocable_v<cudf::DeviceMax, T, T>; // comparable default: return false; } return false; }(); // special cases for individual types if constexpr (cudf::is_fixed_point<T>()) return supported && (agg.kind != aggregation::PRODUCT); if constexpr (std::is_same_v<T, cudf::string_view> || cudf::is_timestamp<T>()) return supported && (inclusive == scan_type::INCLUSIVE); return supported; } std::function<HostType(HostType, HostType)> make_agg(scan_aggregation const& agg) { if constexpr (std::is_same_v<T, cudf::string_view>) { switch (agg.kind) { case aggregation::MIN: return [](HostType a, HostType b) { return std::min(a, b); }; case aggregation::MAX: return [](HostType a, HostType b) { return std::max(a, b); }; default: { CUDF_FAIL("Unsupported aggregation"); return [](HostType a, HostType b) { return std::min(a, b); }; } } } else { switch (agg.kind) { case aggregation::SUM: return std::plus<HostType>{}; case aggregation::PRODUCT: return std::multiplies<HostType>{}; case aggregation::MIN: return [](HostType a, HostType b) { return std::min(a, b); }; case aggregation::MAX: return [](HostType a, HostType b) { return std::max(a, b); }; default: { CUDF_FAIL("Unsupported aggregation"); return [](HostType a, HostType b) { return std::min(a, b); }; } } } } HostType make_identity(scan_aggregation const& agg) { if constexpr (std::is_same_v<T, cudf::string_view>) { switch (agg.kind) { case aggregation::MIN: return std::string{"\xF7\xBF\xBF\xBF"}; case aggregation::MAX: return std::string{}; default: CUDF_FAIL("Unsupported aggregation"); } } else { switch (agg.kind) { case aggregation::SUM: return HostType{0}; case aggregation::PRODUCT: return HostType{1}; case aggregation::MIN: if constexpr (std::numeric_limits<HostType>::has_infinity) { return std::numeric_limits<HostType>::infinity(); } else { return std::numeric_limits<HostType>::max(); } case aggregation::MAX: if constexpr (std::numeric_limits<HostType>::has_infinity) { return -std::numeric_limits<HostType>::infinity(); } else { return std::numeric_limits<HostType>::lowest(); } default: CUDF_FAIL("Unsupported aggregation"); } } } std::unique_ptr<cudf::column> make_expected(cudf::host_span<HostType const> v, cudf::host_span<bool const> b, scan_aggregation const& agg, scan_type inclusive, null_policy null_handling, numeric::scale_type scale = numeric::scale_type{0}) { auto op = this->make_agg(agg); auto identity = this->make_identity(agg); thrust::host_vector<HostType> expected(v.size()); thrust::host_vector<bool> b_out(b.begin(), b.end()); bool const nullable = (b.size() > 0); auto masked_value = [identity](auto const& z) { return thrust::get<1>(z) ? thrust::get<0>(z) : identity; }; if (inclusive == scan_type::INCLUSIVE) { if (nullable) { std::transform_inclusive_scan( thrust::make_zip_iterator(thrust::make_tuple(v.begin(), b.begin())), thrust::make_zip_iterator(thrust::make_tuple(v.end(), b.end())), expected.begin(), op, masked_value); if (null_handling == null_policy::INCLUDE) { std::inclusive_scan(b.begin(), b.end(), b_out.begin(), std::logical_and<bool>{}); } } else { std::inclusive_scan(v.begin(), v.end(), expected.begin(), op); } } else { if (nullable) { std::transform_exclusive_scan( thrust::make_zip_iterator(thrust::make_tuple(v.begin(), b.begin())), thrust::make_zip_iterator(thrust::make_tuple(v.end(), b.end())), expected.begin(), identity, op, masked_value); if (null_handling == null_policy::INCLUDE) { std::exclusive_scan(b.begin(), b.end(), b_out.begin(), true, std::logical_and<bool>{}); } } else { std::exclusive_scan(v.begin(), v.end(), expected.begin(), identity, op); } } return nullable ? this->make_column(expected, b_out, scale) : this->make_column(expected, {}, scale); } }; using TestTypes = cudf::test:: Concat<cudf::test::NumericTypes, cudf::test::FixedPointTypes, cudf::test::StringTypes>; TYPED_TEST_SUITE(ScanTest, TestTypes); TYPED_TEST(ScanTest, Min) { auto const v = make_vector<TypeParam>({123, 64, 63, 99, -5, 123, -16, -120, -111}); auto const b = thrust::host_vector<bool>(std::vector<bool>{1, 0, 1, 1, 1, 1, 0, 0, 1}); // no nulls this->scan_test(v, {}, *cudf::make_min_aggregation<scan_aggregation>(), scan_type::INCLUSIVE); this->scan_test(v, {}, *cudf::make_min_aggregation<scan_aggregation>(), scan_type::EXCLUSIVE); // skipna = true (default) this->scan_test(v, b, *cudf::make_min_aggregation<scan_aggregation>(), scan_type::INCLUSIVE, null_policy::EXCLUDE); this->scan_test(v, b, *cudf::make_min_aggregation<scan_aggregation>(), scan_type::EXCLUSIVE, null_policy::EXCLUDE); // skipna = false this->scan_test(v, b, *cudf::make_min_aggregation<scan_aggregation>(), scan_type::INCLUSIVE, null_policy::INCLUDE); this->scan_test(v, b, *cudf::make_min_aggregation<scan_aggregation>(), scan_type::EXCLUSIVE, null_policy::INCLUDE); } TYPED_TEST(ScanTest, Max) { auto const v = make_vector<TypeParam>({-120, 5, 0, -120, -111, 64, 63, 99, 123, -16}); auto const b = thrust::host_vector<bool>(std::vector<bool>{1, 0, 1, 1, 1, 1, 0, 1, 0, 1}); // inclusive // no nulls this->scan_test(v, {}, *cudf::make_max_aggregation<scan_aggregation>(), scan_type::INCLUSIVE); this->scan_test(v, {}, *cudf::make_max_aggregation<scan_aggregation>(), scan_type::EXCLUSIVE); // skipna = true (default) this->scan_test(v, b, *cudf::make_max_aggregation<scan_aggregation>(), scan_type::INCLUSIVE, null_policy::EXCLUDE); this->scan_test(v, b, *cudf::make_max_aggregation<scan_aggregation>(), scan_type::EXCLUSIVE, null_policy::EXCLUDE); // skipna = false this->scan_test(v, b, *cudf::make_max_aggregation<scan_aggregation>(), scan_type::INCLUSIVE, null_policy::INCLUDE); this->scan_test(v, b, *cudf::make_max_aggregation<scan_aggregation>(), scan_type::EXCLUSIVE, null_policy::INCLUDE); } TYPED_TEST(ScanTest, Product) { auto const v = make_vector<TypeParam>({5, -1, 1, 3, -2, 4}); auto const b = thrust::host_vector<bool>(std::vector<bool>{1, 1, 1, 0, 1, 1}); // no nulls this->scan_test(v, {}, *cudf::make_product_aggregation<scan_aggregation>(), scan_type::INCLUSIVE); this->scan_test(v, {}, *cudf::make_product_aggregation<scan_aggregation>(), scan_type::EXCLUSIVE); // skipna = true (default) this->scan_test(v, b, *cudf::make_product_aggregation<scan_aggregation>(), scan_type::INCLUSIVE, null_policy::EXCLUDE); this->scan_test(v, b, *cudf::make_product_aggregation<scan_aggregation>(), scan_type::EXCLUSIVE, null_policy::EXCLUDE); // skipna = false this->scan_test(v, b, *cudf::make_product_aggregation<scan_aggregation>(), scan_type::INCLUSIVE, null_policy::INCLUDE); this->scan_test(v, b, *cudf::make_product_aggregation<scan_aggregation>(), scan_type::EXCLUSIVE, null_policy::INCLUDE); } TYPED_TEST(ScanTest, Sum) { auto const v = [] { if (std::is_signed_v<TypeParam>) return make_vector<TypeParam>({-120, 5, 6, 113, -111, 64, -63, 9, 34, -16}); return make_vector<TypeParam>({12, 5, 6, 13, 11, 14, 3, 9, 34, 16}); }(); auto const b = thrust::host_vector<bool>(std::vector<bool>{1, 0, 1, 1, 0, 0, 1, 1, 1, 1}); // no nulls this->scan_test(v, {}, *cudf::make_sum_aggregation<scan_aggregation>(), scan_type::INCLUSIVE); this->scan_test(v, {}, *cudf::make_sum_aggregation<scan_aggregation>(), scan_type::EXCLUSIVE); // skipna = true (default) this->scan_test(v, b, *cudf::make_sum_aggregation<scan_aggregation>(), scan_type::INCLUSIVE, null_policy::EXCLUDE); this->scan_test(v, b, *cudf::make_sum_aggregation<scan_aggregation>(), scan_type::EXCLUSIVE, null_policy::EXCLUDE); // skipna = false this->scan_test(v, b, *cudf::make_sum_aggregation<scan_aggregation>(), scan_type::INCLUSIVE, null_policy::INCLUDE); this->scan_test(v, b, *cudf::make_sum_aggregation<scan_aggregation>(), scan_type::EXCLUSIVE, null_policy::INCLUDE); } TYPED_TEST(ScanTest, EmptyColumn) { auto const v = thrust::host_vector<typename TypeParam_to_host_type<TypeParam>::type>{}; auto const b = thrust::host_vector<bool>{}; // skipna = true (default) this->scan_test(v, b, *cudf::make_min_aggregation<scan_aggregation>(), scan_type::INCLUSIVE, null_policy::EXCLUDE); this->scan_test(v, b, *cudf::make_min_aggregation<scan_aggregation>(), scan_type::EXCLUSIVE, null_policy::EXCLUDE); // skipna = false this->scan_test(v, b, *cudf::make_min_aggregation<scan_aggregation>(), scan_type::INCLUSIVE, null_policy::INCLUDE); this->scan_test(v, b, *cudf::make_min_aggregation<scan_aggregation>(), scan_type::EXCLUSIVE, null_policy::INCLUDE); } TYPED_TEST(ScanTest, LeadingNulls) { auto const v = make_vector<TypeParam>({100, 200, 300}); auto const b = thrust::host_vector<bool>(std::vector<bool>{0, 1, 1}); // skipna = true (default) this->scan_test(v, b, *cudf::make_min_aggregation<scan_aggregation>(), scan_type::INCLUSIVE, null_policy::EXCLUDE); this->scan_test(v, b, *cudf::make_min_aggregation<scan_aggregation>(), scan_type::EXCLUSIVE, null_policy::EXCLUDE); // skipna = false this->scan_test(v, b, *cudf::make_min_aggregation<scan_aggregation>(), scan_type::INCLUSIVE, null_policy::INCLUDE); this->scan_test(v, b, *cudf::make_min_aggregation<scan_aggregation>(), scan_type::EXCLUSIVE, null_policy::INCLUDE); } class ScanStringsTest : public ScanTest<cudf::string_view> {}; TEST_F(ScanStringsTest, MoreStringsMinMax) { int row_count = 512; auto data_begin = cudf::detail::make_counting_transform_iterator(0, [](auto idx) { char const s[] = {static_cast<char>('a' + (idx % 26)), 0}; return std::string(s); }); auto validity = cudf::detail::make_counting_transform_iterator( 0, [](auto idx) -> bool { return (idx % 23) != 22; }); cudf::test::strings_column_wrapper col(data_begin, data_begin + row_count, validity); thrust::host_vector<std::string> v(data_begin, data_begin + row_count); thrust::host_vector<bool> b(validity, validity + row_count); this->scan_test(v, {}, *cudf::make_min_aggregation<scan_aggregation>(), scan_type::INCLUSIVE); this->scan_test(v, b, *cudf::make_min_aggregation<scan_aggregation>(), scan_type::INCLUSIVE); this->scan_test(v, b, *cudf::make_min_aggregation<scan_aggregation>(), scan_type::INCLUSIVE, null_policy::EXCLUDE); this->scan_test(v, {}, *cudf::make_min_aggregation<scan_aggregation>(), scan_type::EXCLUSIVE); this->scan_test(v, b, *cudf::make_min_aggregation<scan_aggregation>(), scan_type::EXCLUSIVE); this->scan_test(v, b, *cudf::make_min_aggregation<scan_aggregation>(), scan_type::EXCLUSIVE, null_policy::EXCLUDE); this->scan_test(v, {}, *cudf::make_max_aggregation<scan_aggregation>(), scan_type::INCLUSIVE); this->scan_test(v, b, *cudf::make_max_aggregation<scan_aggregation>(), scan_type::INCLUSIVE); this->scan_test(v, b, *cudf::make_max_aggregation<scan_aggregation>(), scan_type::INCLUSIVE, null_policy::EXCLUDE); this->scan_test(v, {}, *cudf::make_max_aggregation<scan_aggregation>(), scan_type::EXCLUSIVE); this->scan_test(v, b, *cudf::make_max_aggregation<scan_aggregation>(), scan_type::EXCLUSIVE); this->scan_test(v, b, *cudf::make_max_aggregation<scan_aggregation>(), scan_type::EXCLUSIVE, null_policy::EXCLUDE); } template <typename T> struct ScanChronoTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(ScanChronoTest, cudf::test::ChronoTypes); TYPED_TEST(ScanChronoTest, ChronoMinMax) { cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> col({5, 4, 6, 0, 1, 6, 5, 3}, {1, 1, 1, 0, 1, 1, 1, 1}); cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> expected_min({5, 4, 4, 0, 1, 1, 1, 1}, {1, 1, 1, 0, 1, 1, 1, 1}); auto result = cudf::scan(col, *cudf::make_min_aggregation<scan_aggregation>(), cudf::scan_type::INCLUSIVE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result->view(), expected_min); result = cudf::scan(col, *cudf::make_min_aggregation<scan_aggregation>(), cudf::scan_type::INCLUSIVE, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result->view(), expected_min); cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> expected_max({5, 5, 6, 0, 6, 6, 6, 6}, {1, 1, 1, 0, 1, 1, 1, 1}); result = cudf::scan(col, *cudf::make_max_aggregation<scan_aggregation>(), cudf::scan_type::INCLUSIVE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result->view(), expected_max); result = cudf::scan(col, *cudf::make_max_aggregation<scan_aggregation>(), cudf::scan_type::INCLUSIVE, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result->view(), expected_max); EXPECT_THROW( cudf::scan(col, *cudf::make_max_aggregation<scan_aggregation>(), cudf::scan_type::EXCLUSIVE), cudf::logic_error); EXPECT_THROW( cudf::scan(col, *cudf::make_min_aggregation<scan_aggregation>(), cudf::scan_type::EXCLUSIVE), cudf::logic_error); } template <typename T> struct ScanDurationTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(ScanDurationTest, cudf::test::DurationTypes); TYPED_TEST(ScanDurationTest, Sum) { cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> col({5, 4, 6, 0, 1, 6, 5, 3}, {1, 1, 1, 0, 1, 1, 1, 1}); cudf::test::fixed_width_column_wrapper<TypeParam, int32_t> expected({5, 9, 15, 0, 16, 22, 27, 30}, {1, 1, 1, 0, 1, 1, 1, 1}); auto result = cudf::scan(col, *cudf::make_sum_aggregation<scan_aggregation>(), cudf::scan_type::INCLUSIVE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result->view(), expected); result = cudf::scan(col, *cudf::make_sum_aggregation<scan_aggregation>(), cudf::scan_type::INCLUSIVE, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(result->view(), expected); EXPECT_THROW( cudf::scan(col, *cudf::make_sum_aggregation<scan_aggregation>(), cudf::scan_type::EXCLUSIVE), cudf::logic_error); } struct StructScanTest : public cudf::test::BaseFixture {}; TEST_F(StructScanTest, StructScanMinMaxNoNull) { using INTS_CW = cudf::test::fixed_width_column_wrapper<int32_t>; using STRINGS_CW = cudf::test::strings_column_wrapper; using STRUCTS_CW = cudf::test::structs_column_wrapper; auto const input = [] { auto child1 = STRINGS_CW{"año", "bit", "₹1", "aaa", "zit", "bat", "aab", "$1", "€1", "wut"}; auto child2 = INTS_CW{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; return STRUCTS_CW{{child1, child2}}; }(); { auto const expected = [] { auto child1 = STRINGS_CW{"año", "año", "año", "aaa", "aaa", "aaa", "aaa", "$1", "$1", "$1"}; auto child2 = INTS_CW{1, 1, 1, 4, 4, 4, 4, 8, 8, 8}; return STRUCTS_CW{{child1, child2}}; }(); auto const result = cudf::scan( input, *cudf::make_min_aggregation<scan_aggregation>(), cudf::scan_type::INCLUSIVE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } { auto const expected = [] { auto child1 = STRINGS_CW{"año", "bit", "₹1", "₹1", "₹1", "₹1", "₹1", "₹1", "₹1", "₹1"}; auto child2 = INTS_CW{1, 2, 3, 3, 3, 3, 3, 3, 3, 3}; return STRUCTS_CW{{child1, child2}}; }(); auto const result = cudf::scan( input, *cudf::make_max_aggregation<scan_aggregation>(), cudf::scan_type::INCLUSIVE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } } TEST_F(StructScanTest, StructScanMinMaxSlicedInput) { using INTS_CW = cudf::test::fixed_width_column_wrapper<int>; using STRINGS_CW = cudf::test::strings_column_wrapper; using STRUCTS_CW = cudf::test::structs_column_wrapper; constexpr int32_t dont_care{1}; auto const input_original = [] { auto child1 = STRINGS_CW{"$dont_care", "$dont_care", "año", "bit", "₹1", "aaa", "zit", "bat", "aab", "$1", "€1", "wut", "₹dont_care"}; auto child2 = INTS_CW{dont_care, dont_care, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, dont_care}; return STRUCTS_CW{{child1, child2}}; }(); auto const input = cudf::slice(input_original, {2, 12})[0]; { auto const expected = [] { auto child1 = STRINGS_CW{"año", "año", "año", "aaa", "aaa", "aaa", "aaa", "$1", "$1", "$1"}; auto child2 = INTS_CW{1, 1, 1, 4, 4, 4, 4, 8, 8, 8}; return STRUCTS_CW{{child1, child2}}; }(); auto const result = cudf::scan( input, *cudf::make_min_aggregation<scan_aggregation>(), cudf::scan_type::INCLUSIVE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } { auto const expected = [] { auto child1 = STRINGS_CW{"año", "bit", "₹1", "₹1", "₹1", "₹1", "₹1", "₹1", "₹1", "₹1"}; auto child2 = INTS_CW{1, 2, 3, 3, 3, 3, 3, 3, 3, 3}; return STRUCTS_CW{{child1, child2}}; }(); auto const result = cudf::scan( input, *cudf::make_max_aggregation<scan_aggregation>(), cudf::scan_type::INCLUSIVE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } } TEST_F(StructScanTest, StructScanMinMaxWithNulls) { using INTS_CW = cudf::test::fixed_width_column_wrapper<int>; using STRINGS_CW = cudf::test::strings_column_wrapper; using STRUCTS_CW = cudf::test::structs_column_wrapper; using cudf::test::iterators::null_at; using cudf::test::iterators::nulls_at; // `null` means null at child column. // `NULL` means null at parent column. auto const input = [] { auto child1 = STRINGS_CW{{"año", "bit", "₹1" /*null*/, "aaa" /*NULL*/, "zit", "bat", "aab", "$1" /*null*/, "€1" /*NULL*/, "wut"}, nulls_at({2, 7})}; auto child2 = INTS_CW{{1, 2, 3 /*null*/, 4 /*NULL*/, 5, 6, 7, 8 /*null*/, 9 /*NULL*/, 10}, nulls_at({2, 7})}; return STRUCTS_CW{{child1, child2}, nulls_at({3, 8})}; }(); { auto const expected = [] { auto child1 = STRINGS_CW{{"año", "año", "" /*null*/, "" /*null*/, "" /*null*/, "" /*null*/, "" /*null*/, "" /*null*/, "" /*null*/, "" /*null*/}, nulls_at({2, 3, 4, 5, 6, 7, 8, 9})}; auto child2 = INTS_CW{{1, 1, 0 /*null*/, 0 /*null*/, 0 /*null*/, 0 /*null*/, 0 /*null*/, 0 /*null*/, 0 /*null*/, 0 /*null*/}, nulls_at({2, 3, 4, 5, 6, 7, 8, 9})}; return STRUCTS_CW{{child1, child2}, nulls_at({3, 8})}; }(); auto const result = cudf::scan(input, *cudf::make_min_aggregation<scan_aggregation>(), cudf::scan_type::INCLUSIVE, null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } { auto const expected = [] { auto child1 = STRINGS_CW{ "año", "bit", "bit", "" /*NULL*/, "zit", "zit", "zit", "zit", "" /*NULL*/, "zit"}; auto child2 = INTS_CW{1, 2, 2, 0 /*NULL*/, 5, 5, 5, 5, 0 /*NULL*/, 5}; return STRUCTS_CW{{child1, child2}, nulls_at({3, 8})}; }(); auto const result = cudf::scan(input, *cudf::make_max_aggregation<scan_aggregation>(), cudf::scan_type::INCLUSIVE, null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } { auto const expected = [] { auto child1 = STRINGS_CW{{"año", "año", "" /*null*/, "" /*NULL*/, "" /*NULL*/, "" /*NULL*/, "" /*NULL*/, "" /*NULL*/, "" /*NULL*/, "" /*NULL*/}, null_at(2)}; auto child2 = INTS_CW{{1, 1, 0 /*null*/, 0 /*NULL*/, 0 /*NULL*/, 0 /*NULL*/, 0 /*NULL*/, 0 /*NULL*/, 0 /*NULL*/, 0 /*NULL*/}, null_at(2)}; return STRUCTS_CW{{child1, child2}, nulls_at({3, 4, 5, 6, 7, 8, 9})}; }(); auto const result = cudf::scan(input, *cudf::make_min_aggregation<scan_aggregation>(), cudf::scan_type::INCLUSIVE, null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } { auto const expected = [] { auto child1 = STRINGS_CW{"año", "bit", "bit", "" /*NULL*/, "" /*NULL*/, "" /*NULL*/, "" /*NULL*/, "" /*NULL*/, "" /*NULL*/, "" /*NULL*/}; auto child2 = INTS_CW{1, 2, 2, 0 /*NULL*/, 0 /*NULL*/, 0 /*NULL*/, 0 /*NULL*/, 0 /*NULL*/, 0 /*NULL*/, 0 /*NULL*/}; return STRUCTS_CW{{child1, child2}, nulls_at({3, 4, 5, 6, 7, 8, 9})}; }(); auto const result = cudf::scan(input, *cudf::make_max_aggregation<scan_aggregation>(), cudf::scan_type::INCLUSIVE, null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/reductions/list_rank_test.cpp
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <benchmarks/common/generate_input.hpp> #include <cudf/detail/aggregation/aggregation.hpp> #include <cudf/filling.hpp> #include <cudf/reduction.hpp> struct ListRankScanTest : public cudf::test::BaseFixture { inline void test_ungrouped_rank_scan(cudf::column_view const& input, cudf::column_view const& expect_vals, cudf::scan_aggregation const& agg, cudf::null_policy null_handling) { auto col_out = cudf::scan(input, agg, cudf::scan_type::INCLUSIVE, null_handling); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT( expect_vals, col_out->view(), cudf::test::debug_output_level::ALL_ERRORS); } }; TEST_F(ListRankScanTest, BasicList) { using lcw = cudf::test::lists_column_wrapper<uint64_t>; auto const col = lcw{{}, {}, {1}, {1, 1}, {1}, {1, 2}, {2, 2}, {2}, {2}, {2, 1}, {2, 2}, {2, 2}}; auto const expected_dense_vals = cudf::test::fixed_width_column_wrapper<cudf::size_type>{1, 1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 9}; this->test_ungrouped_rank_scan( col, expected_dense_vals, *cudf::make_rank_aggregation<cudf::scan_aggregation>(cudf::rank_method::DENSE), cudf::null_policy::INCLUDE); } TEST_F(ListRankScanTest, DeepList) { using lcw = cudf::test::lists_column_wrapper<uint64_t>; lcw col{ {{1, 2, 3}, {}, {4, 5}, {}, {0, 6, 0}}, {{1, 2, 3}, {}, {4, 5}, {}, {0, 6, 0}}, {{1, 2, 3}, {}, {4, 5}, {0, 6, 0}}, {{7, 8}, {}}, lcw{lcw{}, lcw{}, lcw{}}, lcw{lcw{}}, lcw{lcw{}}, lcw{lcw{}}, lcw{lcw{}, lcw{}, lcw{}}, lcw{lcw{}, lcw{}, lcw{}}, {lcw{10}}, {lcw{10}}, {{13, 14}, {15}}, {{13, 14}, {16}}, lcw{}, lcw{lcw{}}, }; { // Non-sliced auto const expected_dense_vals = cudf::test::fixed_width_column_wrapper<cudf::size_type>{ 1, 1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 7, 8, 9, 10, 11}; this->test_ungrouped_rank_scan( col, expected_dense_vals, *cudf::make_rank_aggregation<cudf::scan_aggregation>(cudf::rank_method::DENSE), cudf::null_policy::INCLUDE); } { // sliced auto sliced_col = cudf::slice(col, {3, 12})[0]; auto const expected_dense_vals = cudf::test::fixed_width_column_wrapper<cudf::size_type>{1, 2, 3, 3, 3, 4, 4, 5, 5}; this->test_ungrouped_rank_scan( sliced_col, expected_dense_vals, *cudf::make_rank_aggregation<cudf::scan_aggregation>(cudf::rank_method::DENSE), cudf::null_policy::INCLUDE); } } TEST_F(ListRankScanTest, ListOfStruct) { // Constructing a list of struct of two elements // 0. [] == // 1. [] != // 2. Null == // 3. Null != // 4. [Null, Null] != // 5. [Null] == // 6. [Null] == // 7. [Null] != // 8. [{Null, Null}] != // 9. [{1,'a'}, {2,'b'}] != // 10. [{0,'a'}, {2,'b'}] != // 11. [{0,'a'}, {2,'c'}] == // 12. [{0,'a'}, {2,'c'}] != // 13. [{0,Null}] == // 14. [{0,Null}] != // 15. [{Null, 0}] == // 16. [{Null, 0}] auto col1 = cudf::test::fixed_width_column_wrapper<int32_t>{ {-1, -1, 0, 2, 2, 2, 1, 2, 0, 2, 0, 2, 0, 2, 0, 0, 1, 2}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0}}; auto col2 = cudf::test::strings_column_wrapper{ {"x", "x", "a", "a", "b", "b", "a", "b", "a", "b", "a", "c", "a", "c", "a", "c", "b", "b"}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1}}; auto struct_col = cudf::test::structs_column_wrapper{ {col1, col2}, {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}; auto offsets = cudf::test::fixed_width_column_wrapper<cudf::size_type>{ 0, 0, 0, 0, 0, 2, 3, 4, 5, 6, 8, 10, 12, 14, 15, 16, 17, 18}; auto list_nullmask = std::vector<bool>{1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; auto [null_mask, null_count] = cudf::test::detail::make_null_mask(list_nullmask.begin(), list_nullmask.end()); auto list_column = cudf::column_view(cudf::data_type(cudf::type_id::LIST), 17, nullptr, static_cast<cudf::bitmask_type*>(null_mask.data()), null_count, 0, {offsets, struct_col}); { // Non-sliced auto expect = cudf::test::fixed_width_column_wrapper<cudf::size_type>{ 1, 1, 2, 2, 3, 4, 4, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10}; this->test_ungrouped_rank_scan( list_column, expect, *cudf::make_rank_aggregation<cudf::scan_aggregation>(cudf::rank_method::DENSE), cudf::null_policy::INCLUDE); } { // Sliced auto sliced_col = cudf::slice(list_column, {3, 15})[0]; auto expect = cudf::test::fixed_width_column_wrapper<cudf::size_type>{1, 2, 3, 3, 3, 4, 5, 6, 7, 7, 8, 8}; this->test_ungrouped_rank_scan( sliced_col, expect, *cudf::make_rank_aggregation<cudf::scan_aggregation>(cudf::rank_method::DENSE), cudf::null_policy::INCLUDE); } } TEST_F(ListRankScanTest, ListOfEmptyStruct) { // [] // [] // Null // Null // [Null, Null] // [Null, Null] // [Null, Null] // [Null] // [Null] // [{}] // [{}] // [{}, {}] // [{}, {}] auto struct_validity = std::vector<bool>{0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1}; auto [null_mask, null_count] = cudf::test::detail::make_null_mask(struct_validity.begin(), struct_validity.end()); auto struct_col = cudf::make_structs_column(14, {}, null_count, std::move(null_mask)); auto offsets = cudf::test::fixed_width_column_wrapper<cudf::size_type>{ 0, 0, 0, 0, 0, 2, 4, 6, 7, 8, 9, 10, 12, 14}; auto list_nullmask = std::vector<bool>{1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1}; std::tie(null_mask, null_count) = cudf::test::detail::make_null_mask(list_nullmask.begin(), list_nullmask.end()); auto list_column = cudf::make_lists_column( 13, offsets.release(), std::move(struct_col), null_count, std::move(null_mask)); auto expect = cudf::test::fixed_width_column_wrapper<cudf::size_type>{1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6}; this->test_ungrouped_rank_scan( *list_column, expect, *cudf::make_rank_aggregation<cudf::scan_aggregation>(cudf::rank_method::DENSE), cudf::null_policy::INCLUDE); } TEST_F(ListRankScanTest, EmptyDeepList) { // List<List<int>>, where all lists are empty // [] // [] // Null // Null // Internal empty list auto list1 = cudf::test::lists_column_wrapper<int>{}; auto offsets = cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 0, 0, 0, 0}; auto list_nullmask = std::vector<bool>{1, 1, 0, 0}; auto [null_mask, null_count] = cudf::test::detail::make_null_mask(list_nullmask.begin(), list_nullmask.end()); auto list_column = cudf::make_lists_column( 4, offsets.release(), list1.release(), null_count, std::move(null_mask)); auto expect = cudf::test::fixed_width_column_wrapper<cudf::size_type>{1, 1, 2, 2}; this->test_ungrouped_rank_scan( *list_column, expect, *cudf::make_rank_aggregation<cudf::scan_aggregation>(cudf::rank_method::DENSE), cudf::null_policy::INCLUDE); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/reductions/rank_tests.cpp
/* * Copyright (c) 2021-2023, NVIDIA CORPORATION. * * Licensed 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 "scan_tests.hpp" #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf/aggregation.hpp> #include <cudf/detail/aggregation/aggregation.hpp> #include <cudf/reduction.hpp> #include <cudf/types.hpp> #include <thrust/host_vector.h> using rank_result_col = cudf::test::fixed_width_column_wrapper<cudf::size_type>; using percent_result_col = cudf::test::fixed_width_column_wrapper<double>; auto const rank = cudf::make_rank_aggregation<cudf::scan_aggregation>(cudf::rank_method::MIN); auto const dense_rank = cudf::make_rank_aggregation<cudf::scan_aggregation>(cudf::rank_method::DENSE); auto const percent_rank = cudf::make_rank_aggregation<cudf::scan_aggregation>(cudf::rank_method::MIN, {}, cudf::null_policy::INCLUDE, {}, cudf::rank_percentage::ONE_NORMALIZED); auto constexpr INCLUSIVE_SCAN = cudf::scan_type::INCLUSIVE; auto constexpr INCLUDE_NULLS = cudf::null_policy::INCLUDE; template <typename T> struct TypedRankScanTest : BaseScanTest<T> { inline void test_ungrouped_rank_scan(cudf::column_view const& input, cudf::column_view const& expect_vals, cudf::scan_aggregation const& agg) { auto col_out = cudf::scan(input, agg, INCLUSIVE_SCAN, INCLUDE_NULLS); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expect_vals, col_out->view()); } }; using RankTypes = cudf::test::Concat<cudf::test::IntegralTypesNotBool, cudf::test::FloatingPointTypes, cudf::test::FixedPointTypes, cudf::test::ChronoTypes, cudf::test::StringTypes>; TYPED_TEST_SUITE(TypedRankScanTest, RankTypes); TYPED_TEST(TypedRankScanTest, Rank) { auto const v = [] { if (std::is_signed_v<TypeParam>) return make_vector<TypeParam>({-120, -120, -120, -16, -16, 5, 6, 6, 6, 6, 34, 113}); return make_vector<TypeParam>({5, 5, 5, 6, 6, 9, 11, 11, 11, 11, 14, 34}); }(); auto const col = this->make_column(v); auto const expected_dense = rank_result_col{1, 1, 1, 2, 2, 3, 4, 4, 4, 4, 5, 6}; auto const expected_rank = rank_result_col{1, 1, 1, 4, 4, 6, 7, 7, 7, 7, 11, 12}; auto const expected_percent = percent_result_col{0.0, 0.0, 0.0, 3.0 / 11, 3.0 / 11, 5.0 / 11, 6.0 / 11, 6.0 / 11, 6.0 / 11, 6.0 / 11, 10.0 / 11, 11.0 / 11}; this->test_ungrouped_rank_scan(*col, expected_dense, *dense_rank); this->test_ungrouped_rank_scan(*col, expected_rank, *rank); this->test_ungrouped_rank_scan(*col, expected_percent, *percent_rank); } TYPED_TEST(TypedRankScanTest, RankWithNulls) { auto const v = [] { if (std::is_signed_v<TypeParam>) return make_vector<TypeParam>({-120, -120, -120, -16, -16, 5, 6, 6, 6, 6, 34, 113}); return make_vector<TypeParam>({5, 5, 5, 6, 6, 9, 11, 11, 11, 11, 14, 34}); }(); auto const null_iter = cudf::test::iterators::nulls_at({3, 6, 7, 11}); auto const b = thrust::host_vector<bool>(null_iter, null_iter + v.size()); auto col = this->make_column(v, b); auto const expected_dense = rank_result_col{1, 1, 1, 2, 3, 4, 5, 5, 6, 6, 7, 8}; auto const expected_rank = rank_result_col{1, 1, 1, 4, 5, 6, 7, 7, 9, 9, 11, 12}; auto const expected_percent = percent_result_col{0.0, 0.0, 0.0, 3.0 / 11, 4.0 / 11, 5.0 / 11, 6.0 / 11, 6.0 / 11, 8.0 / 11, 8.0 / 11, 10.0 / 11, 11.0 / 11}; this->test_ungrouped_rank_scan(*col, expected_dense, *dense_rank); this->test_ungrouped_rank_scan(*col, expected_rank, *rank); this->test_ungrouped_rank_scan(*col, expected_percent, *percent_rank); } namespace { template <typename TypeParam> auto make_input_column() { if constexpr (std::is_same_v<TypeParam, cudf::string_view>) { return cudf::test::strings_column_wrapper{ {"0", "0", "4", "4", "4", "5", "7", "7", "7", "9", "9", "9"}, cudf::test::iterators::null_at(5)}; } else { using fw_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam>; return (std::is_signed_v<TypeParam>) ? fw_wrapper{{-1, -1, -4, -4, -4, 5, 7, 7, 7, 9, 9, 9}, cudf::test::iterators::null_at(5)} : fw_wrapper{{0, 0, 4, 4, 4, 5, 7, 7, 7, 9, 9, 9}, cudf::test::iterators::null_at(5)}; } } auto make_strings_column() { return cudf::test::strings_column_wrapper{ {"0a", "0a", "2a", "2a", "3b", "5", "6c", "6c", "", "9", "9", "10d"}, cudf::test::iterators::null_at(8)}; } template <typename TypeParam> auto make_mixed_structs_column() { auto col = make_input_column<TypeParam>(); auto strings = make_strings_column(); return cudf::test::structs_column_wrapper{{col, strings}}; } } // namespace TYPED_TEST(TypedRankScanTest, MixedStructs) { auto const struct_col = make_mixed_structs_column<TypeParam>(); auto const expected_dense = rank_result_col{1, 1, 2, 2, 3, 4, 5, 5, 6, 7, 7, 8}; auto const expected_rank = rank_result_col{1, 1, 3, 3, 5, 6, 7, 7, 9, 10, 10, 12}; auto const expected_percent = percent_result_col{0.0, 0.0, 2.0 / 11, 2.0 / 11, 4.0 / 11, 5.0 / 11, 6.0 / 11, 6.0 / 11, 8.0 / 11, 9.0 / 11, 9.0 / 11, 11.0 / 11}; this->test_ungrouped_rank_scan(struct_col, expected_dense, *dense_rank); this->test_ungrouped_rank_scan(struct_col, expected_rank, *rank); this->test_ungrouped_rank_scan(struct_col, expected_percent, *percent_rank); } TYPED_TEST(TypedRankScanTest, NestedStructs) { auto const nested_col = [&] { auto struct_col = [&] { auto col = make_input_column<TypeParam>(); auto strings = make_strings_column(); return cudf::test::structs_column_wrapper{{col, strings}}; }(); auto col = make_input_column<TypeParam>(); return cudf::test::structs_column_wrapper{{struct_col, col}}; }(); auto const flat_col = [&] { auto col = make_input_column<TypeParam>(); auto strings_col = make_strings_column(); auto nuther_col = make_input_column<TypeParam>(); return cudf::test::structs_column_wrapper{{col, strings_col, nuther_col}}; }(); auto const dense_out = cudf::scan(nested_col, *dense_rank, INCLUSIVE_SCAN, INCLUDE_NULLS); auto const dense_expected = cudf::scan(flat_col, *dense_rank, INCLUSIVE_SCAN, INCLUDE_NULLS); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(dense_out->view(), dense_expected->view()); auto const rank_out = cudf::scan(nested_col, *rank, INCLUSIVE_SCAN, INCLUDE_NULLS); auto const rank_expected = cudf::scan(flat_col, *rank, INCLUSIVE_SCAN, INCLUDE_NULLS); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(rank_out->view(), rank_expected->view()); auto const percent_out = cudf::scan(nested_col, *percent_rank, INCLUSIVE_SCAN, INCLUDE_NULLS); auto const percent_expected = cudf::scan(flat_col, *percent_rank, INCLUSIVE_SCAN, INCLUDE_NULLS); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(percent_out->view(), percent_expected->view()); } TYPED_TEST(TypedRankScanTest, StructsWithNullPushdown) { auto struct_col = make_mixed_structs_column<TypeParam>().release(); // First, verify that if the structs column has only nulls, all output rows are ranked 1. { // Null mask not pushed down to members. struct_col->set_null_mask(create_null_mask(struct_col->size(), cudf::mask_state::ALL_NULL), struct_col->size()); auto const expected_null_result = rank_result_col{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; auto const expected_percent_rank_null_result = percent_result_col{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; auto const dense_out = cudf::scan(*struct_col, *dense_rank, INCLUSIVE_SCAN, INCLUDE_NULLS); auto const rank_out = cudf::scan(*struct_col, *rank, INCLUSIVE_SCAN, INCLUDE_NULLS); auto const percent_out = cudf::scan(*struct_col, *percent_rank, INCLUSIVE_SCAN, INCLUDE_NULLS); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(dense_out->view(), expected_null_result); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(rank_out->view(), expected_null_result); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(percent_out->view(), expected_percent_rank_null_result); } // Next, verify that if the structs column a null mask that is NOT pushed down to members, // the ranks are still correct. { auto const null_iter = cudf::test::iterators::nulls_at({1, 2}); auto [null_mask, null_count] = cudf::test::detail::make_null_mask(null_iter, null_iter + struct_col->size()); struct_col->set_null_mask(std::move(null_mask), null_count); auto const expected_dense = rank_result_col{1, 2, 2, 3, 4, 5, 6, 6, 7, 8, 8, 9}; auto const expected_rank = rank_result_col{1, 2, 2, 4, 5, 6, 7, 7, 9, 10, 10, 12}; auto const expected_percent = percent_result_col{0.0, 1.0 / 11, 1.0 / 11, 3.0 / 11, 4.0 / 11, 5.0 / 11, 6.0 / 11, 6.0 / 11, 8.0 / 11, 9.0 / 11, 9.0 / 11, 11.0 / 11}; auto const dense_out = cudf::scan(*struct_col, *dense_rank, INCLUSIVE_SCAN, INCLUDE_NULLS); auto const rank_out = cudf::scan(*struct_col, *rank, INCLUSIVE_SCAN, INCLUDE_NULLS); auto const percent_out = cudf::scan(*struct_col, *percent_rank, INCLUSIVE_SCAN, INCLUDE_NULLS); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(dense_out->view(), expected_dense); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(rank_out->view(), expected_rank); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(percent_out->view(), expected_percent); } } struct RankScanTest : public cudf::test::BaseFixture {}; TEST(RankScanTest, BoolRank) { auto const vals = cudf::test::fixed_width_column_wrapper<bool>{0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1}; auto const expected_dense = rank_result_col{1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2}; auto const expected_rank = rank_result_col{1, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4}; auto const expected_percent = percent_result_col{0.0, 0.0, 0.0, 3.0 / 11, 3.0 / 11, 3.0 / 11, 3.0 / 11, 3.0 / 11, 3.0 / 11, 3.0 / 11, 3.0 / 11, 3.0 / 11}; auto const dense_out = cudf::scan(vals, *dense_rank, INCLUSIVE_SCAN, INCLUDE_NULLS); auto const rank_out = cudf::scan(vals, *rank, INCLUSIVE_SCAN, INCLUDE_NULLS); auto const percent_out = cudf::scan(vals, *percent_rank, INCLUSIVE_SCAN, INCLUDE_NULLS); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_dense, dense_out->view()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_rank, rank_out->view()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_percent, percent_out->view()); } TEST(RankScanTest, BoolRankWithNull) { auto const vals = cudf::test::fixed_width_column_wrapper<bool>{ {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1}, cudf::test::iterators::nulls_at({8, 9, 10, 11})}; auto const expected_dense = rank_result_col{1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3}; auto const expected_rank = rank_result_col{1, 1, 1, 4, 4, 4, 4, 4, 9, 9, 9, 9}; auto const expected_percent = percent_result_col{0.0, 0.0, 0.0, 3.0 / 11, 3.0 / 11, 3.0 / 11, 3.0 / 11, 3.0 / 11, 8.0 / 11, 8.0 / 11, 8.0 / 11, 8.0 / 11}; auto nullable_dense_out = cudf::scan(vals, *dense_rank, INCLUSIVE_SCAN, INCLUDE_NULLS); auto nullable_rank_out = cudf::scan(vals, *rank, INCLUSIVE_SCAN, INCLUDE_NULLS); auto nullable_percent_out = cudf::scan(vals, *percent_rank, INCLUSIVE_SCAN, INCLUDE_NULLS); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_dense, nullable_dense_out->view()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_rank, nullable_rank_out->view()); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_percent, nullable_percent_out->view()); } TEST(RankScanTest, ExclusiveScan) { auto const vals = cudf::test::fixed_width_column_wrapper<uint32_t>{3, 4, 5}; // Only inclusive scans are supported, so these should all raise exceptions. EXPECT_THROW(cudf::scan(vals, *dense_rank, cudf::scan_type::EXCLUSIVE, INCLUDE_NULLS), cudf::logic_error); EXPECT_THROW(cudf::scan(vals, *rank, cudf::scan_type::EXCLUSIVE, INCLUDE_NULLS), cudf::logic_error); EXPECT_THROW(cudf::scan(vals, *percent_rank, cudf::scan_type::EXCLUSIVE, INCLUDE_NULLS), cudf::logic_error); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/reductions/scan_tests.hpp
/* * Copyright (c) 2021-2022, NVIDIA CORPORATION. * * Licensed 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. */ #pragma once #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/column/column.hpp> #include <cudf/fixed_point/fixed_point.hpp> #include <cudf/strings/string_view.hpp> #include <cudf/utilities/span.hpp> #include <cudf/utilities/traits.hpp> #include <thrust/host_vector.h> #include <initializer_list> #include <type_traits> #include <vector> template <typename T> struct TypeParam_to_host_type { using type = T; }; template <> struct TypeParam_to_host_type<cudf::string_view> { using type = std::string; }; template <> struct TypeParam_to_host_type<numeric::decimal32> { using type = numeric::decimal32::rep; }; template <> struct TypeParam_to_host_type<numeric::decimal64> { using type = numeric::decimal64::rep; }; template <> struct TypeParam_to_host_type<numeric::decimal128> { using type = numeric::decimal128::rep; }; template <typename TypeParam, typename T> std::enable_if_t<std::is_same_v<TypeParam, cudf::string_view>, thrust::host_vector<std::string>> make_vector(std::initializer_list<T> const& init) { return cudf::test::make_type_param_vector<std::string, T>(init); } template <typename TypeParam, typename T> std::enable_if_t<cudf::is_fixed_point<TypeParam>(), thrust::host_vector<typename TypeParam::rep>> make_vector(std::initializer_list<T> const& init) { return cudf::test::make_type_param_vector<typename TypeParam::rep, T>(init); } template <typename TypeParam, typename T> std::enable_if_t<not(std::is_same_v<TypeParam, cudf::string_view> || cudf::is_fixed_point<TypeParam>()), thrust::host_vector<TypeParam>> make_vector(std::initializer_list<T> const& init) { return cudf::test::make_type_param_vector<TypeParam, T>(init); } // This is the base test feature template <typename T> struct BaseScanTest : public cudf::test::BaseFixture { using HostType = typename TypeParam_to_host_type<T>::type; std::unique_ptr<cudf::column> make_column(cudf::host_span<HostType const> v, cudf::host_span<bool const> b = {}, numeric::scale_type scale = numeric::scale_type{0}) { if constexpr (std::is_same_v<T, cudf::string_view>) { auto col = (b.size() > 0) ? cudf::test::strings_column_wrapper(v.begin(), v.end(), b.begin()) : cudf::test::strings_column_wrapper(v.begin(), v.end()); return col.release(); } else if constexpr (cudf::is_fixed_point<T>()) { auto col = (b.size() > 0) ? cudf::test::fixed_point_column_wrapper<typename T::rep>( v.begin(), v.end(), b.begin(), scale) : cudf::test::fixed_point_column_wrapper<typename T::rep>( v.begin(), v.end(), scale); return col.release(); } else { auto col = (b.size() > 0) ? cudf::test::fixed_width_column_wrapper<T>(v.begin(), v.end(), b.begin()) : cudf::test::fixed_width_column_wrapper<T>(v.begin(), v.end()); return col.release(); } } };
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/reductions/segmented_reduction_tests.cpp
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/aggregation.hpp> #include <cudf/detail/utilities/vector_factories.hpp> #include <cudf/reduction.hpp> #include <cudf/scalar/scalar_factories.hpp> #include <cudf/types.hpp> #include <limits> #include <utility> #include <vector> #define XXX 0 // null placeholder template <typename T> struct SegmentedReductionTest : public cudf::test::BaseFixture {}; struct SegmentedReductionTestUntyped : public cudf::test::BaseFixture {}; TYPED_TEST_CASE(SegmentedReductionTest, cudf::test::NumericTypes); TYPED_TEST(SegmentedReductionTest, SumExcludeNulls) { // [1, 2, 3], [1, null, 3], [1], [null], [null, null], [] // values: {1, 2, 3, 1, XXX, 3, 1, XXX, XXX, XXX} // offsets: {0, 3, 6, 7, 8, 10, 10} // nullmask: {1, 1, 1, 1, 0, 1, 1, 0, 0, 0} // outputs: {6, 4, 1, XXX, XXX, XXX} // output nullmask: {1, 1, 1, 0, 0, 0} auto const input = cudf::test::fixed_width_column_wrapper<TypeParam>{ {1, 2, 3, 1, XXX, 3, 1, XXX, XXX, XXX}, {1, 1, 1, 1, 0, 1, 1, 0, 0, 0}}; auto const offsets = std::vector<cudf::size_type>{0, 3, 6, 7, 8, 10, 10}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const expect = cudf::test::fixed_width_column_wrapper<TypeParam>{{6, 4, 1, XXX, XXX, XXX}, {1, 1, 1, 0, 0, 0}}; auto res = cudf::segmented_reduce(input, d_offsets, *cudf::make_sum_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); // Test with initial value auto const init_scalar = cudf::make_fixed_width_scalar<TypeParam>(3); auto const init_expect = cudf::test::fixed_width_column_wrapper<TypeParam>{{9, 7, 4, 3, 3, 3}, {1, 1, 1, 1, 1, 1}}; res = cudf::segmented_reduce(input, d_offsets, *cudf::make_sum_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::EXCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, init_expect); // Test with null initial value init_scalar->set_valid_async(false); res = cudf::segmented_reduce(input, d_offsets, *cudf::make_sum_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::EXCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); } TYPED_TEST(SegmentedReductionTest, ProductExcludeNulls) { // [1, 3, 5], [null, 3, 5], [1], [null], [null, null], [] // values: {1, 3, 5, XXX, 3, 5, 1, XXX, XXX, XXX} // offsets: {0, 3, 6, 7, 8, 10, 10} // nullmask: {1, 1, 1, 0, 1, 1, 1, 0, 0, 0} // outputs: {15, 15, 1, XXX, XXX, XXX} // output nullmask: {1, 1, 1, 0, 0, 0} auto const input = cudf::test::fixed_width_column_wrapper<TypeParam>{ {1, 3, 5, XXX, 3, 5, 1, XXX, XXX, XXX}, {1, 1, 1, 0, 1, 1, 1, 0, 0, 0}}; auto const offsets = std::vector<cudf::size_type>{0, 3, 6, 7, 8, 10, 10}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const expect = cudf::test::fixed_width_column_wrapper<TypeParam>{{15, 15, 1, XXX, XXX, XXX}, {1, 1, 1, 0, 0, 0}}; auto res = cudf::segmented_reduce(input, d_offsets, *cudf::make_product_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); // Test with initial value auto const init_scalar = cudf::make_fixed_width_scalar<TypeParam>(3); auto const init_expect = cudf::test::fixed_width_column_wrapper<TypeParam>{{45, 45, 3, 3, 3, 3}, {1, 1, 1, 1, 1, 1}}; res = cudf::segmented_reduce(input, d_offsets, *cudf::make_product_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::EXCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, init_expect); // Test with null initial value init_scalar->set_valid_async(false); res = cudf::segmented_reduce(input, d_offsets, *cudf::make_product_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::EXCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); } TYPED_TEST(SegmentedReductionTest, MaxExcludeNulls) { // [1, 2, 3], [1, null, 3], [1], [null], [null, null], [] // values: {1, 2, 3, 1, XXX, 3, 1, XXX, XXX, XXX} // offsets: {0, 3, 6, 7, 8, 10, 10} // nullmask: {1, 1, 1, 1, 0, 1, 1, 0, 0, 0} // outputs: {3, 3, 1, XXX, XXX, XXX} // output nullmask: {1, 1, 1, 0, 0, 0} auto const input = cudf::test::fixed_width_column_wrapper<TypeParam>{ {1, 2, 3, 1, XXX, 3, 1, XXX, XXX, XXX}, {1, 1, 1, 1, 0, 1, 1, 0, 0, 0}}; auto const offsets = std::vector<cudf::size_type>{0, 3, 6, 7, 8, 10, 10}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const expect = cudf::test::fixed_width_column_wrapper<TypeParam>{{3, 3, 1, XXX, XXX, XXX}, {1, 1, 1, 0, 0, 0}}; auto res = cudf::segmented_reduce(input, d_offsets, *cudf::make_max_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); // Test with initial value auto const init_scalar = cudf::make_fixed_width_scalar<TypeParam>(2); auto const init_expect = cudf::test::fixed_width_column_wrapper<TypeParam>{{3, 3, 2, 2, 2, 2}, {1, 1, 1, 1, 1, 1}}; res = cudf::segmented_reduce(input, d_offsets, *cudf::make_max_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::EXCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, init_expect); // Test with null initial value init_scalar->set_valid_async(false); res = cudf::segmented_reduce(input, d_offsets, *cudf::make_max_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::EXCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); } TYPED_TEST(SegmentedReductionTest, MinExcludeNulls) { // [1, 2, 3], [1, null, 3], [1], [null], [null, null], [] // values: {1, 2, 3, 1, XXX, 3, 1, XXX, XXX, XXX} // offsets: {0, 3, 6, 7, 8, 10, 10} // nullmask: {1, 1, 1, 1, 0, 1, 1, 0, 0, 0} // outputs: {1, 1, 1, XXX, XXX, XXX} // output nullmask: {1, 1, 1, 0, 0, 0} auto const input = cudf::test::fixed_width_column_wrapper<TypeParam>{ {1, 2, 3, 1, XXX, 3, 1, XXX, XXX, XXX}, {1, 1, 1, 1, 0, 1, 1, 0, 0, 0}}; auto const offsets = std::vector<cudf::size_type>{0, 3, 6, 7, 8, 10, 10}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const expect = cudf::test::fixed_width_column_wrapper<TypeParam>{{1, 1, 1, XXX, XXX, XXX}, {1, 1, 1, 0, 0, 0}}; auto res = cudf::segmented_reduce(input, d_offsets, *cudf::make_min_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); // Test with initial value auto const init_scalar = cudf::make_fixed_width_scalar<TypeParam>(2); auto const init_expect = cudf::test::fixed_width_column_wrapper<TypeParam>{{1, 1, 1, 2, 2, 2}, {1, 1, 1, 1, 1, 1}}; res = cudf::segmented_reduce(input, d_offsets, *cudf::make_min_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::EXCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, init_expect); // Test with null initial value init_scalar->set_valid_async(false); res = cudf::segmented_reduce(input, d_offsets, *cudf::make_min_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::EXCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); } TYPED_TEST(SegmentedReductionTest, AnyExcludeNulls) { // [0, 0, 0], [0, null, 0], [0, 1, 0], [1, null, 0], [], [0], [1], [null], [null, null] // values: {0, 0, 0, 0, XXX, 0, 0, 1, 0, 1, XXX, 0, 0, 1, XXX, XXX, XXX} // offsets: {0, 3, 6, 9, 12, 12, 13, 14, 15, 17} // nullmask:{1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0} // outputs: {0, 0, 1, 1, XXX, 0, 1, XXX, XXX} // output nullmask: {1, 1, 1, 1, 0, 1, 1, 0, 0} auto const input = cudf::test::fixed_width_column_wrapper<TypeParam>{ {0, 0, 0, 0, XXX, 0, 0, 1, 0, 1, XXX, 0, 0, 1, XXX, XXX, XXX}, {1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0}}; auto const offsets = std::vector<cudf::size_type>{0, 3, 6, 9, 12, 12, 13, 14, 15, 17}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const expect = cudf::test::fixed_width_column_wrapper<bool>{ {false, false, true, true, bool{XXX}, false, true, bool{XXX}, bool{XXX}}, {true, true, true, true, false, true, true, false, false}}; auto const agg = cudf::make_any_aggregation<cudf::segmented_reduce_aggregation>(); auto const output_type = cudf::data_type{cudf::type_id::BOOL8}; auto const policy = cudf::null_policy::EXCLUDE; auto res = cudf::segmented_reduce(input, d_offsets, *agg, output_type, policy); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); // Test with initial value auto const init_scalar = cudf::make_fixed_width_scalar<TypeParam>(0); auto const init_expect = cudf::test::fixed_width_column_wrapper<bool>{ {false, false, true, true, false, false, true, false, false}, {true, true, true, true, true, true, true, true, true}}; res = cudf::segmented_reduce(input, d_offsets, *agg, output_type, policy, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, init_expect); // Test with null initial value init_scalar->set_valid_async(false); res = cudf::segmented_reduce(input, d_offsets, *agg, output_type, policy, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); } TYPED_TEST(SegmentedReductionTest, AllExcludeNulls) { // [1, 2, 3], [1, null, 3], [], [1], [null], [null, null], [1, 0, 3], [1, null, 0], [0] // values: {1, 2, 3, 1, XXX, 3, 1, XXX, XXX, XXX, 1, 0, 3, 1, XXX, 0, 0} // offsets: {0, 3, 6, 6, 7, 8, 10, 13, 16, 17} // nullmask: {1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1} // outputs: {true, true, XXX, true, XXX, XXX, false, false, false} // output nullmask: {1, 1, 0, 1, 0, 0, 1, 1, 1} auto const input = cudf::test::fixed_width_column_wrapper<TypeParam>{ {1, 2, 3, 1, XXX, 3, 1, XXX, XXX, XXX, 1, 0, 3, 1, XXX, 0, 0}, {1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1}}; auto const offsets = std::vector<cudf::size_type>{0, 3, 6, 6, 7, 8, 10, 13, 16, 17}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const expect = cudf::test::fixed_width_column_wrapper<bool>{ {true, true, bool{XXX}, true, bool{XXX}, bool{XXX}, false, false, false}, {true, true, false, true, false, false, true, true, true}}; auto res = cudf::segmented_reduce(input, d_offsets, *cudf::make_all_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_id::BOOL8}, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); // Test with initial value auto const init_scalar = cudf::make_fixed_width_scalar<TypeParam>(1); auto const init_expect = cudf::test::fixed_width_column_wrapper<bool>{ {true, true, true, true, true, true, false, false, false}, {true, true, true, true, true, true, true, true, true}}; res = cudf::segmented_reduce(input, d_offsets, *cudf::make_all_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_id::BOOL8}, cudf::null_policy::EXCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, init_expect); // Test with null initial value init_scalar->set_valid_async(false); res = cudf::segmented_reduce(input, d_offsets, *cudf::make_all_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_id::BOOL8}, cudf::null_policy::EXCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); } TYPED_TEST(SegmentedReductionTest, SumIncludeNulls) { // [1, 2, 3], [1, null, 3], [1], [null], [null, null], [] // values: {1, 2, 3, 1, XXX, 3, 1, XXX, XXX, XXX} // offsets: {0, 3, 6, 7, 8, 10, 10} // nullmask: {1, 1, 1, 1, 0, 1, 1, 0, 0, 0} // outputs: {6, XXX, 1, XXX, XXX, XXX} // output nullmask: {1, 0, 1, 0, 0, 0} auto const input = cudf::test::fixed_width_column_wrapper<TypeParam>{ {1, 2, 3, 1, XXX, 3, 1, XXX, XXX, XXX}, {1, 1, 1, 1, 0, 1, 1, 0, 0, 0}}; auto const offsets = std::vector<cudf::size_type>{0, 3, 6, 7, 8, 10, 10}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const expect = cudf::test::fixed_width_column_wrapper<TypeParam>{{6, XXX, 1, XXX, XXX, XXX}, {1, 0, 1, 0, 0, 0}}; auto res = cudf::segmented_reduce(input, d_offsets, *cudf::make_sum_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); // Test with initial value auto const init_scalar = cudf::make_fixed_width_scalar<TypeParam>(3); auto const init_expect = cudf::test::fixed_width_column_wrapper<TypeParam>{{9, XXX, 4, XXX, XXX, 3}, {1, 0, 1, 0, 0, 1}}; res = cudf::segmented_reduce(input, d_offsets, *cudf::make_sum_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::INCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, init_expect); // Test with null initial value init_scalar->set_valid_async(false); auto null_init_expect = cudf::test::fixed_width_column_wrapper<TypeParam>{ {XXX, XXX, XXX, XXX, XXX, XXX}, {0, 0, 0, 0, 0, 0}}; res = cudf::segmented_reduce(input, d_offsets, *cudf::make_sum_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::INCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, null_init_expect); } TYPED_TEST(SegmentedReductionTest, ProductIncludeNulls) { // [1, 3, 5], [null, 3, 5], [1], [null], [null, null], [] // values: {1, 3, 5, XXX, 3, 5, 1, XXX, XXX, XXX} // offsets: {0, 3, 6, 7, 8, 10, 10} // nullmask: {1, 1, 1, 0, 1, 1, 1, 0, 0, 0} // outputs: {15, XXX, 1, XXX, XXX, XXX} // output nullmask: {1, 0, 1, 0, 0, 0} auto const input = cudf::test::fixed_width_column_wrapper<TypeParam>{ {1, 3, 5, XXX, 3, 5, 1, XXX, XXX, XXX}, {1, 1, 1, 0, 1, 1, 1, 0, 0, 0}}; auto const offsets = std::vector<cudf::size_type>{0, 3, 6, 7, 8, 10, 10}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const expect = cudf::test::fixed_width_column_wrapper<TypeParam>{{15, XXX, 1, XXX, XXX, XXX}, {1, 0, 1, 0, 0, 0}}; auto res = cudf::segmented_reduce(input, d_offsets, *cudf::make_product_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); // Test with initial value auto const init_scalar = cudf::make_fixed_width_scalar<TypeParam>(3); auto const init_expect = cudf::test::fixed_width_column_wrapper<TypeParam>{ {45, XXX, 3, XXX, XXX, 3}, {1, 0, 1, 0, 0, 1}}; res = cudf::segmented_reduce(input, d_offsets, *cudf::make_product_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::INCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, init_expect); // Test with null initial value init_scalar->set_valid_async(false); auto null_init_expect = cudf::test::fixed_width_column_wrapper<TypeParam>{ {XXX, XXX, XXX, XXX, XXX, XXX}, {0, 0, 0, 0, 0, 0}}; res = cudf::segmented_reduce(input, d_offsets, *cudf::make_product_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::INCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, null_init_expect); } TYPED_TEST(SegmentedReductionTest, MaxIncludeNulls) { // [1, 2, 3], [1, null, 3], [1], [null], [null, null], [] // values: {1, 2, 3, 1, XXX, 3, 1, XXX, XXX, XXX} // offsets: {0, 3, 6, 7, 8, 10, 10} // nullmask: {1, 1, 1, 1, 0, 1, 1, 0, 0, 0} // outputs: {3, XXX, 1, XXX, XXX, XXX} // output nullmask: {1, 0, 1, 0, 0, 0} auto const input = cudf::test::fixed_width_column_wrapper<TypeParam>{ {1, 2, 3, 1, XXX, 3, 1, XXX, XXX, XXX}, {1, 1, 1, 1, 0, 1, 1, 0, 0, 0}}; auto const offsets = std::vector<cudf::size_type>{0, 3, 6, 7, 8, 10, 10}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const expect = cudf::test::fixed_width_column_wrapper<TypeParam>{{3, XXX, 1, XXX, XXX, XXX}, {1, 0, 1, 0, 0, 0}}; auto res = cudf::segmented_reduce(input, d_offsets, *cudf::make_max_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); // Test with initial value auto const init_scalar = cudf::make_fixed_width_scalar<TypeParam>(2); auto const init_expect = cudf::test::fixed_width_column_wrapper<TypeParam>{{3, XXX, 2, XXX, XXX, 2}, {1, 0, 1, 0, 0, 1}}; res = cudf::segmented_reduce(input, d_offsets, *cudf::make_max_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::INCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, init_expect); // Test with null initial value init_scalar->set_valid_async(false); auto null_init_expect = cudf::test::fixed_width_column_wrapper<TypeParam>{ {XXX, XXX, XXX, XXX, XXX, XXX}, {0, 0, 0, 0, 0, 0}}; res = cudf::segmented_reduce(input, d_offsets, *cudf::make_max_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::INCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, null_init_expect); } TYPED_TEST(SegmentedReductionTest, MinIncludeNulls) { // [1, 2, 3], [1, null, 3], [1], [null], [null, null], [] // values: {1, 2, 3, 1, XXX, 3, 1, XXX, XXX} // offsets: {0, 3, 6, 7, 8, 10, 10} // nullmask: {1, 1, 1, 1, 0, 1, 1, 0, 0} // outputs: {1, XXX, 1, XXX, XXX, XXX} // output nullmask: {1, 0, 1, 0, 0, 0} auto const input = cudf::test::fixed_width_column_wrapper<TypeParam>{ {1, 2, 3, 1, XXX, 3, 1, XXX, XXX, XXX}, {1, 1, 1, 1, 0, 1, 1, 0, 0}}; auto const offsets = std::vector<cudf::size_type>{0, 3, 6, 7, 8, 10, 10}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const expect = cudf::test::fixed_width_column_wrapper<TypeParam>{{1, XXX, 1, XXX, XXX, XXX}, {1, 0, 1, 0, 0, 0}}; auto res = cudf::segmented_reduce(input, d_offsets, *cudf::make_min_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); // Test with initial value auto const init_scalar = cudf::make_fixed_width_scalar<TypeParam>(2); auto const init_expect = cudf::test::fixed_width_column_wrapper<TypeParam>{{1, XXX, 1, XXX, XXX, 2}, {1, 0, 1, 0, 0, 1}}; res = cudf::segmented_reduce(input, d_offsets, *cudf::make_min_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::INCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, init_expect); // Test with null initial value init_scalar->set_valid_async(false); auto null_init_expect = cudf::test::fixed_width_column_wrapper<TypeParam>{ {XXX, XXX, XXX, XXX, XXX, XXX}, {0, 0, 0, 0, 0, 0}}; res = cudf::segmented_reduce(input, d_offsets, *cudf::make_min_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<TypeParam>()}, cudf::null_policy::INCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, null_init_expect); } TYPED_TEST(SegmentedReductionTest, AnyIncludeNulls) { // [0, 0, 0], [0, null, 0], [0, 1, 0], [1, null, 0], [], [0], [1], [null], [null, null] // values: {0, 0, 0, 0, XXX, 0, 0, 1, 0, 1, XXX, 0, 0, 1, XXX, XXX, XXX} // offsets: {0, 3, 6, 9, 12, 12, 13, 14, 15, 17} // nullmask:{1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0} // outputs: {0, XXX, 1, XXX, XXX, 0, 1, XXX, XXX} // output nullmask: {1, 0, 1, 0, 0, 1, 1, 0, 0} auto const input = cudf::test::fixed_width_column_wrapper<TypeParam>{ {0, 0, 0, 0, XXX, 0, 0, 1, 0, 1, XXX, 0, 0, 1, XXX, XXX, XXX}, {1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0}}; auto const offsets = std::vector<cudf::size_type>{0, 3, 6, 9, 12, 12, 13, 14, 15, 17}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const expect = cudf::test::fixed_width_column_wrapper<bool>{ {false, bool{XXX}, true, bool{XXX}, bool{XXX}, false, true, bool{XXX}, bool{XXX}}, {true, false, true, false, false, true, true, false, false}}; auto res = cudf::segmented_reduce(input, d_offsets, *cudf::make_any_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_id::BOOL8}, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); // Test with initial value auto const init_scalar = cudf::make_fixed_width_scalar<TypeParam>(1); auto const init_expect = cudf::test::fixed_width_column_wrapper<bool>{ {true, bool{XXX}, true, bool{XXX}, true, true, true, bool{XXX}, bool{XXX}}, {true, false, true, false, true, true, true, false, false}}; res = cudf::segmented_reduce(input, d_offsets, *cudf::make_any_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_id::BOOL8}, cudf::null_policy::INCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, init_expect); // Test with null initial value init_scalar->set_valid_async(false); auto null_init_expect = cudf::test::fixed_width_column_wrapper<bool>{ {bool{XXX}, bool{XXX}, bool{XXX}, bool{XXX}, bool{XXX}, bool{XXX}, bool{XXX}, bool{XXX}, bool{XXX}}, {false, false, false, false, false, false, false, false, false}}; res = cudf::segmented_reduce(input, d_offsets, *cudf::make_any_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_id::BOOL8}, cudf::null_policy::INCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, null_init_expect); } TYPED_TEST(SegmentedReductionTest, AllIncludeNulls) { // [1, 2, 3], [1, null, 3], [], [1], [null], [null, null], [1, 0, 3], [1, null, 0], [0] // values: {1, 2, 3, 1, XXX, 3, 1, XXX, XXX, XXX, 1, 0, 3, 1, XXX, 0, 0} // offsets: {0, 3, 6, 6, 7, 8, 10, 13, 16, 17} // nullmask: {1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1} // outputs: {true, XXX, XXX, true, XXX, XXX, false, XXX, false} // output nullmask: {1, 0, 0, 1, 0, 0, 1, 0, 1} auto const input = cudf::test::fixed_width_column_wrapper<TypeParam>{ {1, 2, 3, 1, XXX, 3, 1, XXX, XXX, XXX, 1, 0, 3, 1, XXX, 0, 0}, {1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1}}; auto const offsets = std::vector<cudf::size_type>{0, 3, 6, 6, 7, 8, 10, 13, 16, 17}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const expect = cudf::test::fixed_width_column_wrapper<bool>{ {true, bool{XXX}, bool{XXX}, true, bool{XXX}, bool{XXX}, false, bool{XXX}, false}, {true, false, false, true, false, false, true, false, true}}; auto res = cudf::segmented_reduce(input, d_offsets, *cudf::make_all_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_id::BOOL8}, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); // Test with initial value auto const init_scalar = cudf::make_fixed_width_scalar<TypeParam>(1); auto const init_expect = cudf::test::fixed_width_column_wrapper<bool>{ {true, bool{XXX}, true, true, bool{XXX}, bool{XXX}, false, bool{XXX}, false}, {true, false, true, true, false, false, true, false, true}}; res = cudf::segmented_reduce(input, d_offsets, *cudf::make_all_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_id::BOOL8}, cudf::null_policy::INCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, init_expect); // Test with null initial value init_scalar->set_valid_async(false); auto null_init_expect = cudf::test::fixed_width_column_wrapper<bool>{ {bool{XXX}, bool{XXX}, bool{XXX}, bool{XXX}, bool{XXX}, bool{XXX}, bool{XXX}, bool{XXX}, bool{XXX}}, {false, false, false, false, false, false, false, false, false}}; res = cudf::segmented_reduce(input, d_offsets, *cudf::make_all_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_id::BOOL8}, cudf::null_policy::INCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, null_init_expect); } TEST_F(SegmentedReductionTestUntyped, PartialSegmentReduction) { // Segmented reduction allows offsets only specify part of the input columns. // [1], [2, 3], [4] // values: {1, 2, 3, 4, 5, 6, 7} // offsets: {0, 1, 3, 4} // nullmask: {1, 1, 1, 1, 1, 1, 1} // outputs: {1, 5, 4} // output nullmask: {1, 1, 1} auto const input = cudf::test::fixed_width_column_wrapper<int32_t>{ {1, 2, 3, 4, 5, 6, 7}, {true, true, true, true, true, true, true}}; auto const offsets = std::vector<cudf::size_type>{1, 3, 4}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const expect = cudf::test::fixed_width_column_wrapper<int32_t>{{5, 4}, {true, true}}; auto res = cudf::segmented_reduce(input, d_offsets, *cudf::make_sum_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_id::INT32}, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); // Test with initial value auto const init_scalar = cudf::make_fixed_width_scalar<int32_t>(3); auto const init_expect = cudf::test::fixed_width_column_wrapper<int32_t>{{8, 7}, {true, true}}; res = cudf::segmented_reduce(input, d_offsets, *cudf::make_sum_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_id::INT32}, cudf::null_policy::INCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, init_expect); // Test with null initial value init_scalar->set_valid_async(false); auto null_init_expect = cudf::test::fixed_width_column_wrapper<int32_t>{{XXX, XXX}, {false, false}}; res = cudf::segmented_reduce(input, d_offsets, *cudf::make_sum_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_id::INT32}, cudf::null_policy::INCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, null_init_expect); } TEST_F(SegmentedReductionTestUntyped, NonNullableInput) { // Segmented reduction allows offsets only specify part of the input columns. // [1], [], [2, 3], [4, 5, 6, 7] // values: {1, 2, 3, 4, 5, 6, 7} // offsets: {0, 1, 1, 3, 7} // nullmask: nullptr // outputs: {1, 5, 4} // output nullmask: {1, 1, 1} auto const input = cudf::test::fixed_width_column_wrapper<int32_t>{1, 2, 3, 4, 5, 6, 7}; auto const offsets = std::vector<cudf::size_type>{0, 1, 1, 3, 7}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const expect = cudf::test::fixed_width_column_wrapper<int32_t>{{1, XXX, 5, 22}, {true, false, true, true}}; auto res = cudf::segmented_reduce(input, d_offsets, *cudf::make_sum_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_id::INT32}, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); // Test with initial value auto const init_scalar = cudf::make_fixed_width_scalar<int32_t>(3); auto const init_expect = cudf::test::fixed_width_column_wrapper<int32_t>{{4, 3, 8, 25}, {true, true, true, true}}; res = cudf::segmented_reduce(input, d_offsets, *cudf::make_sum_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_id::INT32}, cudf::null_policy::INCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, init_expect); // Test with null initial value init_scalar->set_valid_async(false); auto null_init_expect = cudf::test::fixed_width_column_wrapper<int32_t>{ {XXX, XXX, XXX, XXX}, {false, false, false, false}}; res = cudf::segmented_reduce(input, d_offsets, *cudf::make_sum_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_id::INT32}, cudf::null_policy::INCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, null_init_expect); } TEST_F(SegmentedReductionTestUntyped, Mean) { auto const input = cudf::test::fixed_width_column_wrapper<int32_t>{10, 20, 30, 40, 50, 60, 70, 80, 90}; auto const offsets = std::vector<cudf::size_type>{0, 1, 1, 4, 9}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const agg = cudf::make_mean_aggregation<cudf::segmented_reduce_aggregation>(); auto const output_type = cudf::data_type{cudf::type_id::FLOAT32}; auto const expected = cudf::test::fixed_width_column_wrapper<float>{{10, 0, 30, 70}, {1, 0, 1, 1}}; auto result = cudf::segmented_reduce(input, d_offsets, *agg, output_type, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); result = cudf::segmented_reduce(input, d_offsets, *agg, output_type, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } TEST_F(SegmentedReductionTestUntyped, MeanNulls) { auto const input = cudf::test::fixed_width_column_wrapper<int32_t>( {10, 20, 30, 40, 50, 60, 0, 80, 90}, {1, 1, 1, 1, 1, 1, 0, 1, 1}); auto const offsets = std::vector<cudf::size_type>{0, 1, 1, 4, 9}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const agg = cudf::make_mean_aggregation<cudf::segmented_reduce_aggregation>(); auto const output_type = cudf::data_type{cudf::type_id::FLOAT64}; auto expected = cudf::test::fixed_width_column_wrapper<double>{{10, 0, 30, 70}, {1, 0, 1, 1}}; auto result = cudf::segmented_reduce(input, d_offsets, *agg, output_type, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); expected = cudf::test::fixed_width_column_wrapper<double>{{10, 0, 30, 0}, {1, 0, 1, 0}}; result = cudf::segmented_reduce(input, d_offsets, *agg, output_type, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } TEST_F(SegmentedReductionTestUntyped, SumOfSquares) { auto const input = cudf::test::fixed_width_column_wrapper<int32_t>{10, 20, 30, 40, 50, 60, 70, 80, 90}; auto const offsets = std::vector<cudf::size_type>{0, 1, 1, 4, 9}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const agg = cudf::make_sum_of_squares_aggregation<cudf::segmented_reduce_aggregation>(); auto const output_type = cudf::data_type{cudf::type_id::INT32}; auto const expected = cudf::test::fixed_width_column_wrapper<int32_t>{{100, 0, 2900, 25500}, {1, 0, 1, 1}}; auto result = cudf::segmented_reduce(input, d_offsets, *agg, output_type, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); result = cudf::segmented_reduce(input, d_offsets, *agg, output_type, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } TEST_F(SegmentedReductionTestUntyped, SumOfSquaresNulls) { auto const input = cudf::test::fixed_width_column_wrapper<int32_t>( {10, 20, 30, 40, 50, 60, 0, 80, 90}, {1, 1, 1, 1, 1, 1, 0, 1, 1}); auto const offsets = std::vector<cudf::size_type>{0, 1, 1, 4, 9}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const agg = cudf::make_sum_of_squares_aggregation<cudf::segmented_reduce_aggregation>(); auto const output_type = cudf::data_type{cudf::type_id::INT64}; auto expected = cudf::test::fixed_width_column_wrapper<int64_t>{{100, 0, 2900, 20600}, {1, 0, 1, 1}}; auto result = cudf::segmented_reduce(input, d_offsets, *agg, output_type, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); expected = cudf::test::fixed_width_column_wrapper<int64_t>{{100, 0, 2900, 0}, {1, 0, 1, 0}}; result = cudf::segmented_reduce(input, d_offsets, *agg, output_type, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } TEST_F(SegmentedReductionTestUntyped, StandardDeviation) { constexpr float NaN{std::numeric_limits<float>::quiet_NaN()}; auto const input = cudf::test::fixed_width_column_wrapper<int32_t>{10, 20, 30, 40, 50, 60, 70, 80, 90}; auto const offsets = std::vector<cudf::size_type>{0, 1, 1, 4, 9}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const agg = cudf::make_std_aggregation<cudf::segmented_reduce_aggregation>(); auto const output_type = cudf::data_type{cudf::type_id::FLOAT32}; auto expected = cudf::test::fixed_width_column_wrapper<float>{ {NaN, 0.f, 10.f, static_cast<float>(std::sqrt(250.))}, {1, 0, 1, 1}}; auto result = cudf::segmented_reduce(input, d_offsets, *agg, output_type, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); result = cudf::segmented_reduce(input, d_offsets, *agg, output_type, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } TEST_F(SegmentedReductionTestUntyped, StandardDeviationNulls) { constexpr double NaN{std::numeric_limits<double>::quiet_NaN()}; auto const input = cudf::test::fixed_width_column_wrapper<int32_t>( {10, 0, 20, 30, 54, 63, 0, 72, 81}, {1, 0, 1, 1, 1, 1, 0, 1, 1}); auto const offsets = std::vector<cudf::size_type>{0, 1, 1, 4, 9}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const agg = cudf::make_std_aggregation<cudf::segmented_reduce_aggregation>(); auto const output_type = cudf::data_type{cudf::type_id::FLOAT64}; auto expected = cudf::test::fixed_width_column_wrapper<double>{ {NaN, 0., std::sqrt(50.), std::sqrt(135.)}, {1, 0, 1, 1}}; auto result = cudf::segmented_reduce(input, d_offsets, *agg, output_type, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); expected = cudf::test::fixed_width_column_wrapper<double>{{NaN, 0., 0., 0.}, {1, 0, 0, 0}}; result = cudf::segmented_reduce(input, d_offsets, *agg, output_type, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } TEST_F(SegmentedReductionTestUntyped, Variance) { constexpr float NaN{std::numeric_limits<float>::quiet_NaN()}; auto const input = cudf::test::fixed_width_column_wrapper<int32_t>{10, 20, 30, 40, 50, 60, 70, 80, 90}; auto const offsets = std::vector<cudf::size_type>{0, 1, 1, 4, 9}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const agg = cudf::make_variance_aggregation<cudf::segmented_reduce_aggregation>(); auto const output_type = cudf::data_type{cudf::type_id::FLOAT32}; auto expected = cudf::test::fixed_width_column_wrapper<float>{{NaN, 0.f, 100.f, 250.f}, {1, 0, 1, 1}}; auto result = cudf::segmented_reduce(input, d_offsets, *agg, output_type, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); result = cudf::segmented_reduce(input, d_offsets, *agg, output_type, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } TEST_F(SegmentedReductionTestUntyped, VarianceNulls) { constexpr double NaN{std::numeric_limits<double>::quiet_NaN()}; auto const input = cudf::test::fixed_width_column_wrapper<int32_t>( {10, 0, 20, 30, 54, 63, 0, 72, 81}, {1, 0, 1, 1, 1, 1, 0, 1, 1}); auto const offsets = std::vector<cudf::size_type>{0, 1, 1, 4, 9}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const agg = cudf::make_variance_aggregation<cudf::segmented_reduce_aggregation>(); auto const output_type = cudf::data_type{cudf::type_id::FLOAT64}; auto expected = cudf::test::fixed_width_column_wrapper<double>{{NaN, 0., 50., 135.}, {1, 0, 1, 1}}; auto result = cudf::segmented_reduce(input, d_offsets, *agg, output_type, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); expected = cudf::test::fixed_width_column_wrapper<double>{{NaN, 0., 0., 0.}, {1, 0, 0, 0}}; result = cudf::segmented_reduce(input, d_offsets, *agg, output_type, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } TEST_F(SegmentedReductionTestUntyped, NUnique) { auto const input = cudf::test::fixed_width_column_wrapper<int32_t>({10, 15, 20, 30, 60, 60, 70, 70, 80}); auto const offsets = std::vector<cudf::size_type>{0, 1, 1, 2, 4, 9}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const agg = cudf::make_nunique_aggregation<cudf::segmented_reduce_aggregation>(); auto const output_type = cudf::data_type{cudf::type_id::INT32}; auto expected = cudf::test::fixed_width_column_wrapper<cudf::size_type>{{1, 0, 1, 2, 3}, {1, 0, 1, 1, 1}}; auto result = cudf::segmented_reduce(input, d_offsets, *agg, output_type, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); result = cudf::segmented_reduce(input, d_offsets, *agg, output_type, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } TEST_F(SegmentedReductionTestUntyped, NUniqueNulls) { auto const input = cudf::test::fixed_width_column_wrapper<int32_t>( {10, 0, 20, 30, 60, 60, 70, 70, 0}, {1, 0, 1, 1, 1, 1, 1, 1, 0}); auto const offsets = std::vector<cudf::size_type>{0, 1, 1, 2, 4, 9}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const agg = cudf::make_nunique_aggregation<cudf::segmented_reduce_aggregation>(); auto const output_type = cudf::data_type{cudf::type_id::INT32}; auto expected = cudf::test::fixed_width_column_wrapper<cudf::size_type>{{1, 0, 0, 2, 2}, {1, 0, 0, 1, 1}}; auto result = cudf::segmented_reduce(input, d_offsets, *agg, output_type, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); expected = cudf::test::fixed_width_column_wrapper<cudf::size_type>{{1, 0, 1, 2, 3}, {1, 0, 1, 1, 1}}; result = cudf::segmented_reduce(input, d_offsets, *agg, output_type, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*result, expected); } TEST_F(SegmentedReductionTestUntyped, Errors) { auto const input = cudf::test::fixed_width_column_wrapper<int32_t>( {10, 0, 20, 30, 54, 63, 0, 72, 81}, {1, 0, 1, 1, 1, 1, 0, 1, 1}); auto const offsets = std::vector<cudf::size_type>{0, 1, 1, 4, 9}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const null_policy = cudf::null_policy::EXCLUDE; auto const output_type = cudf::data_type{cudf::type_id::TIMESTAMP_DAYS}; auto const str_input = cudf::test::strings_column_wrapper({"10", "0", "20", "30", "54", "63", "", "72", "81"}); auto const sum_agg = cudf::make_sum_aggregation<cudf::segmented_reduce_aggregation>(); EXPECT_THROW(cudf::segmented_reduce(input, d_offsets, *sum_agg, output_type, null_policy), cudf::logic_error); EXPECT_THROW(cudf::segmented_reduce(str_input, d_offsets, *sum_agg, output_type, null_policy), cudf::logic_error); auto const product_agg = cudf::make_product_aggregation<cudf::segmented_reduce_aggregation>(); EXPECT_THROW(cudf::segmented_reduce(input, d_offsets, *product_agg, output_type, null_policy), cudf::logic_error); EXPECT_THROW(cudf::segmented_reduce(str_input, d_offsets, *product_agg, output_type, null_policy), cudf::logic_error); auto const min_agg = cudf::make_min_aggregation<cudf::segmented_reduce_aggregation>(); EXPECT_THROW(cudf::segmented_reduce(input, d_offsets, *min_agg, output_type, null_policy), cudf::logic_error); auto const max_agg = cudf::make_max_aggregation<cudf::segmented_reduce_aggregation>(); EXPECT_THROW(cudf::segmented_reduce(input, d_offsets, *max_agg, output_type, null_policy), cudf::logic_error); auto const any_agg = cudf::make_any_aggregation<cudf::segmented_reduce_aggregation>(); EXPECT_THROW(cudf::segmented_reduce(input, d_offsets, *any_agg, output_type, null_policy), cudf::logic_error); EXPECT_THROW(cudf::segmented_reduce(str_input, d_offsets, *any_agg, output_type, null_policy), cudf::logic_error); auto const all_agg = cudf::make_all_aggregation<cudf::segmented_reduce_aggregation>(); EXPECT_THROW(cudf::segmented_reduce(input, d_offsets, *all_agg, output_type, null_policy), cudf::logic_error); EXPECT_THROW(cudf::segmented_reduce(str_input, d_offsets, *all_agg, output_type, null_policy), cudf::logic_error); auto const mean_agg = cudf::make_mean_aggregation<cudf::segmented_reduce_aggregation>(); EXPECT_THROW(cudf::segmented_reduce(input, d_offsets, *mean_agg, output_type, null_policy), cudf::logic_error); EXPECT_THROW(cudf::segmented_reduce(str_input, d_offsets, *mean_agg, output_type, null_policy), cudf::logic_error); auto const std_agg = cudf::make_std_aggregation<cudf::segmented_reduce_aggregation>(); EXPECT_THROW(cudf::segmented_reduce(input, d_offsets, *std_agg, output_type, null_policy), cudf::logic_error); EXPECT_THROW(cudf::segmented_reduce(str_input, d_offsets, *std_agg, output_type, null_policy), cudf::logic_error); auto const var_agg = cudf::make_variance_aggregation<cudf::segmented_reduce_aggregation>(); EXPECT_THROW(cudf::segmented_reduce(input, d_offsets, *var_agg, output_type, null_policy), cudf::logic_error); EXPECT_THROW(cudf::segmented_reduce(str_input, d_offsets, *var_agg, output_type, null_policy), cudf::logic_error); auto const squares_agg = cudf::make_sum_of_squares_aggregation<cudf::segmented_reduce_aggregation>(); EXPECT_THROW(cudf::segmented_reduce(input, d_offsets, *squares_agg, output_type, null_policy), cudf::logic_error); EXPECT_THROW(cudf::segmented_reduce(str_input, d_offsets, *squares_agg, output_type, null_policy), cudf::logic_error); } TEST_F(SegmentedReductionTestUntyped, ReduceEmptyColumn) { auto const input = cudf::test::fixed_width_column_wrapper<int32_t>{}; auto const offsets = std::vector<cudf::size_type>{0}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const expect = cudf::test::fixed_width_column_wrapper<int32_t>{}; auto res = cudf::segmented_reduce(input, d_offsets, *cudf::make_sum_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<int32_t>()}, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); // Test with initial value auto const init_scalar = cudf::make_fixed_width_scalar<int32_t>(3); res = cudf::segmented_reduce(input, d_offsets, *cudf::make_sum_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<int32_t>()}, cudf::null_policy::EXCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); // Test with null initial value init_scalar->set_valid_async(false); res = cudf::segmented_reduce(input, d_offsets, *cudf::make_sum_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_to_id<int32_t>()}, cudf::null_policy::EXCLUDE, *init_scalar); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); } TEST_F(SegmentedReductionTestUntyped, EmptyInputWithOffsets) { auto const input = cudf::test::fixed_width_column_wrapper<int32_t>{}; auto const offsets = std::vector<cudf::size_type>{0, 0, 0, 0, 0, 0}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const expect = cudf::test::fixed_width_column_wrapper<int32_t>{{XXX, XXX, XXX, XXX, XXX}, {0, 0, 0, 0, 0}}; auto aggregates = std::vector<std::unique_ptr<cudf::segmented_reduce_aggregation, std::default_delete<cudf::segmented_reduce_aggregation>>>(); aggregates.push_back(std::move(cudf::make_max_aggregation<cudf::segmented_reduce_aggregation>())); aggregates.push_back(std::move(cudf::make_min_aggregation<cudf::segmented_reduce_aggregation>())); aggregates.push_back(std::move(cudf::make_sum_aggregation<cudf::segmented_reduce_aggregation>())); aggregates.push_back( std::move(cudf::make_product_aggregation<cudf::segmented_reduce_aggregation>())); auto output_type = cudf::data_type{cudf::type_to_id<int32_t>()}; for (auto&& agg : aggregates) { auto result = cudf::segmented_reduce(input, d_offsets, *agg, output_type, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } auto const expect_bool = cudf::test::fixed_width_column_wrapper<bool>{{XXX, XXX, XXX, XXX, XXX}, {0, 0, 0, 0, 0}}; auto result = cudf::segmented_reduce(input, d_offsets, *cudf::make_any_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_id::BOOL8}, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect_bool); result = cudf::segmented_reduce(input, d_offsets, *cudf::make_all_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_id::BOOL8}, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect_bool); } template <typename T> struct SegmentedReductionFixedPointTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(SegmentedReductionFixedPointTest, cudf::test::FixedPointTypes); TYPED_TEST(SegmentedReductionFixedPointTest, MaxWithNulls) { using RepType = cudf::device_storage_type_t<TypeParam>; auto const offsets = std::vector<cudf::size_type>{0, 3, 6, 7, 8, 10, 10}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const agg = cudf::make_max_aggregation<cudf::segmented_reduce_aggregation>(); for (auto scale : {-2, 0, 5}) { auto const input = cudf::test::fixed_point_column_wrapper<RepType>({1, 2, 3, 1, XXX, 3, 1, XXX, XXX, XXX}, {1, 1, 1, 1, 0, 1, 1, 0, 0, 0}, numeric::scale_type{scale}); auto out_type = cudf::column_view(input).type(); auto expect = cudf::test::fixed_point_column_wrapper<RepType>( {3, XXX, 1, XXX, XXX, XXX}, {1, 0, 1, 0, 0, 0}, numeric::scale_type{scale}); auto result = cudf::segmented_reduce(input, d_offsets, *agg, out_type, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); expect = cudf::test::fixed_point_column_wrapper<RepType>( {3, 3, 1, XXX, XXX, XXX}, {1, 1, 1, 0, 0, 0}, numeric::scale_type{scale}); result = cudf::segmented_reduce(input, d_offsets, *agg, out_type, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } } TYPED_TEST(SegmentedReductionFixedPointTest, MinWithNulls) { using RepType = cudf::device_storage_type_t<TypeParam>; auto const offsets = std::vector<cudf::size_type>{0, 3, 6, 7, 8, 10, 10}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const agg = cudf::make_min_aggregation<cudf::segmented_reduce_aggregation>(); for (auto scale : {-2, 0, 5}) { auto const input = cudf::test::fixed_point_column_wrapper<RepType>({1, 2, 3, 1, XXX, 3, 1, XXX, XXX, XXX}, {1, 1, 1, 1, 0, 1, 1, 0, 0, 0}, numeric::scale_type{scale}); auto out_type = cudf::column_view(input).type(); auto expect = cudf::test::fixed_point_column_wrapper<RepType>( {1, XXX, 1, XXX, XXX, XXX}, {1, 0, 1, 0, 0, 0}, numeric::scale_type{scale}); auto result = cudf::segmented_reduce(input, d_offsets, *agg, out_type, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); expect = cudf::test::fixed_point_column_wrapper<RepType>( {1, 1, 1, XXX, XXX, XXX}, {1, 1, 1, 0, 0, 0}, numeric::scale_type{scale}); result = cudf::segmented_reduce(input, d_offsets, *agg, out_type, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } } TYPED_TEST(SegmentedReductionFixedPointTest, MaxNonNullableInput) { using RepType = cudf::device_storage_type_t<TypeParam>; auto const offsets = std::vector<cudf::size_type>{0, 3, 4, 4}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const agg = cudf::make_max_aggregation<cudf::segmented_reduce_aggregation>(); for (auto scale : {-2, 0, 5}) { auto const input = cudf::test::fixed_point_column_wrapper<RepType>({1, 2, 3, 1}, numeric::scale_type{scale}); auto out_type = cudf::column_view(input).type(); auto const expect = cudf::test::fixed_point_column_wrapper<RepType>( {3, 1, XXX}, {1, 1, 0}, numeric::scale_type{scale}); auto result = cudf::segmented_reduce(input, d_offsets, *agg, out_type, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); result = cudf::segmented_reduce(input, d_offsets, *agg, out_type, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } } TYPED_TEST(SegmentedReductionFixedPointTest, MinNonNullableInput) { using RepType = cudf::device_storage_type_t<TypeParam>; auto const offsets = std::vector<cudf::size_type>{0, 3, 4, 4}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const agg = cudf::make_min_aggregation<cudf::segmented_reduce_aggregation>(); for (auto scale : {-2, 0, 5}) { auto const input = cudf::test::fixed_point_column_wrapper<RepType>({1, 2, 3, 1}, numeric::scale_type{scale}); auto out_type = cudf::column_view(input).type(); auto const expect = cudf::test::fixed_point_column_wrapper<RepType>( {1, 1, XXX}, {1, 1, 0}, numeric::scale_type{scale}); auto result = cudf::segmented_reduce(input, d_offsets, *agg, out_type, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); result = cudf::segmented_reduce(input, d_offsets, *agg, out_type, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } } TYPED_TEST(SegmentedReductionFixedPointTest, Sum) { using RepType = cudf::device_storage_type_t<TypeParam>; auto const offsets = std::vector<cudf::size_type>{0, 3, 6, 7, 8, 10, 10}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const agg = cudf::make_sum_aggregation<cudf::segmented_reduce_aggregation>(); for (auto scale : {-2, 0, 5}) { auto input = cudf::test::fixed_point_column_wrapper<RepType>({-10, 0, 33, 100, XXX, 53, 11, XXX, XXX, XXX}, {1, 1, 1, 1, 0, 1, 1, 0, 0, 0}, numeric::scale_type{scale}); auto const out_type = cudf::column_view(input).type(); auto expect = cudf::test::fixed_point_column_wrapper<RepType>( {23, XXX, 11, XXX, XXX, XXX}, {1, 0, 1, 0, 0, 0}, numeric::scale_type{scale}); auto result = cudf::segmented_reduce(input, d_offsets, *agg, out_type, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); expect = cudf::test::fixed_point_column_wrapper<RepType>( {23, 153, 11, XXX, XXX, XXX}, {1, 1, 1, 0, 0, 0}, numeric::scale_type{scale}); result = cudf::segmented_reduce(input, d_offsets, *agg, out_type, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); input = cudf::test::fixed_point_column_wrapper<RepType>( {-10, 0, 33, 100, 123, 53, 11, 0, -120, 88}, numeric::scale_type{scale}); expect = cudf::test::fixed_point_column_wrapper<RepType>( {23, 276, 11, 0, -32, XXX}, {1, 1, 1, 1, 1, 0}, numeric::scale_type{scale}); result = cudf::segmented_reduce(input, d_offsets, *agg, out_type, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); result = cudf::segmented_reduce(input, d_offsets, *agg, out_type, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } } TYPED_TEST(SegmentedReductionFixedPointTest, Product) { using RepType = cudf::device_storage_type_t<TypeParam>; auto const offsets = std::vector<cudf::size_type>{0, 3, 6, 7, 8, 12, 12}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const agg = cudf::make_product_aggregation<cudf::segmented_reduce_aggregation>(); for (auto scale : {-2, 0, 5}) { auto input = cudf::test::fixed_point_column_wrapper<RepType>( {-10, 1, 33, 40, XXX, 50, 11000, XXX, XXX, XXX, XXX, XXX}, {1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0}, numeric::scale_type{scale}); auto const out_type = cudf::column_view(input).type(); auto result = cudf::segmented_reduce(input, d_offsets, *agg, out_type, cudf::null_policy::INCLUDE); auto expect = cudf::test::fixed_point_column_wrapper<RepType>( {-330, XXX, 11000, XXX, XXX, XXX}, {1, 0, 1, 0, 0, 0}, numeric::scale_type{scale * 3}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); result = cudf::segmented_reduce(input, d_offsets, *agg, out_type, cudf::null_policy::EXCLUDE); expect = cudf::test::fixed_point_column_wrapper<RepType>( {-330, 2000, 11000, XXX, XXX, XXX}, {1, 1, 1, 0, 0, 0}, numeric::scale_type{scale * 3}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); input = cudf::test::fixed_point_column_wrapper<RepType>( {-10, 1, 33, 3, 40, 50, 11000, 0, -3, 50, 10, 4}, numeric::scale_type{scale}); expect = cudf::test::fixed_point_column_wrapper<RepType>( {-330, 6000, 11000, 0, -6000, XXX}, {1, 1, 1, 1, 1, 0}, numeric::scale_type{scale * 4}); result = cudf::segmented_reduce(input, d_offsets, *agg, out_type, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); result = cudf::segmented_reduce(input, d_offsets, *agg, out_type, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } } TYPED_TEST(SegmentedReductionFixedPointTest, SumOfSquares) { using RepType = cudf::device_storage_type_t<TypeParam>; auto const offsets = std::vector<cudf::size_type>{0, 3, 6, 7, 8, 10, 10}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const agg = cudf::make_sum_of_squares_aggregation<cudf::segmented_reduce_aggregation>(); for (auto scale : {-2, 0, 5}) { auto input = cudf::test::fixed_point_column_wrapper<RepType>({-10, 0, 33, 100, XXX, 53, 11, XXX, XXX, XXX}, {1, 1, 1, 1, 0, 1, 1, 0, 0, 0}, numeric::scale_type{scale}); auto const out_type = cudf::column_view(input).type(); auto expect = cudf::test::fixed_point_column_wrapper<RepType>( {1189, XXX, 121, XXX, XXX, XXX}, {1, 0, 1, 0, 0, 0}, numeric::scale_type{scale * 2}); auto result = cudf::segmented_reduce(input, d_offsets, *agg, out_type, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); expect = cudf::test::fixed_point_column_wrapper<RepType>( {1189, 12809, 121, XXX, XXX, XXX}, {1, 1, 1, 0, 0, 0}, numeric::scale_type{scale * 2}); result = cudf::segmented_reduce(input, d_offsets, *agg, out_type, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); input = cudf::test::fixed_point_column_wrapper<RepType>( {-10, 0, 33, 100, 123, 53, 11, 0, -120, 88}, numeric::scale_type{scale}); expect = cudf::test::fixed_point_column_wrapper<RepType>( {1189, 27938, 121, 0, 22144, XXX}, {1, 1, 1, 1, 1, 0}, numeric::scale_type{scale * 2}); result = cudf::segmented_reduce(input, d_offsets, *agg, out_type, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); result = cudf::segmented_reduce(input, d_offsets, *agg, out_type, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } } // String min/max test grid // Segment: Length 0, length 1, length 2 // Element nulls: No nulls, all nulls, some nulls // String: Empty string, // Position of the min/max: start of segment, end of segment // Include null, exclude null #undef XXX #define XXX "" // null placeholder struct SegmentedReductionStringTest : public cudf::test::BaseFixture { std::pair<cudf::test::strings_column_wrapper, cudf::test::fixed_width_column_wrapper<cudf::size_type>> input() { return std::pair( cudf::test::strings_column_wrapper{ {"world", "cudf", XXX, "", "rapids", "i am", "ai", "apples", "zebras", XXX, XXX, XXX}, {true, true, false, true, true, true, true, true, true, false, false, false}}, cudf::test::fixed_width_column_wrapper<cudf::size_type>{0, 1, 4, 7, 9, 9, 10, 12}); } }; TEST_F(SegmentedReductionStringTest, MaxIncludeNulls) { // data: ['world'], ['cudf', NULL, ''], ['rapids', 'i am', 'ai'], ['apples', 'zebras'], // [], [NULL], [NULL, NULL] // values: {"world", "cudf", XXX, "", "rapids", "i am", "ai", "apples", "zebras", XXX, XXX, XXX} // nullmask:{1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0} // offsets: {0, 1, 4, 7, 9, 9, 10, 12} // output_dtype: string dtype // outputs: {"world", XXX, "rapids", "zebras", XXX, XXX, XXX} // output nullmask: {1, 0, 1, 1, 0, 0, 0} auto const [input, offsets] = this->input(); cudf::data_type output_dtype{cudf::type_id::STRING}; cudf::test::strings_column_wrapper expect{{"world", XXX, "rapids", "zebras", XXX, XXX, XXX}, {true, false, true, true, false, false, false}}; auto res = cudf::segmented_reduce(input, cudf::column_view(offsets), *cudf::make_max_aggregation<cudf::segmented_reduce_aggregation>(), output_dtype, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); } TEST_F(SegmentedReductionStringTest, MaxExcludeNulls) { // data: ['world'], ['cudf', NULL, ''], ['rapids', 'i am', 'ai'], ['apples', 'zebras'], // [], [NULL], [NULL, NULL] // values: {"world", "cudf", XXX, "", "rapids", "i am", "ai", "apples", "zebras", XXX, XXX, XXX} // nullmask:{1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0} // offsets: {0, 1, 4, 7, 9, 9, 10, 12} // output_dtype: string dtype // outputs: {"world", "cudf", "rapids", "zebras", XXX, XXX, XXX} // output nullmask: {1, 1, 1, 1, 0, 0, 0} auto const [input, offsets] = this->input(); cudf::data_type output_dtype{cudf::type_id::STRING}; cudf::test::strings_column_wrapper expect{{"world", "cudf", "rapids", "zebras", XXX, XXX, XXX}, {true, true, true, true, false, false, false}}; auto res = cudf::segmented_reduce(input, cudf::column_view(offsets), *cudf::make_max_aggregation<cudf::segmented_reduce_aggregation>(), output_dtype, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); } TEST_F(SegmentedReductionStringTest, MinIncludeNulls) { // data: ['world'], ['cudf', NULL, ''], ['rapids', 'i am', 'ai'], ['apples', 'zebras'], // [], [NULL], [NULL, NULL] // values: {"world", "cudf", XXX, "", "rapids", "i am", "ai", "apples", "zebras", XXX, XXX, XXX} // nullmask:{1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0} // offsets: {0, 1, 4, 7, 9, 9, 10, 12} // output_dtype: string dtype // outputs: {"world", XXX, "ai", "apples", XXX, XXX, XXX} // output nullmask: {1, 0, 1, 1, 0, 0, 0} auto const [input, offsets] = this->input(); cudf::data_type output_dtype{cudf::type_id::STRING}; cudf::test::strings_column_wrapper expect{{"world", XXX, "ai", "apples", XXX, XXX, XXX}, {true, false, true, true, false, false, false}}; auto res = cudf::segmented_reduce(input, cudf::column_view(offsets), *cudf::make_min_aggregation<cudf::segmented_reduce_aggregation>(), output_dtype, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); } TEST_F(SegmentedReductionStringTest, MinExcludeNulls) { // data: ['world'], ['cudf', NULL, ''], ['rapids', 'i am', 'ai'], ['apples', 'zebras'], // [], [NULL], [NULL, NULL] // values: {"world", "cudf", XXX, "", "rapids", "i am", "ai", "apples", "zebras", XXX, XXX, XXX} // nullmask:{1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0} // offsets: {0, 1, 4, 7, 9, 9, 10, 12} // output_dtype: string dtype // outputs: {"world", "", "ai", "apples", XXX, XXX, XXX} // output nullmask: {1, 1, 1, 1, 0, 0, 0} auto const [input, offsets] = this->input(); cudf::data_type output_dtype{cudf::type_id::STRING}; cudf::test::strings_column_wrapper expect{{"world", "", "ai", "apples", XXX, XXX, XXX}, {true, true, true, true, false, false, false}}; auto res = cudf::segmented_reduce(input, cudf::column_view(offsets), *cudf::make_min_aggregation<cudf::segmented_reduce_aggregation>(), output_dtype, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*res, expect); } TEST_F(SegmentedReductionStringTest, EmptyInputWithOffsets) { auto const input = cudf::test::strings_column_wrapper{}; auto const offsets = std::vector<cudf::size_type>{0, 0, 0, 0}; auto const d_offsets = cudf::detail::make_device_uvector_async( offsets, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto const expect = cudf::test::strings_column_wrapper({XXX, XXX, XXX}, {0, 0, 0}); auto result = cudf::segmented_reduce(input, d_offsets, *cudf::make_max_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_id::STRING}, cudf::null_policy::EXCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); result = cudf::segmented_reduce(input, d_offsets, *cudf::make_min_aggregation<cudf::segmented_reduce_aggregation>(), cudf::data_type{cudf::type_id::STRING}, cudf::null_policy::INCLUDE); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, expect); } #undef XXX
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/reductions/tdigest_tests.cu
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/tdigest_utilities.cuh> #include <cudf_test/type_lists.hpp> #include <cudf/reduction.hpp> template <typename T> struct ReductionTDigestAllTypes : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(ReductionTDigestAllTypes, cudf::test::NumericTypes); struct reduce_op { std::unique_ptr<cudf::column> operator()(cudf::column_view const& values, int delta) const { // result is a scalar, but we want to extract out the underlying column auto scalar_result = cudf::reduce(values, *cudf::make_tdigest_aggregation<cudf::reduce_aggregation>(delta), cudf::data_type{cudf::type_id::STRUCT}); auto tbl = static_cast<cudf::struct_scalar const*>(scalar_result.get())->view(); std::vector<std::unique_ptr<cudf::column>> cols; std::transform( tbl.begin(), tbl.end(), std::back_inserter(cols), [](cudf::column_view const& col) { return std::make_unique<cudf::column>(col); }); return cudf::make_structs_column(tbl.num_rows(), std::move(cols), 0, rmm::device_buffer()); } }; struct reduce_merge_op { std::unique_ptr<cudf::column> operator()(cudf::column_view const& values, int delta) const { // result is a scalar, but we want to extract out the underlying column auto scalar_result = cudf::reduce(values, *cudf::make_merge_tdigest_aggregation<cudf::reduce_aggregation>(delta), cudf::data_type{cudf::type_id::STRUCT}); auto tbl = static_cast<cudf::struct_scalar const*>(scalar_result.get())->view(); std::vector<std::unique_ptr<cudf::column>> cols; std::transform( tbl.begin(), tbl.end(), std::back_inserter(cols), [](cudf::column_view const& col) { return std::make_unique<cudf::column>(col); }); return cudf::make_structs_column(tbl.num_rows(), std::move(cols), 0, rmm::device_buffer()); } }; TYPED_TEST(ReductionTDigestAllTypes, Simple) { using T = TypeParam; cudf::test::tdigest_simple_aggregation<T>(reduce_op{}); } TYPED_TEST(ReductionTDigestAllTypes, SimpleWithNulls) { using T = TypeParam; cudf::test::tdigest_simple_with_nulls_aggregation<T>(reduce_op{}); } TYPED_TEST(ReductionTDigestAllTypes, AllNull) { using T = TypeParam; cudf::test::tdigest_simple_all_nulls_aggregation<T>(reduce_op{}); } struct ReductionTDigestMerge : public cudf::test::BaseFixture {}; TEST_F(ReductionTDigestMerge, Simple) { cudf::test::tdigest_merge_simple(reduce_op{}, reduce_merge_op{}); } // tests an issue with the cluster generating code with a small number of centroids that have large // weights TEST_F(ReductionTDigestMerge, FewHeavyCentroids) { // digest 1 cudf::test::fixed_width_column_wrapper<double> c0c{1.0, 2.0}; cudf::test::fixed_width_column_wrapper<double> c0w{100.0, 50.0}; cudf::test::structs_column_wrapper c0s({c0c, c0w}); cudf::test::fixed_width_column_wrapper<cudf::size_type> c0_offsets{0, 2}; auto c0l = cudf::make_lists_column(1, c0_offsets.release(), c0s.release(), 0, rmm::device_buffer{}); cudf::test::fixed_width_column_wrapper<double> c0min{1.0}; cudf::test::fixed_width_column_wrapper<double> c0max{2.0}; std::vector<std::unique_ptr<cudf::column>> c0_children; c0_children.push_back(std::move(c0l)); c0_children.push_back(c0min.release()); c0_children.push_back(c0max.release()); // tdigest struct auto c0 = cudf::make_structs_column(1, std::move(c0_children), 0, {}); cudf::tdigest::tdigest_column_view tdv0(*c0); // digest 2 cudf::test::fixed_width_column_wrapper<double> c1c{3.0, 4.0}; cudf::test::fixed_width_column_wrapper<double> c1w{200.0, 50.0}; cudf::test::structs_column_wrapper c1s({c1c, c1w}); cudf::test::fixed_width_column_wrapper<cudf::size_type> c1_offsets{0, 2}; auto c1l = cudf::make_lists_column(1, c1_offsets.release(), c1s.release(), 0, rmm::device_buffer{}); cudf::test::fixed_width_column_wrapper<double> c1min{3.0}; cudf::test::fixed_width_column_wrapper<double> c1max{4.0}; std::vector<std::unique_ptr<cudf::column>> c1_children; c1_children.push_back(std::move(c1l)); c1_children.push_back(c1min.release()); c1_children.push_back(c1max.release()); // tdigest struct auto c1 = cudf::make_structs_column(1, std::move(c1_children), 0, {}); std::vector<cudf::column_view> views; views.push_back(*c0); views.push_back(*c1); auto values = cudf::concatenate(views); // merge auto scalar_result = cudf::reduce(*values, *cudf::make_merge_tdigest_aggregation<cudf::reduce_aggregation>(1000), cudf::data_type{cudf::type_id::STRUCT}); // convert to a table auto tbl = static_cast<cudf::struct_scalar const*>(scalar_result.get())->view(); std::vector<std::unique_ptr<cudf::column>> cols; std::transform( tbl.begin(), tbl.end(), std::back_inserter(cols), [](cudf::column_view const& col) { return std::make_unique<cudf::column>(col); }); auto result = cudf::make_structs_column(tbl.num_rows(), std::move(cols), 0, rmm::device_buffer()); // we expect to see exactly 4 centroids (the same inputs) with properly computed min/max. cudf::test::fixed_width_column_wrapper<double> ec{1.0, 2.0, 3.0, 4.0}; cudf::test::fixed_width_column_wrapper<double> ew{100.0, 50.0, 200.0, 50.0}; cudf::test::structs_column_wrapper es({ec, ew}); cudf::test::fixed_width_column_wrapper<cudf::size_type> e_offsets{0, 4}; auto el = cudf::make_lists_column(1, e_offsets.release(), es.release(), 0, rmm::device_buffer{}); cudf::test::fixed_width_column_wrapper<double> emin{1.0}; cudf::test::fixed_width_column_wrapper<double> emax{4.0}; std::vector<std::unique_ptr<cudf::column>> e_children; e_children.push_back(std::move(el)); e_children.push_back(emin.release()); e_children.push_back(emax.release()); // tdigest struct auto expected = cudf::make_structs_column(1, std::move(e_children), 0, {}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*result, *expected); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/reductions/collect_ops_tests.cpp
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/aggregation.hpp> #include <cudf/reduction.hpp> #include <cudf/sorting.hpp> namespace { auto collect_set(cudf::column_view const& input, std::unique_ptr<cudf::reduce_aggregation> const& agg) { auto const result_scalar = cudf::reduce(input, *agg, cudf::data_type{cudf::type_id::LIST}); // The results of `collect_set` are unordered thus we need to sort them for comparison. auto const result_sorted_table = cudf::sort(cudf::table_view{{dynamic_cast<cudf::list_scalar*>(result_scalar.get())->view()}}, {}, {cudf::null_order::AFTER}); return std::make_unique<cudf::list_scalar>(std::move(result_sorted_table->get_column(0))); } } // namespace template <typename T> struct CollectTestFixedWidth : public cudf::test::BaseFixture {}; using CollectFixedWidthTypes = cudf::test::Concat<cudf::test::IntegralTypesNotBool, cudf::test::FloatingPointTypes, cudf::test::ChronoTypes, cudf::test::FixedPointTypes>; TYPED_TEST_SUITE(CollectTestFixedWidth, CollectFixedWidthTypes); // ------------------------------------------------------------------------ TYPED_TEST(CollectTestFixedWidth, CollectList) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; std::vector<int> values({5, 0, -120, -111, 0, 64, 63, 99, 123, -16}); std::vector<bool> null_mask({1, 1, 0, 1, 1, 1, 0, 1, 0, 1}); // null_include without nulls fw_wrapper col(values.begin(), values.end()); auto const ret = cudf::reduce(col, *cudf::make_collect_list_aggregation<cudf::reduce_aggregation>(), cudf::data_type{cudf::type_id::LIST}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(col, dynamic_cast<cudf::list_scalar*>(ret.get())->view()); // null_include with nulls fw_wrapper col_with_null(values.begin(), values.end(), null_mask.begin()); auto const ret1 = cudf::reduce(col_with_null, *cudf::make_collect_list_aggregation<cudf::reduce_aggregation>(), cudf::data_type{cudf::type_id::LIST}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(col_with_null, dynamic_cast<cudf::list_scalar*>(ret1.get())->view()); // null_exclude with nulls fw_wrapper col_null_filtered{{5, 0, -111, 0, 64, 99, -16}}; auto const ret2 = cudf::reduce( col_with_null, *cudf::make_collect_list_aggregation<cudf::reduce_aggregation>(cudf::null_policy::EXCLUDE), cudf::data_type{cudf::type_id::LIST}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(col_null_filtered, dynamic_cast<cudf::list_scalar*>(ret2.get())->view()); } TYPED_TEST(CollectTestFixedWidth, CollectSet) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; std::vector<int> values({5, 0, 120, 0, 0, 64, 64, 99, 120, 99}); std::vector<bool> null_mask({1, 1, 0, 1, 1, 1, 0, 1, 0, 1}); fw_wrapper col(values.begin(), values.end()); fw_wrapper col_with_null(values.begin(), values.end(), null_mask.begin()); auto null_exclude = cudf::make_collect_set_aggregation<cudf::reduce_aggregation>( cudf::null_policy::EXCLUDE, cudf::null_equality::UNEQUAL, cudf::nan_equality::ALL_EQUAL); auto null_eq = cudf::make_collect_set_aggregation<cudf::reduce_aggregation>( cudf::null_policy::INCLUDE, cudf::null_equality::EQUAL, cudf::nan_equality::ALL_EQUAL); auto null_unequal = cudf::make_collect_set_aggregation<cudf::reduce_aggregation>( cudf::null_policy::INCLUDE, cudf::null_equality::UNEQUAL, cudf::nan_equality::ALL_EQUAL); // test without nulls auto const ret = collect_set(col, null_eq); fw_wrapper expected{{0, 5, 64, 99, 120}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, dynamic_cast<cudf::list_scalar*>(ret.get())->view()); // null exclude auto const ret1 = collect_set(col_with_null, null_exclude); fw_wrapper expected1{{0, 5, 64, 99}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected1, dynamic_cast<cudf::list_scalar*>(ret1.get())->view()); // null equal auto const ret2 = collect_set(col_with_null, null_eq); fw_wrapper expected2{{0, 5, 64, 99, -1}, {1, 1, 1, 1, 0}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected2, dynamic_cast<cudf::list_scalar*>(ret2.get())->view()); // null unequal auto const ret3 = collect_set(col_with_null, null_unequal); fw_wrapper expected3{{0, 5, 64, 99, -1, -1, -1}, {1, 1, 1, 1, 0, 0, 0}}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected3, dynamic_cast<cudf::list_scalar*>(ret3.get())->view()); } TYPED_TEST(CollectTestFixedWidth, MergeLists) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; using lists_col = cudf::test::lists_column_wrapper<TypeParam, int32_t>; // test without nulls auto const lists1 = lists_col{{1, 2, 3}, {}, {}, {4}, {5, 6, 7}, {8, 9}, {}}; auto const expected1 = fw_wrapper{{1, 2, 3, 4, 5, 6, 7, 8, 9}}; auto const ret1 = cudf::reduce(lists1, *cudf::make_merge_lists_aggregation<cudf::reduce_aggregation>(), cudf::data_type{cudf::type_id::LIST}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected1, dynamic_cast<cudf::list_scalar*>(ret1.get())->view()); // test with nulls auto const lists2 = lists_col{{ lists_col{1, 2, 3}, lists_col{}, lists_col{{0, 4, 0, 5}, cudf::test::iterators::nulls_at({0, 2})}, lists_col{{0, 0, 0}, cudf::test::iterators::all_nulls()}, lists_col{6}, lists_col{-1, -1}, // null_list lists_col{7, 8, 9}, }, cudf::test::iterators::null_at(5)}; auto const expected2 = fw_wrapper{{1, 2, 3, 0, 4, 0, 5, 0, 0, 0, 6, 7, 8, 9}, {1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1}}; auto const ret2 = cudf::reduce(lists2, *cudf::make_merge_lists_aggregation<cudf::reduce_aggregation>(), cudf::data_type{cudf::type_id::LIST}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected2, dynamic_cast<cudf::list_scalar*>(ret2.get())->view()); } TYPED_TEST(CollectTestFixedWidth, MergeSets) { using fw_wrapper = cudf::test::fixed_width_column_wrapper<TypeParam, int32_t>; using lists_col = cudf::test::lists_column_wrapper<TypeParam, int32_t>; // test without nulls auto const lists1 = lists_col{{1, 2, 3}, {}, {}, {4}, {1, 3, 4}, {0, 3, 10}, {}}; auto const expected1 = fw_wrapper{{0, 1, 2, 3, 4, 10}}; auto const ret1 = collect_set(lists1, cudf::make_merge_sets_aggregation<cudf::reduce_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected1, dynamic_cast<cudf::list_scalar*>(ret1.get())->view()); // test with null_equal auto const lists2 = lists_col{{ lists_col{1, 2, 3}, lists_col{}, lists_col{{0, 4, 0, 5}, cudf::test::iterators::nulls_at({0, 2})}, lists_col{{0, 0, 0}, cudf::test::iterators::all_nulls()}, lists_col{5}, lists_col{-1, -1}, // null_list lists_col{1, 3, 5}, }, cudf::test::iterators::null_at(5)}; auto const expected2 = fw_wrapper{{1, 2, 3, 4, 5, 0}, {1, 1, 1, 1, 1, 0}}; auto const ret2 = collect_set(lists2, cudf::make_merge_sets_aggregation<cudf::reduce_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected2, dynamic_cast<cudf::list_scalar*>(ret2.get())->view()); // test with null_unequal auto const& lists3 = lists2; auto const expected3 = fw_wrapper{{1, 2, 3, 4, 5, 0, 0, 0, 0, 0}, {1, 1, 1, 1, 1, 0, 0, 0, 0, 0}}; auto const ret3 = collect_set( lists3, cudf::make_merge_sets_aggregation<cudf::reduce_aggregation>(cudf::null_equality::UNEQUAL)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected3, dynamic_cast<cudf::list_scalar*>(ret3.get())->view()); } struct CollectTest : public cudf::test::BaseFixture {}; TEST_F(CollectTest, CollectSetWithNaN) { using fp_wrapper = cudf::test::fixed_width_column_wrapper<float>; fp_wrapper col{{1.0f, 1.0f, -2.3e-5f, -2.3e-5f, 2.3e5f, 2.3e5f, -NAN, -NAN, NAN, NAN, 0.0f, 0.0f}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0}}; // nan unequal with null equal fp_wrapper expected1{{-2.3e-5f, 1.0f, 2.3e5f, -NAN, -NAN, NAN, NAN, 0.0f}, {1, 1, 1, 1, 1, 1, 1, 0}}; auto const ret1 = collect_set( col, cudf::make_collect_set_aggregation<cudf::reduce_aggregation>( cudf::null_policy::INCLUDE, cudf::null_equality::EQUAL, cudf::nan_equality::UNEQUAL)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected1, dynamic_cast<cudf::list_scalar*>(ret1.get())->view()); // nan unequal with null unequal fp_wrapper expected2{{-2.3e-5f, 1.0f, 2.3e5f, -NAN, -NAN, NAN, NAN, 0.0f, 0.0f}, {1, 1, 1, 1, 1, 1, 1, 0, 0}}; auto const ret2 = collect_set( col, cudf::make_collect_set_aggregation<cudf::reduce_aggregation>( cudf::null_policy::INCLUDE, cudf::null_equality::UNEQUAL, cudf::nan_equality::UNEQUAL)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected2, dynamic_cast<cudf::list_scalar*>(ret2.get())->view()); // nan equal with null equal fp_wrapper expected3{{-2.3e-5f, 1.0f, 2.3e5f, NAN, 0.0f}, {1, 1, 1, 1, 0}}; auto const ret3 = collect_set( col, cudf::make_collect_set_aggregation<cudf::reduce_aggregation>( cudf::null_policy::INCLUDE, cudf::null_equality::EQUAL, cudf::nan_equality::ALL_EQUAL)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected3, dynamic_cast<cudf::list_scalar*>(ret3.get())->view()); // nan equal with null unequal fp_wrapper expected4{{-2.3e-5f, 1.0f, 2.3e5f, -NAN, 0.0f, 0.0f}, {1, 1, 1, 1, 0, 0}}; auto const ret4 = collect_set( col, cudf::make_collect_set_aggregation<cudf::reduce_aggregation>( cudf::null_policy::INCLUDE, cudf::null_equality::UNEQUAL, cudf::nan_equality::ALL_EQUAL)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected4, dynamic_cast<cudf::list_scalar*>(ret4.get())->view()); } TEST_F(CollectTest, MergeSetsWithNaN) { using fp_wrapper = cudf::test::fixed_width_column_wrapper<float>; using lists_col = cudf::test::lists_column_wrapper<float>; auto const col = lists_col{ lists_col{1.0f, -2.3e-5f, NAN}, lists_col{}, lists_col{{-2.3e-5f, 2.3e5f, NAN, 0.0f}, cudf::test::iterators::nulls_at({3})}, lists_col{{0.0f, 0.0f}, cudf::test::iterators::all_nulls()}, lists_col{-NAN}, }; // nan unequal with null equal fp_wrapper expected1{{-2.3e-5f, 1.0f, 2.3e5f, -NAN, NAN, NAN, 0.0f}, {1, 1, 1, 1, 1, 1, 0}}; auto const ret1 = collect_set(col, cudf::make_merge_sets_aggregation<cudf::reduce_aggregation>( cudf::null_equality::EQUAL, cudf::nan_equality::UNEQUAL)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected1, dynamic_cast<cudf::list_scalar*>(ret1.get())->view()); // nan unequal with null unequal fp_wrapper expected2{{-2.3e-5f, 1.0f, 2.3e5f, -NAN, NAN, NAN, 0.0f, 0.0f, 0.0f}, {1, 1, 1, 1, 1, 1, 0, 0, 0}}; auto const ret2 = collect_set(col, cudf::make_merge_sets_aggregation<cudf::reduce_aggregation>( cudf::null_equality::UNEQUAL, cudf::nan_equality::UNEQUAL)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected2, dynamic_cast<cudf::list_scalar*>(ret2.get())->view()); // nan equal with null equal fp_wrapper expected3{{-2.3e-5f, 1.0f, 2.3e5f, -NAN, 0.0f}, {1, 1, 1, 1, 0}}; auto const ret3 = collect_set(col, cudf::make_merge_sets_aggregation<cudf::reduce_aggregation>( cudf::null_equality::EQUAL, cudf::nan_equality::ALL_EQUAL)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected3, dynamic_cast<cudf::list_scalar*>(ret3.get())->view()); // nan equal with null unequal fp_wrapper expected4{{-2.3e-5f, 1.0f, 2.3e5f, -NAN, 0.0f, 0.0f, 0.0f}, {1, 1, 1, 1, 0, 0, 0}}; auto const ret4 = collect_set(col, cudf::make_merge_sets_aggregation<cudf::reduce_aggregation>( cudf::null_equality::UNEQUAL, cudf::nan_equality::ALL_EQUAL)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected4, dynamic_cast<cudf::list_scalar*>(ret4.get())->view()); } TEST_F(CollectTest, CollectStrings) { using str_col = cudf::test::strings_column_wrapper; using lists_col = cudf::test::lists_column_wrapper<cudf::string_view>; auto const s_col = str_col{{"a", "a", "b", "b", "b", "c", "c", "d", "e", "e"}, {1, 1, 1, 0, 1, 1, 0, 1, 1, 1}}; // collect_list including nulls auto const ret1 = cudf::reduce(s_col, *cudf::make_collect_list_aggregation<cudf::reduce_aggregation>(), cudf::data_type{cudf::type_id::LIST}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(s_col, dynamic_cast<cudf::list_scalar*>(ret1.get())->view()); // collect_list excluding nulls auto const expected2 = str_col{"a", "a", "b", "b", "c", "d", "e", "e"}; auto const ret2 = cudf::reduce( s_col, *cudf::make_collect_list_aggregation<cudf::reduce_aggregation>(cudf::null_policy::EXCLUDE), cudf::data_type{cudf::type_id::LIST}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected2, dynamic_cast<cudf::list_scalar*>(ret2.get())->view()); // collect_set with null_equal auto const expected3 = str_col{{"a", "b", "c", "d", "e", ""}, cudf::test::iterators::null_at(5)}; auto const ret3 = collect_set(s_col, cudf::make_collect_set_aggregation<cudf::reduce_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected3, dynamic_cast<cudf::list_scalar*>(ret3.get())->view()); // collect_set with null_unequal auto const expected4 = str_col{{"a", "b", "c", "d", "e", "", ""}, {1, 1, 1, 1, 1, 0, 0}}; auto const ret4 = collect_set(s_col, cudf::make_collect_set_aggregation<cudf::reduce_aggregation>( cudf::null_policy::INCLUDE, cudf::null_equality::UNEQUAL)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected4, dynamic_cast<cudf::list_scalar*>(ret4.get())->view()); lists_col strings{{"a"}, {}, {"a", "b"}, lists_col{{"b", "null", "c"}, cudf::test::iterators::null_at(1)}, lists_col{{"null", "d"}, cudf::test::iterators::null_at(0)}, lists_col{{"null"}, cudf::test::iterators::null_at(0)}, {"e"}}; // merge_lists auto const expected5 = str_col{{"a", "a", "b", "b", "null", "c", "null", "d", "null", "e"}, {1, 1, 1, 1, 0, 1, 0, 1, 0, 1}}; auto const ret5 = cudf::reduce(strings, *cudf::make_merge_lists_aggregation<cudf::reduce_aggregation>(), cudf::data_type{cudf::type_id::LIST}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected5, dynamic_cast<cudf::list_scalar*>(ret5.get())->view()); // merge_sets with null_equal auto const expected6 = str_col{{"a", "b", "c", "d", "e", "null"}, {1, 1, 1, 1, 1, 0}}; auto const ret6 = collect_set(strings, cudf::make_merge_sets_aggregation<cudf::reduce_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected6, dynamic_cast<cudf::list_scalar*>(ret6.get())->view()); // merge_sets with null_unequal auto const expected7 = str_col{{"a", "b", "c", "d", "e", "null", "null", "null"}, {1, 1, 1, 1, 1, 0, 0, 0}}; auto const ret7 = collect_set( strings, cudf::make_merge_sets_aggregation<cudf::reduce_aggregation>(cudf::null_equality::UNEQUAL)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected7, dynamic_cast<cudf::list_scalar*>(ret7.get())->view()); } TEST_F(CollectTest, CollectEmptys) { using int_col = cudf::test::fixed_width_column_wrapper<int32_t>; // test collect empty columns auto empty = int_col{}; auto ret = cudf::reduce(empty, *cudf::make_collect_list_aggregation<cudf::reduce_aggregation>(), cudf::data_type{cudf::type_id::LIST}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(int_col{}, dynamic_cast<cudf::list_scalar*>(ret.get())->view()); ret = collect_set(empty, cudf::make_collect_set_aggregation<cudf::reduce_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(int_col{}, dynamic_cast<cudf::list_scalar*>(ret.get())->view()); // test collect all null columns auto all_nulls = int_col{{1, 2, 3, 4, 5}, {0, 0, 0, 0, 0}}; ret = cudf::reduce(all_nulls, *cudf::make_collect_list_aggregation<cudf::reduce_aggregation>(), cudf::data_type{cudf::type_id::LIST}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(int_col{}, dynamic_cast<cudf::list_scalar*>(ret.get())->view()); ret = collect_set(all_nulls, cudf::make_collect_set_aggregation<cudf::reduce_aggregation>()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(int_col{}, dynamic_cast<cudf::list_scalar*>(ret.get())->view()); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/reductions/reduction_tests.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/copying.hpp> #include <cudf/detail/aggregation/aggregation.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/dictionary/encode.hpp> #include <cudf/fixed_point/fixed_point.hpp> #include <cudf/reduction.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/scalar/scalar_factories.hpp> #include <cudf/sorting.hpp> #include <cudf/types.hpp> #include <cudf/wrappers/timestamps.hpp> #include <thrust/iterator/counting_iterator.h> #include <iostream> #include <vector> using aggregation = cudf::aggregation; using reduce_aggregation = cudf::reduce_aggregation; template <typename T> auto convert_int(int value) { if (std::is_unsigned_v<T>) value = std::abs(value); if constexpr (cudf::is_timestamp_t<T>::value) { return T{typename T::duration(value)}; } else { return static_cast<T>(value); } } template <typename T> auto convert_values(std::vector<int> const& int_values) { std::vector<T> v(int_values.size()); std::transform( int_values.begin(), int_values.end(), v.begin(), [](int x) { return convert_int<T>(x); }); return v; } template <typename T> cudf::test::fixed_width_column_wrapper<T> construct_null_column(std::vector<T> const& values, std::vector<bool> const& bools) { if (values.size() > bools.size()) { throw std::logic_error("input vector size mismatch."); } return cudf::test::fixed_width_column_wrapper<T>(values.begin(), values.end(), bools.begin()); } template <typename T> std::vector<T> replace_nulls(std::vector<T> const& values, std::vector<bool> const& bools, T identity) { std::vector<T> v(values.size()); std::transform(values.begin(), values.end(), bools.begin(), v.begin(), [identity](T x, bool b) { return (b) ? x : identity; }); return v; } // ------------------------------------------------------------------------ // This is the main test feature template <typename T> struct ReductionTest : public cudf::test::BaseFixture { // Sum/Prod/SumOfSquare never support non arithmetics static constexpr bool ret_non_arithmetic = (std::is_arithmetic_v<T> || std::is_same_v<T, bool>); ReductionTest() {} ~ReductionTest() {} template <typename T_out> std::pair<T_out, bool> reduction_test(cudf::column_view const& underlying_column, reduce_aggregation const& agg, std::optional<cudf::data_type> _output_dtype = {}) { auto const output_dtype = _output_dtype.value_or(underlying_column.type()); std::unique_ptr<cudf::scalar> reduction = cudf::reduce(underlying_column, agg, output_dtype); using ScalarType = cudf::scalar_type_t<T_out>; auto result = static_cast<ScalarType*>(reduction.get()); return {result->value(), result->is_valid()}; } // Test with initial value template <typename T_out> std::pair<T_out, bool> reduction_test(cudf::column_view const& underlying_column, cudf::scalar const& initial_value, reduce_aggregation const& agg, std::optional<cudf::data_type> _output_dtype = {}) { auto const output_dtype = _output_dtype.value_or(underlying_column.type()); std::unique_ptr<cudf::scalar> reduction = cudf::reduce(underlying_column, agg, output_dtype, initial_value); using ScalarType = cudf::scalar_type_t<T_out>; auto result = static_cast<ScalarType*>(reduction.get()); return {result->value(), result->is_valid()}; } }; template <typename T> struct MinMaxReductionTest : public ReductionTest<T> {}; using MinMaxTypes = cudf::test::Types<int16_t, int32_t, float, double>; TYPED_TEST_SUITE(MinMaxReductionTest, MinMaxTypes); // ------------------------------------------------------------------------ TYPED_TEST(MinMaxReductionTest, MinMaxTypes) { using T = TypeParam; std::vector<int> int_values({5, 0, -120, -111, 0, 64, 63, 99, 123, -16}); std::vector<bool> host_bools({1, 1, 0, 1, 1, 1, 0, 1, 0, 1}); std::vector<bool> all_null({0, 0, 0, 0, 0, 0, 0, 0, 0, 0}); std::vector<T> v = convert_values<T>(int_values); T init_value = convert_int<T>(100); auto const init_scalar = cudf::make_fixed_width_scalar<T>(init_value); // Min/Max succeeds for any gdf types including // non-arithmetic types (date32, date64, timestamp, category) // test without nulls cudf::test::fixed_width_column_wrapper<T> col(v.begin(), v.end()); T expected_min_result = *(std::min_element(v.begin(), v.end())); T expected_max_result = *(std::max_element(v.begin(), v.end())); T expected_min_init_result = std::accumulate( v.begin(), v.end(), init_value, [](T const& a, T const& b) { return std::min<T>(a, b); }); T expected_max_init_result = std::accumulate( v.begin(), v.end(), init_value, [](T const& a, T const& b) { return std::max<T>(a, b); }); EXPECT_EQ( this->template reduction_test<T>(col, *cudf::make_min_aggregation<reduce_aggregation>()).first, expected_min_result); EXPECT_EQ( this->template reduction_test<T>(col, *cudf::make_max_aggregation<reduce_aggregation>()).first, expected_max_result); EXPECT_EQ(this ->template reduction_test<T>( col, *init_scalar, *cudf::make_min_aggregation<reduce_aggregation>()) .first, expected_min_init_result); EXPECT_EQ(this ->template reduction_test<T>( col, *init_scalar, *cudf::make_max_aggregation<reduce_aggregation>()) .first, expected_max_init_result); auto res = cudf::minmax(col); using ScalarType = cudf::scalar_type_t<T>; auto min_result = static_cast<ScalarType*>(res.first.get()); auto max_result = static_cast<ScalarType*>(res.second.get()); EXPECT_EQ(T{min_result->value()}, expected_min_result); EXPECT_EQ(T{max_result->value()}, expected_max_result); // test with some nulls cudf::test::fixed_width_column_wrapper<T> col_nulls = construct_null_column(v, host_bools); auto r_min = replace_nulls(v, host_bools, std::numeric_limits<T>::max()); auto r_max = replace_nulls(v, host_bools, std::numeric_limits<T>::lowest()); T expected_min_null_result = *(std::min_element(r_min.begin(), r_min.end())); T expected_max_null_result = *(std::max_element(r_max.begin(), r_max.end())); T expected_min_init_null_result = std::accumulate(r_min.begin(), r_min.end(), init_value, [](T const& a, T const& b) { return std::min<T>(a, b); }); T expected_max_init_null_result = std::accumulate(r_max.begin(), r_max.end(), init_value, [](T const& a, T const& b) { return std::max<T>(a, b); }); EXPECT_EQ( this->template reduction_test<T>(col_nulls, *cudf::make_min_aggregation<reduce_aggregation>()) .first, expected_min_null_result); EXPECT_EQ( this->template reduction_test<T>(col_nulls, *cudf::make_max_aggregation<reduce_aggregation>()) .first, expected_max_null_result); EXPECT_EQ(this ->template reduction_test<T>( col_nulls, *init_scalar, *cudf::make_min_aggregation<reduce_aggregation>()) .first, expected_min_init_null_result); EXPECT_EQ(this ->template reduction_test<T>( col_nulls, *init_scalar, *cudf::make_max_aggregation<reduce_aggregation>()) .first, expected_max_init_null_result); auto null_res = cudf::minmax(col_nulls); using ScalarType = cudf::scalar_type_t<T>; auto min_null_result = static_cast<ScalarType*>(null_res.first.get()); auto max_null_result = static_cast<ScalarType*>(null_res.second.get()); EXPECT_EQ(T{min_null_result->value()}, expected_min_null_result); EXPECT_EQ(T{max_null_result->value()}, expected_max_null_result); // test with all null cudf::test::fixed_width_column_wrapper<T> col_all_nulls = construct_null_column(v, all_null); init_scalar->set_valid_async(false); EXPECT_FALSE( this ->template reduction_test<T>(col_all_nulls, *cudf::make_min_aggregation<reduce_aggregation>()) .second); EXPECT_FALSE( this ->template reduction_test<T>(col_all_nulls, *cudf::make_max_aggregation<reduce_aggregation>()) .second); EXPECT_FALSE(this ->template reduction_test<T>( col_all_nulls, *init_scalar, *cudf::make_min_aggregation<reduce_aggregation>()) .second); EXPECT_FALSE(this ->template reduction_test<T>( col_all_nulls, *init_scalar, *cudf::make_max_aggregation<reduce_aggregation>()) .second); auto all_null_res = cudf::minmax(col_all_nulls); using ScalarType = cudf::scalar_type_t<T>; auto min_all_null_result = static_cast<ScalarType*>(all_null_res.first.get()); auto max_all_null_result = static_cast<ScalarType*>(all_null_res.second.get()); EXPECT_EQ(min_all_null_result->is_valid(), false); EXPECT_EQ(max_all_null_result->is_valid(), false); } template <typename T> struct SumReductionTest : public ReductionTest<T> {}; using SumTypes = cudf::test::Types<int16_t, int32_t, float, double>; TYPED_TEST_SUITE(SumReductionTest, SumTypes); TYPED_TEST(SumReductionTest, Sum) { using T = TypeParam; std::vector<int> int_values({6, -14, 13, 64, 0, -13, -20, 45}); std::vector<bool> host_bools({1, 1, 0, 0, 1, 1, 1, 1}); std::vector<T> v = convert_values<T>(int_values); T init_value = convert_int<T>(100); auto const init_scalar = cudf::make_fixed_width_scalar<T>(init_value); // test without nulls cudf::test::fixed_width_column_wrapper<T> col(v.begin(), v.end()); T expected_value = std::accumulate(v.begin(), v.end(), T{0}); T expected_value_init = std::accumulate(v.begin(), v.end(), init_value); EXPECT_EQ( this->template reduction_test<T>(col, *cudf::make_sum_aggregation<reduce_aggregation>()).first, expected_value); EXPECT_EQ(this ->template reduction_test<T>( col, *init_scalar, *cudf::make_sum_aggregation<reduce_aggregation>()) .first, expected_value_init); // test with nulls cudf::test::fixed_width_column_wrapper<T> col_nulls = construct_null_column(v, host_bools); auto r = replace_nulls(v, host_bools, T{0}); T expected_null_value = std::accumulate(r.begin(), r.end(), T{0}); init_scalar->set_valid_async(false); EXPECT_EQ( this->template reduction_test<T>(col_nulls, *cudf::make_sum_aggregation<reduce_aggregation>()) .first, expected_null_value); EXPECT_FALSE(this ->template reduction_test<T>( col_nulls, *init_scalar, *cudf::make_sum_aggregation<reduce_aggregation>()) .second); } TYPED_TEST_SUITE(ReductionTest, cudf::test::NumericTypes); TYPED_TEST(ReductionTest, Product) { using T = TypeParam; std::vector<int> int_values({5, -1, 1, 0, 3, 2, 4}); std::vector<bool> host_bools({1, 1, 0, 0, 1, 1, 1}); std::vector<TypeParam> v = convert_values<TypeParam>(int_values); T init_value = convert_int<T>(4); auto const init_scalar = cudf::make_fixed_width_scalar<T>(init_value); auto calc_prod = [](std::vector<T>& v) { T expected_value = std::accumulate(v.begin(), v.end(), T{1}, std::multiplies<T>()); return expected_value; }; auto calc_prod_init = [](std::vector<T>& v, T init) { T expected_value = std::accumulate(v.begin(), v.end(), init, std::multiplies<T>()); return expected_value; }; // test without nulls cudf::test::fixed_width_column_wrapper<T> col(v.begin(), v.end()); TypeParam expected_value = calc_prod(v); TypeParam expected_value_init = calc_prod_init(v, init_value); EXPECT_EQ( this->template reduction_test<T>(col, *cudf::make_product_aggregation<reduce_aggregation>()) .first, expected_value); EXPECT_EQ(this ->template reduction_test<T>( col, *init_scalar, *cudf::make_product_aggregation<reduce_aggregation>()) .first, expected_value_init); // test with nulls cudf::test::fixed_width_column_wrapper<T> col_nulls = construct_null_column(v, host_bools); auto r = replace_nulls(v, host_bools, T{1}); TypeParam expected_null_value = calc_prod(r); init_scalar->set_valid_async(false); EXPECT_EQ( this ->template reduction_test<T>(col_nulls, *cudf::make_product_aggregation<reduce_aggregation>()) .first, expected_null_value); EXPECT_FALSE(this ->template reduction_test<T>( col_nulls, *init_scalar, *cudf::make_product_aggregation<reduce_aggregation>()) .second); } TYPED_TEST(ReductionTest, SumOfSquare) { using T = TypeParam; std::vector<int> int_values({-3, 2, 1, 0, 5, -3, -2}); std::vector<bool> host_bools({1, 1, 0, 0, 1, 1, 1, 1}); std::vector<T> v = convert_values<T>(int_values); auto calc_reduction = [](std::vector<T>& v) { T value = std::accumulate(v.begin(), v.end(), T{0}, [](T acc, T i) { return acc + i * i; }); return value; }; // test without nulls cudf::test::fixed_width_column_wrapper<T> col(v.begin(), v.end()); T expected_value = calc_reduction(v); EXPECT_EQ(this ->template reduction_test<T>( col, *cudf::make_sum_of_squares_aggregation<reduce_aggregation>()) .first, expected_value); // test with nulls cudf::test::fixed_width_column_wrapper<T> col_nulls = construct_null_column(v, host_bools); auto r = replace_nulls(v, host_bools, T{0}); T expected_null_value = calc_reduction(r); EXPECT_EQ(this ->template reduction_test<T>( col_nulls, *cudf::make_sum_of_squares_aggregation<reduce_aggregation>()) .first, expected_null_value); } auto histogram_reduction(cudf::column_view const& input, std::unique_ptr<cudf::reduce_aggregation> const& agg) { CUDF_EXPECTS( agg->kind == cudf::aggregation::HISTOGRAM || agg->kind == cudf::aggregation::MERGE_HISTOGRAM, "Aggregation must be either HISTOGRAM or MERGE_HISTOGRAM."); auto const result_scalar = cudf::reduce(input, *agg, cudf::data_type{cudf::type_id::INT64}); EXPECT_EQ(result_scalar->is_valid(), true); auto const result_list_scalar = dynamic_cast<cudf::list_scalar*>(result_scalar.get()); EXPECT_NE(result_list_scalar, nullptr); auto const histogram = result_list_scalar->view(); EXPECT_EQ(histogram.num_children(), 2); EXPECT_EQ(histogram.null_count(), 0); EXPECT_EQ(histogram.child(1).null_count(), 0); // Sort the histogram based on the first column (unique input values). auto const sort_order = cudf::sorted_order(cudf::table_view{{histogram.child(0)}}, {}, {}); return std::move(cudf::gather(cudf::table_view{{histogram}}, *sort_order)->release().front()); } template <typename T> struct ReductionHistogramTest : public cudf::test::BaseFixture {}; // Avoid unsigned types, as the tests below have negative values in their input. using HistogramTestTypes = cudf::test::Concat<cudf::test::Types<int8_t, int16_t, int32_t, int64_t>, cudf::test::FloatingPointTypes, cudf::test::FixedPointTypes, cudf::test::ChronoTypes>; TYPED_TEST_SUITE(ReductionHistogramTest, HistogramTestTypes); TYPED_TEST(ReductionHistogramTest, Histogram) { using data_col = cudf::test::fixed_width_column_wrapper<TypeParam, int>; using int64_col = cudf::test::fixed_width_column_wrapper<int64_t>; using structs_col = cudf::test::structs_column_wrapper; auto const agg = cudf::make_histogram_aggregation<reduce_aggregation>(); // Empty input. { auto const input = data_col{}; auto const expected = [] { auto child1 = data_col{}; auto child2 = int64_col{}; return structs_col{{child1, child2}}; }(); auto const result = histogram_reduction(input, agg); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result); } { auto const input = data_col{-3, 2, 1, 2, 0, 5, 2, -3, -2, 2, 1}; auto const expected = [] { auto child1 = data_col{-3, -2, 0, 1, 2, 5}; auto child2 = int64_col{2, 1, 1, 2, 4, 1}; return structs_col{{child1, child2}}; }(); auto const result = histogram_reduction(input, agg); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result); } // Test without nulls, sliced input. { auto const input_original = data_col{-3, 2, 1, 2, 0, 5, 2, -3, -2, 2, 1}; auto const input = cudf::slice(input_original, {0, 7})[0]; auto const expected = [] { auto child1 = data_col{-3, 0, 1, 2, 5}; auto child2 = int64_col{1, 1, 1, 3, 1}; return structs_col{{child1, child2}}; }(); auto const result = histogram_reduction(input, agg); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result); } // Test with nulls. using namespace cudf::test::iterators; auto constexpr null{0}; { auto const input = data_col{{null, -3, 2, 1, 2, 0, null, 5, 2, null, -3, -2, null, 2, 1}, nulls_at({0, 6, 9, 12})}; auto const expected = [] { auto child1 = data_col{{null, -3, -2, 0, 1, 2, 5}, null_at(0)}; auto child2 = int64_col{4, 2, 1, 1, 2, 4, 1}; return structs_col{{child1, child2}}; }(); auto const result = histogram_reduction(input, agg); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result); } // Test with nulls, sliced input. { auto const input_original = data_col{ {null, -3, 2, 1, 2, 0, null, 5, 2, null, -3, -2, null, 2, 1}, nulls_at({0, 6, 9, 12})}; auto const input = cudf::slice(input_original, {0, 9})[0]; auto const expected = [] { auto child1 = data_col{{null, -3, 0, 1, 2, 5}, null_at(0)}; auto child2 = int64_col{2, 1, 1, 1, 3, 1}; return structs_col{{child1, child2}}; }(); auto const result = histogram_reduction(input, agg); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result); } } TYPED_TEST(ReductionHistogramTest, MergeHistogram) { using data_col = cudf::test::fixed_width_column_wrapper<TypeParam>; using int64_col = cudf::test::fixed_width_column_wrapper<int64_t>; using structs_col = cudf::test::structs_column_wrapper; auto const agg = cudf::make_merge_histogram_aggregation<reduce_aggregation>(); // Empty input. { auto const input = [] { auto child1 = data_col{}; auto child2 = int64_col{}; return structs_col{{child1, child2}}; }(); auto const expected = [] { auto child1 = data_col{}; auto child2 = int64_col{}; return structs_col{{child1, child2}}; }(); auto const result = histogram_reduction(input, agg); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result); } // Test without nulls. { auto const input = [] { auto child1 = data_col{-3, 2, 1, 2, 0, 5, 2, -3, -2, 2, 1}; auto child2 = int64_col{2, 1, 1, 2, 4, 1, 2, 3, 5, 3, 4}; return structs_col{{child1, child2}}; }(); auto const expected = [] { auto child1 = data_col{-3, -2, 0, 1, 2, 5}; auto child2 = int64_col{5, 5, 4, 5, 8, 1}; return structs_col{{child1, child2}}; }(); auto const result = histogram_reduction(input, agg); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result); } // Test without nulls, sliced input. { auto const input_original = [] { auto child1 = data_col{-3, 2, 1, 2, 0, 5, 2, -3, -2, 2, 1}; auto child2 = int64_col{2, 1, 1, 2, 4, 1, 2, 3, 5, 3, 4}; return structs_col{{child1, child2}}; }(); auto const input = cudf::slice(input_original, {0, 7})[0]; auto const expected = [] { auto child1 = data_col{-3, 0, 1, 2, 5}; auto child2 = int64_col{2, 4, 1, 5, 1}; return structs_col{{child1, child2}}; }(); auto const result = histogram_reduction(input, agg); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result); } // Test with nulls. using namespace cudf::test::iterators; auto constexpr null{0}; { auto const input = [] { auto child1 = data_col{{-3, 2, null, 1, 2, null, 0, 5, null, 2, -3, null, -2, 2, 1, null}, nulls_at({2, 5, 8, 11, 15})}; auto child2 = int64_col{2, 1, 12, 1, 2, 11, 4, 1, 10, 2, 3, 15, 5, 3, 4, 19}; return structs_col{{child1, child2}}; }(); auto const expected = [] { auto child1 = data_col{{null, -3, -2, 0, 1, 2, 5}, null_at(0)}; auto child2 = int64_col{67, 5, 5, 4, 5, 8, 1}; return structs_col{{child1, child2}}; }(); auto const result = histogram_reduction(input, agg); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result); } // Test with nulls, sliced input. { auto const input_original = [] { auto child1 = data_col{{-3, 2, null, 1, 2, null, 0, 5, null, 2, -3, null, -2, 2, 1, null}, nulls_at({2, 5, 8, 11, 15})}; auto child2 = int64_col{2, 1, 12, 1, 2, 11, 4, 1, 10, 2, 3, 15, 5, 3, 4, 19}; return structs_col{{child1, child2}}; }(); auto const input = cudf::slice(input_original, {0, 9})[0]; auto const expected = [] { auto child1 = data_col{{null, -3, 0, 1, 2, 5}, null_at(0)}; auto child2 = int64_col{33, 2, 4, 1, 3, 1}; return structs_col{{child1, child2}}; }(); auto const result = histogram_reduction(input, agg); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, *result); } } template <typename T> struct ReductionAnyAllTest : public ReductionTest<bool> {}; using AnyAllTypes = cudf::test::Types<int32_t, float, bool>; TYPED_TEST_SUITE(ReductionAnyAllTest, AnyAllTypes); TYPED_TEST(ReductionAnyAllTest, AnyAllTrueTrue) { using T = TypeParam; std::vector<int> int_values({true, true, true, true}); std::vector<bool> host_bools({1, 1, 0, 1}); std::vector<T> v = convert_values<T>(int_values); auto const init_scalar = cudf::make_fixed_width_scalar<T>(convert_int<T>(true)); // Min/Max succeeds for any gdf types including // non-arithmetic types (date32, date64, timestamp, category) bool expected = true; cudf::data_type output_dtype(cudf::type_id::BOOL8); // test without nulls cudf::test::fixed_width_column_wrapper<T> col(v.begin(), v.end()); EXPECT_EQ(this ->template reduction_test<bool>( col, *cudf::make_any_aggregation<reduce_aggregation>(), output_dtype) .first, expected); EXPECT_EQ(this ->template reduction_test<bool>( col, *cudf::make_all_aggregation<reduce_aggregation>(), output_dtype) .first, expected); EXPECT_EQ(this ->template reduction_test<bool>( col, *init_scalar, *cudf::make_any_aggregation<reduce_aggregation>(), output_dtype) .first, expected); EXPECT_EQ(this ->template reduction_test<bool>( col, *init_scalar, *cudf::make_all_aggregation<reduce_aggregation>(), output_dtype) .first, expected); // test with nulls cudf::test::fixed_width_column_wrapper<T> col_nulls = construct_null_column(v, host_bools); init_scalar->set_valid_async(false); EXPECT_EQ(this ->template reduction_test<bool>( col_nulls, *cudf::make_any_aggregation<reduce_aggregation>(), output_dtype) .first, expected); EXPECT_EQ(this ->template reduction_test<bool>( col_nulls, *cudf::make_all_aggregation<reduce_aggregation>(), output_dtype) .first, expected); EXPECT_FALSE( this ->template reduction_test<bool>( col_nulls, *init_scalar, *cudf::make_any_aggregation<reduce_aggregation>(), output_dtype) .second); EXPECT_FALSE( this ->template reduction_test<bool>( col_nulls, *init_scalar, *cudf::make_all_aggregation<reduce_aggregation>(), output_dtype) .second); } TYPED_TEST(ReductionAnyAllTest, AnyAllFalseFalse) { using T = TypeParam; std::vector<int> int_values({false, false, false, false}); std::vector<bool> host_bools({1, 1, 0, 1}); std::vector<T> v = convert_values<T>(int_values); auto const init_scalar = cudf::make_fixed_width_scalar<T>(convert_int<T>(false)); // Min/Max succeeds for any gdf types including // non-arithmetic types (date32, date64, timestamp, category) bool expected = false; cudf::data_type output_dtype(cudf::type_id::BOOL8); // test without nulls cudf::test::fixed_width_column_wrapper<T> col(v.begin(), v.end()); EXPECT_EQ(this ->template reduction_test<bool>( col, *cudf::make_any_aggregation<reduce_aggregation>(), output_dtype) .first, expected); EXPECT_EQ(this ->template reduction_test<bool>( col, *cudf::make_all_aggregation<reduce_aggregation>(), output_dtype) .first, expected); EXPECT_EQ(this ->template reduction_test<bool>( col, *init_scalar, *cudf::make_any_aggregation<reduce_aggregation>(), output_dtype) .first, expected); EXPECT_EQ(this ->template reduction_test<bool>( col, *init_scalar, *cudf::make_all_aggregation<reduce_aggregation>(), output_dtype) .first, expected); // test with nulls cudf::test::fixed_width_column_wrapper<T> col_nulls = construct_null_column(v, host_bools); init_scalar->set_valid_async(false); EXPECT_EQ(this ->template reduction_test<bool>( col_nulls, *cudf::make_any_aggregation<reduce_aggregation>(), output_dtype) .first, expected); EXPECT_EQ(this ->template reduction_test<bool>( col_nulls, *cudf::make_all_aggregation<reduce_aggregation>(), output_dtype) .first, expected); EXPECT_FALSE( this ->template reduction_test<bool>( col_nulls, *init_scalar, *cudf::make_any_aggregation<reduce_aggregation>(), output_dtype) .second); EXPECT_FALSE( this ->template reduction_test<bool>( col_nulls, *init_scalar, *cudf::make_all_aggregation<reduce_aggregation>(), output_dtype) .second); } // ---------------------------------------------------------------------------- template <typename T> struct MultiStepReductionTest : public ReductionTest<T> {}; using MultiStepReductionTypes = cudf::test::Types<int16_t, int32_t, float, double>; TYPED_TEST_SUITE(MultiStepReductionTest, MultiStepReductionTypes); TYPED_TEST(MultiStepReductionTest, Mean) { using T = TypeParam; std::vector<int> int_values({-3, 2, 1, 0, 5, -3, -2, 28}); std::vector<bool> host_bools({1, 1, 0, 1, 1, 1, 0, 1}); auto calc_mean = [](std::vector<T>& v, cudf::size_type valid_count) { double sum = std::accumulate(v.begin(), v.end(), double{0}); return sum / valid_count; }; // test without nulls std::vector<T> v = convert_values<T>(int_values); cudf::test::fixed_width_column_wrapper<T> col(v.begin(), v.end()); double expected_value = calc_mean(v, v.size()); EXPECT_EQ(this ->template reduction_test<double>(col, *cudf::make_mean_aggregation<reduce_aggregation>(), cudf::data_type(cudf::type_id::FLOAT64)) .first, expected_value); // test with nulls cudf::test::fixed_width_column_wrapper<T> col_nulls = construct_null_column(v, host_bools); cudf::size_type valid_count = cudf::column_view(col_nulls).size() - cudf::column_view(col_nulls).null_count(); auto replaced_array = replace_nulls(v, host_bools, T{0}); double expected_value_nulls = calc_mean(replaced_array, valid_count); EXPECT_EQ(this ->template reduction_test<double>(col_nulls, *cudf::make_mean_aggregation<reduce_aggregation>(), cudf::data_type(cudf::type_id::FLOAT64)) .first, expected_value_nulls); } // This test is disabled for only a Debug build because a compiler error // documented in cpp/src/reductions/std.cu and cpp/src/reductions/var.cu #ifdef NDEBUG TYPED_TEST(MultiStepReductionTest, var_std) #else TYPED_TEST(MultiStepReductionTest, DISABLED_var_std) #endif { using T = TypeParam; std::vector<int> int_values({-3, 2, 1, 0, 5, -3, -2, 28}); std::vector<bool> host_bools({1, 1, 0, 1, 1, 1, 0, 1}); auto calc_var = [](std::vector<T>& v, cudf::size_type valid_count, int ddof) { double mean = std::accumulate(v.begin(), v.end(), double{0}); mean /= valid_count; double sum_of_sq = std::accumulate( v.begin(), v.end(), double{0}, [](double acc, TypeParam i) { return acc + i * i; }); cudf::size_type div = valid_count - ddof; double var = sum_of_sq / div - ((mean * mean) * valid_count) / div; return var; }; // test without nulls std::vector<T> v = convert_values<T>(int_values); cudf::test::fixed_width_column_wrapper<T> col(v.begin(), v.end()); auto const ddof = 1; double var = calc_var(v, v.size(), ddof); double std = std::sqrt(var); auto var_agg = cudf::make_variance_aggregation<reduce_aggregation>(ddof); auto std_agg = cudf::make_std_aggregation<reduce_aggregation>(ddof); EXPECT_EQ( this->template reduction_test<double>(col, *var_agg, cudf::data_type(cudf::type_id::FLOAT64)) .first, var); EXPECT_EQ( this->template reduction_test<double>(col, *std_agg, cudf::data_type(cudf::type_id::FLOAT64)) .first, std); // test with nulls cudf::test::fixed_width_column_wrapper<T> col_nulls = construct_null_column(v, host_bools); cudf::size_type valid_count = cudf::column_view(col_nulls).size() - cudf::column_view(col_nulls).null_count(); auto replaced_array = replace_nulls(v, host_bools, T{0}); double var_nulls = calc_var(replaced_array, valid_count, ddof); double std_nulls = std::sqrt(var_nulls); EXPECT_EQ(this ->template reduction_test<double>( col_nulls, *var_agg, cudf::data_type(cudf::type_id::FLOAT64)) .first, var_nulls); EXPECT_EQ(this ->template reduction_test<double>( col_nulls, *std_agg, cudf::data_type(cudf::type_id::FLOAT64)) .first, std_nulls); } // ---------------------------------------------------------------------------- template <typename T> struct ReductionMultiStepErrorCheck : public ReductionTest<T> { void reduction_error_check(cudf::test::fixed_width_column_wrapper<T>& col, bool succeeded_condition, reduce_aggregation const& agg, cudf::data_type output_dtype) { const cudf::column_view underlying_column = col; auto statement = [&]() { cudf::reduce(underlying_column, agg, output_dtype); }; if (succeeded_condition) { CUDF_EXPECT_NO_THROW(statement()); } else { EXPECT_ANY_THROW(statement()); } } }; TYPED_TEST_SUITE(ReductionMultiStepErrorCheck, cudf::test::AllTypes); // This test is disabled for only a Debug build because a compiler error // documented in cpp/src/reductions/std.cu and cpp/src/reductions/var.cu #ifdef NDEBUG TYPED_TEST(ReductionMultiStepErrorCheck, ErrorHandling) #else TYPED_TEST(ReductionMultiStepErrorCheck, DISABLED_ErrorHandling) #endif { using T = TypeParam; std::vector<int> int_values({-3, 2}); std::vector<bool> host_bools({1, 0}); std::vector<T> v = convert_values<T>(int_values); cudf::test::fixed_width_column_wrapper<T> col(v.begin(), v.end()); cudf::test::fixed_width_column_wrapper<T> col_nulls = construct_null_column(v, host_bools); bool is_input_acceptable = this->ret_non_arithmetic; std::vector<cudf::data_type> dtypes(static_cast<int32_t>(cudf::type_id::NUM_TYPE_IDS) + 1); int i = 0; std::generate(dtypes.begin(), dtypes.end(), [&]() { return cudf::data_type(static_cast<cudf::type_id>(i++)); }); auto is_supported_outdtype = [](cudf::data_type dtype) { if (dtype == cudf::data_type(cudf::type_id::FLOAT32)) return true; if (dtype == cudf::data_type(cudf::type_id::FLOAT64)) return true; return false; }; auto evaluate = [&](cudf::data_type dtype) mutable { bool expect_succeed = is_input_acceptable & is_supported_outdtype(dtype); auto const ddof = 1; auto var_agg = cudf::make_variance_aggregation<reduce_aggregation>(ddof); auto std_agg = cudf::make_std_aggregation<reduce_aggregation>(ddof); this->reduction_error_check( col, expect_succeed, *cudf::make_mean_aggregation<reduce_aggregation>(), dtype); this->reduction_error_check(col, expect_succeed, *var_agg, dtype); this->reduction_error_check(col, expect_succeed, *std_agg, dtype); this->reduction_error_check( col_nulls, expect_succeed, *cudf::make_mean_aggregation<reduce_aggregation>(), dtype); this->reduction_error_check(col_nulls, expect_succeed, *var_agg, dtype); this->reduction_error_check(col_nulls, expect_succeed, *std_agg, dtype); return; }; std::for_each(dtypes.begin(), dtypes.end(), evaluate); } // ---------------------------------------------------------------------------- struct ReductionDtypeTest : public cudf::test::BaseFixture { template <typename T_in, typename T_out> void reduction_test(std::vector<int>& int_values, T_out expected_value, bool succeeded_condition, reduce_aggregation const& agg, cudf::data_type out_dtype, bool expected_overflow = false) { std::vector<T_in> input_values = convert_values<T_in>(int_values); cudf::test::fixed_width_column_wrapper<T_in> const col(input_values.begin(), input_values.end()); auto statement = [&]() { std::unique_ptr<cudf::scalar> result = cudf::reduce(col, agg, out_dtype); using ScalarType = cudf::scalar_type_t<T_out>; auto result1 = static_cast<ScalarType*>(result.get()); if (result1->is_valid() && !expected_overflow) { EXPECT_EQ(expected_value, result1->value()); } }; if (succeeded_condition) { CUDF_EXPECT_NO_THROW(statement()); } else { EXPECT_ANY_THROW(statement()); } } }; TEST_F(ReductionDtypeTest, all_null_output) { auto sum_agg = cudf::make_sum_aggregation<reduce_aggregation>(); auto const col = cudf::test::fixed_point_column_wrapper<int32_t>{{0, 0, 0}, {0, 0, 0}, numeric::scale_type{-2}} .release(); std::unique_ptr<cudf::scalar> result = cudf::reduce(*col, *sum_agg, col->type()); EXPECT_EQ(result->is_valid(), false); EXPECT_EQ(result->type().id(), col->type().id()); EXPECT_EQ(result->type().scale(), col->type().scale()); } // test case for different output precision TEST_F(ReductionDtypeTest, different_precision) { constexpr bool expected_overflow = true; std::vector<int> int_values({6, -14, 13, 109, -13, -20, 0, 98, 122, 123}); int expected_value = std::accumulate(int_values.begin(), int_values.end(), 0); auto sum_agg = cudf::make_sum_aggregation<reduce_aggregation>(); // over flow this->reduction_test<int8_t, int8_t>(int_values, static_cast<int8_t>(expected_value), true, *sum_agg, cudf::data_type(cudf::type_id::INT8), expected_overflow); this->reduction_test<int8_t, int64_t>(int_values, static_cast<int64_t>(expected_value), true, *sum_agg, cudf::data_type(cudf::type_id::INT64)); this->reduction_test<int8_t, double>(int_values, static_cast<double>(expected_value), true, *sum_agg, cudf::data_type(cudf::type_id::FLOAT64)); // down cast (over flow) this->reduction_test<double, int8_t>(int_values, static_cast<int8_t>(expected_value), true, *sum_agg, cudf::data_type(cudf::type_id::INT8), expected_overflow); // down cast (no over flow) this->reduction_test<double, int16_t>(int_values, static_cast<int16_t>(expected_value), true, *sum_agg, cudf::data_type(cudf::type_id::INT16)); // not supported case: // wrapper classes other than bool are not convertible this->reduction_test<cudf::timestamp_D, cudf::timestamp_s>( int_values, cudf::timestamp_s{cudf::duration_s(expected_value)}, false, *sum_agg, cudf::data_type(cudf::type_id::TIMESTAMP_SECONDS)); this->reduction_test<cudf::timestamp_s, cudf::timestamp_ns>( int_values, cudf::timestamp_ns{cudf::duration_ns(expected_value)}, false, *sum_agg, cudf::data_type(cudf::type_id::TIMESTAMP_NANOSECONDS)); this->reduction_test<int8_t, cudf::timestamp_us>( int_values, cudf::timestamp_us{cudf::duration_us(expected_value)}, false, *sum_agg, cudf::data_type(cudf::type_id::TIMESTAMP_MICROSECONDS)); std::vector<bool> v = convert_values<bool>(int_values); // When summing bool values into an non-bool arithmetic type, // it's an integer/float sum of ones and zeros. int expected = std::accumulate(v.begin(), v.end(), int{0}); this->reduction_test<bool, int8_t>(int_values, static_cast<int8_t>(expected), true, *sum_agg, cudf::data_type(cudf::type_id::INT8)); this->reduction_test<bool, int16_t>(int_values, static_cast<int16_t>(expected), true, *sum_agg, cudf::data_type(cudf::type_id::INT16)); this->reduction_test<bool, int32_t>(int_values, static_cast<int32_t>(expected), true, *sum_agg, cudf::data_type(cudf::type_id::INT32)); this->reduction_test<bool, int64_t>(int_values, static_cast<int64_t>(expected), true, *sum_agg, cudf::data_type(cudf::type_id::INT64)); this->reduction_test<bool, float>(int_values, static_cast<float>(expected), true, *sum_agg, cudf::data_type(cudf::type_id::FLOAT32)); this->reduction_test<bool, double>(int_values, static_cast<double>(expected), true, *sum_agg, cudf::data_type(cudf::type_id::FLOAT64)); // make sure boolean arithmetic semantics are obeyed when reducing to a bool this->reduction_test<bool, bool>( int_values, true, true, *sum_agg, cudf::data_type(cudf::type_id::BOOL8)); this->reduction_test<int32_t, bool>( int_values, true, true, *sum_agg, cudf::data_type(cudf::type_id::BOOL8)); // cudf::timestamp_s and int64_t are not convertible types. this->reduction_test<cudf::timestamp_s, int64_t>(int_values, static_cast<int64_t>(expected_value), false, *sum_agg, cudf::data_type(cudf::type_id::INT64)); } struct ReductionEmptyTest : public cudf::test::BaseFixture {}; // test case for empty input cases TEST_F(ReductionEmptyTest, empty_column) { using T = int32_t; auto statement = [](cudf::column_view const& col) { std::unique_ptr<cudf::scalar> result = cudf::reduce(col, *cudf::make_sum_aggregation<reduce_aggregation>(), cudf::data_type(cudf::type_id::INT64)); EXPECT_EQ(result->is_valid(), false); }; // default column_view{} is an empty column // empty column_view CUDF_EXPECT_NO_THROW(statement(cudf::column_view{})); // test if the size of input column is zero // expect result.is_valid() is false std::vector<T> empty_data(0); cudf::test::fixed_width_column_wrapper<T> const col0(empty_data.begin(), empty_data.end()); CUDF_EXPECT_NO_THROW(statement(col0)); // test if null count is equal or greater than size of input // expect result.is_valid() is false int col_size = 5; std::vector<T> col_data(col_size); std::vector<bool> valids(col_size, 0); cudf::test::fixed_width_column_wrapper<T> col_nulls = construct_null_column(col_data, valids); CUDF_EXPECT_NO_THROW(statement(col_nulls)); auto any_agg = cudf::make_any_aggregation<cudf::reduce_aggregation>(); auto all_agg = cudf::make_all_aggregation<cudf::reduce_aggregation>(); auto bool_type = cudf::data_type{cudf::type_id::BOOL8}; auto result = cudf::reduce(col0, *any_agg, bool_type); EXPECT_EQ(result->is_valid(), true); EXPECT_EQ(dynamic_cast<cudf::numeric_scalar<bool>*>(result.get())->value(), false); result = cudf::reduce(col_nulls, *any_agg, bool_type); EXPECT_EQ(result->is_valid(), true); EXPECT_EQ(dynamic_cast<cudf::numeric_scalar<bool>*>(result.get())->value(), false); result = cudf::reduce(col0, *all_agg, bool_type); EXPECT_EQ(result->is_valid(), true); EXPECT_EQ(dynamic_cast<cudf::numeric_scalar<bool>*>(result.get())->value(), true); result = cudf::reduce(col_nulls, *all_agg, bool_type); EXPECT_EQ(result->is_valid(), true); EXPECT_EQ(dynamic_cast<cudf::numeric_scalar<bool>*>(result.get())->value(), true); } // ---------------------------------------------------------------------------- struct ReductionParamTest : public ReductionTest<double>, public ::testing::WithParamInterface<cudf::size_type> {}; INSTANTIATE_TEST_CASE_P(ddofParam, ReductionParamTest, ::testing::Range(1, 5)); // This test is disabled for only a Debug build because a compiler error // documented in cpp/src/reductions/std.cu and cpp/src/reductions/var.cu #ifdef NDEBUG TEST_P(ReductionParamTest, std_var) #else TEST_P(ReductionParamTest, DISABLED_std_var) #endif { int ddof = GetParam(); std::vector<double> int_values({-3, 2, 1, 0, 5, -3, -2, 28}); std::vector<bool> host_bools({1, 1, 0, 1, 1, 1, 0, 1}); auto calc_var = [ddof](std::vector<double>& v, cudf::size_type valid_count) { double mean = std::accumulate(v.begin(), v.end(), double{0}); mean /= valid_count; double sum_of_sq = std::accumulate( v.begin(), v.end(), double{0}, [](double acc, double i) { return acc + i * i; }); cudf::size_type div = valid_count - ddof; double var = sum_of_sq / div - ((mean * mean) * valid_count) / div; return var; }; // test without nulls cudf::test::fixed_width_column_wrapper<double> col(int_values.begin(), int_values.end()); double var = calc_var(int_values, int_values.size()); double std = std::sqrt(var); auto var_agg = cudf::make_variance_aggregation<reduce_aggregation>(ddof); auto std_agg = cudf::make_std_aggregation<reduce_aggregation>(ddof); EXPECT_EQ( this->template reduction_test<double>(col, *var_agg, cudf::data_type(cudf::type_id::FLOAT64)) .first, var); EXPECT_EQ( this->template reduction_test<double>(col, *std_agg, cudf::data_type(cudf::type_id::FLOAT64)) .first, std); // test with nulls cudf::test::fixed_width_column_wrapper<double> col_nulls = construct_null_column(int_values, host_bools); cudf::size_type valid_count = cudf::column_view(col_nulls).size() - cudf::column_view(col_nulls).null_count(); auto replaced_array = replace_nulls<double>(int_values, host_bools, int{0}); double var_nulls = calc_var(replaced_array, valid_count); double std_nulls = std::sqrt(var_nulls); EXPECT_EQ(this ->template reduction_test<double>( col_nulls, *var_agg, cudf::data_type(cudf::type_id::FLOAT64)) .first, var_nulls); EXPECT_EQ(this ->template reduction_test<double>( col_nulls, *std_agg, cudf::data_type(cudf::type_id::FLOAT64)) .first, std_nulls); } //------------------------------------------------------------------- struct StringReductionTest : public cudf::test::BaseFixture, public testing::WithParamInterface<std::vector<std::string>> { // Min/Max void reduction_test(cudf::column_view const& underlying_column, std::string expected_value, bool succeeded_condition, reduce_aggregation const& agg, cudf::data_type output_dtype = cudf::data_type{}) { if (cudf::data_type{} == output_dtype) output_dtype = underlying_column.type(); auto statement = [&]() { std::unique_ptr<cudf::scalar> result = cudf::reduce(underlying_column, agg, output_dtype); using ScalarType = cudf::scalar_type_t<cudf::string_view>; auto result1 = static_cast<ScalarType*>(result.get()); EXPECT_TRUE(result1->is_valid()); if (result1->is_valid()) { EXPECT_EQ(expected_value, result1->to_string()) << (agg.kind == aggregation::MIN ? "MIN" : "MAX"); } }; if (succeeded_condition) { CUDF_EXPECT_NO_THROW(statement()); } else { EXPECT_ANY_THROW(statement()); } } void reduction_test(cudf::column_view const& underlying_column, std::string initial_value, std::string expected_value, bool succeeded_condition, reduce_aggregation const& agg, cudf::data_type output_dtype = cudf::data_type{}) { if (cudf::data_type{} == output_dtype) output_dtype = underlying_column.type(); auto string_scalar = cudf::make_string_scalar(initial_value); auto statement = [&]() { std::unique_ptr<cudf::scalar> result = cudf::reduce(underlying_column, agg, output_dtype, *string_scalar); using ScalarType = cudf::scalar_type_t<cudf::string_view>; auto result1 = static_cast<ScalarType*>(result.get()); EXPECT_TRUE(result1->is_valid()); if (result1->is_valid()) { EXPECT_EQ(expected_value, result1->to_string()) << (agg.kind == aggregation::MIN ? "MIN" : "MAX"); } }; if (succeeded_condition) { CUDF_EXPECT_NO_THROW(statement()); } else { EXPECT_ANY_THROW(statement()); } } }; // ------------------------------------------------------------------------ std::vector<std::string> string_list[] = { {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}, {"", "two", "three", "four", "five", "six", "seven", "eight", "nine"}, {"one", "", "three", "four", "five", "six", "seven", "eight", "nine"}, {"", "", "", "four", "five", "six", "seven", "eight", "nine"}, {"", "", "", "", "", "", "", "", ""}, // DeviceMin identity sentinel test cases {"\xF7\xBF\xBF\xBF", "", "", "", "", "", "", "", ""}, {"one", "two", "three", "four", "\xF7\xBF\xBF\xBF", "six", "seven", "eight", "nine"}, {"one", "two", "\xF7\xBF\xBF\xBF", "four", "five", "six", "seven", "eight", "nine"}, }; INSTANTIATE_TEST_CASE_P(string_cases, StringReductionTest, testing::ValuesIn(string_list)); TEST_P(StringReductionTest, MinMax) { // data and valid arrays std::vector<std::string> host_strings(GetParam()); std::vector<bool> host_bools({1, 0, 1, 1, 1, 1, 0, 0, 1}); bool succeed(true); std::string initial_value = "init"; // all valid string column cudf::test::strings_column_wrapper col(host_strings.begin(), host_strings.end()); std::string expected_min_result = *(std::min_element(host_strings.begin(), host_strings.end())); std::string expected_max_result = *(std::max_element(host_strings.begin(), host_strings.end())); std::string expected_min_init_result = std::min(expected_min_result, initial_value); std::string expected_max_init_result = std::max(expected_max_result, initial_value); // string column with nulls cudf::test::strings_column_wrapper col_nulls( host_strings.begin(), host_strings.end(), host_bools.begin()); std::vector<std::string> r_strings; std::copy_if(host_strings.begin(), host_strings.end(), std::back_inserter(r_strings), [host_bools, i = 0](auto s) mutable { return host_bools[i++]; }); std::string expected_min_null_result = *(std::min_element(r_strings.begin(), r_strings.end())); std::string expected_max_null_result = *(std::max_element(r_strings.begin(), r_strings.end())); std::string expected_min_init_null_result = std::min(expected_min_null_result, initial_value); std::string expected_max_init_null_result = std::max(expected_max_null_result, initial_value); // MIN this->reduction_test( col, expected_min_result, succeed, *cudf::make_min_aggregation<reduce_aggregation>()); this->reduction_test(col_nulls, expected_min_null_result, succeed, *cudf::make_min_aggregation<reduce_aggregation>()); this->reduction_test(col, initial_value, expected_min_init_result, succeed, *cudf::make_min_aggregation<reduce_aggregation>()); this->reduction_test(col_nulls, initial_value, expected_min_init_null_result, succeed, *cudf::make_min_aggregation<reduce_aggregation>()); // MAX this->reduction_test( col, expected_max_result, succeed, *cudf::make_max_aggregation<reduce_aggregation>()); this->reduction_test(col_nulls, expected_max_null_result, succeed, *cudf::make_max_aggregation<reduce_aggregation>()); this->reduction_test(col, initial_value, expected_max_init_result, succeed, *cudf::make_max_aggregation<reduce_aggregation>()); this->reduction_test(col_nulls, initial_value, expected_max_init_null_result, succeed, *cudf::make_max_aggregation<reduce_aggregation>()); // MINMAX auto result = cudf::minmax(col); EXPECT_EQ(static_cast<cudf::string_scalar*>(result.first.get())->to_string(), expected_min_result); EXPECT_EQ(static_cast<cudf::string_scalar*>(result.second.get())->to_string(), expected_max_result); result = cudf::minmax(col_nulls); EXPECT_EQ(static_cast<cudf::string_scalar*>(result.first.get())->to_string(), expected_min_null_result); EXPECT_EQ(static_cast<cudf::string_scalar*>(result.second.get())->to_string(), expected_max_null_result); } TEST_P(StringReductionTest, DictionaryMinMax) { // data and valid arrays std::vector<std::string> host_strings(GetParam()); cudf::test::dictionary_column_wrapper<std::string> col(host_strings.begin(), host_strings.end()); std::string expected_min_result = *(std::min_element(host_strings.begin(), host_strings.end())); std::string expected_max_result = *(std::max_element(host_strings.begin(), host_strings.end())); auto result = cudf::minmax(col); EXPECT_EQ(static_cast<cudf::string_scalar*>(result.first.get())->to_string(), expected_min_result); EXPECT_EQ(static_cast<cudf::string_scalar*>(result.second.get())->to_string(), expected_max_result); // column with nulls std::vector<bool> validity({1, 0, 1, 1, 1, 1, 0, 0, 1}); cudf::test::dictionary_column_wrapper<std::string> col_nulls( host_strings.begin(), host_strings.end(), validity.begin()); std::vector<std::string> r_strings; std::copy_if(host_strings.begin(), host_strings.end(), std::back_inserter(r_strings), [validity, i = 0](auto s) mutable { return validity[i++]; }); expected_min_result = *(std::min_element(r_strings.begin(), r_strings.end())); expected_max_result = *(std::max_element(r_strings.begin(), r_strings.end())); result = cudf::minmax(col_nulls); EXPECT_EQ(static_cast<cudf::string_scalar*>(result.first.get())->to_string(), expected_min_result); EXPECT_EQ(static_cast<cudf::string_scalar*>(result.second.get())->to_string(), expected_max_result); // test sliced column result = cudf::minmax(cudf::slice(col_nulls, {3, 7}).front()); // 3->2 and 7->5 because r_strings contains no null entries expected_min_result = *(std::min_element(r_strings.begin() + 2, r_strings.begin() + 5)); expected_max_result = *(std::max_element(r_strings.begin() + 2, r_strings.begin() + 5)); EXPECT_EQ(static_cast<cudf::string_scalar*>(result.first.get())->to_string(), expected_min_result); EXPECT_EQ(static_cast<cudf::string_scalar*>(result.second.get())->to_string(), expected_max_result); } TEST_F(StringReductionTest, AllNull) { // data and all null arrays std::vector<std::string> host_strings( {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}); std::vector<bool> host_bools(host_strings.size(), false); auto initial_value = cudf::make_string_scalar("init"); initial_value->set_valid_async(false); // string column with nulls cudf::test::strings_column_wrapper col_nulls( host_strings.begin(), host_strings.end(), host_bools.begin()); cudf::data_type output_dtype = cudf::column_view(col_nulls).type(); // MIN auto result = cudf::reduce(col_nulls, *cudf::make_min_aggregation<reduce_aggregation>(), output_dtype); EXPECT_FALSE(result->is_valid()); result = cudf::reduce( col_nulls, *cudf::make_min_aggregation<reduce_aggregation>(), output_dtype, *initial_value); EXPECT_FALSE(result->is_valid()); // MAX result = cudf::reduce(col_nulls, *cudf::make_max_aggregation<reduce_aggregation>(), output_dtype); EXPECT_FALSE(result->is_valid()); result = cudf::reduce( col_nulls, *cudf::make_max_aggregation<reduce_aggregation>(), output_dtype, *initial_value); EXPECT_FALSE(result->is_valid()); // MINMAX auto mm_result = cudf::minmax(col_nulls); EXPECT_FALSE(mm_result.first->is_valid()); EXPECT_FALSE(mm_result.second->is_valid()); } TYPED_TEST(ReductionTest, Median) { using T = TypeParam; //{-20, -14, -13, 0, 6, 13, 45, 64/None} = 3.0, 0.0 std::vector<int> int_values({6, -14, 13, 64, 0, -13, -20, 45}); std::vector<bool> host_bools({1, 1, 1, 0, 1, 1, 1, 1}); std::vector<T> v = convert_values<T>(int_values); // test without nulls cudf::test::fixed_width_column_wrapper<T> col(v.begin(), v.end()); double expected_value = [] { if (std::is_same_v<T, bool>) return 1.0; if (std::is_signed_v<T>) return 3.0; return 13.5; }(); EXPECT_EQ( this->template reduction_test<double>(col, *cudf::make_median_aggregation<reduce_aggregation>()) .first, expected_value); auto col_odd = cudf::split(col, {1})[1]; double expected_value_odd = [] { if (std::is_same_v<T, bool>) return 1.0; if (std::is_signed_v<T>) return 0.0; return 14.0; }(); EXPECT_EQ(this ->template reduction_test<double>( col_odd, *cudf::make_median_aggregation<reduce_aggregation>()) .first, expected_value_odd); // test with nulls cudf::test::fixed_width_column_wrapper<T> col_nulls = construct_null_column(v, host_bools); double expected_null_value = [] { if (std::is_same_v<T, bool>) return 1.0; if (std::is_signed_v<T>) return 0.0; return 13.0; }(); EXPECT_EQ(this ->template reduction_test<double>( col_nulls, *cudf::make_median_aggregation<reduce_aggregation>()) .first, expected_null_value); auto col_nulls_odd = cudf::split(col_nulls, {1})[1]; double expected_null_value_odd = [] { if (std::is_same_v<T, bool>) return 1.0; if (std::is_signed_v<T>) return -6.5; return 13.5; }(); EXPECT_EQ(this ->template reduction_test<double>( col_nulls_odd, *cudf::make_median_aggregation<reduce_aggregation>()) .first, expected_null_value_odd); } TYPED_TEST(ReductionTest, Quantile) { using T = TypeParam; //{-20, -14, -13, 0, 6, 13, 45, 64/None} std::vector<int> int_values({6, -14, 13, 64, 0, -13, -20, 45}); std::vector<bool> host_bools({1, 1, 1, 0, 1, 1, 1, 1}); std::vector<T> v = convert_values<T>(int_values); cudf::interpolation interp{cudf::interpolation::LINEAR}; // test without nulls cudf::test::fixed_width_column_wrapper<T> col(v.begin(), v.end()); double expected_value0 = std::is_same_v<T, bool> || std::is_unsigned_v<T> ? v[4] : v[6]; EXPECT_EQ(this ->template reduction_test<double>( col, *cudf::make_quantile_aggregation<reduce_aggregation>({0.0}, interp)) .first, expected_value0); double expected_value1 = v[3]; EXPECT_EQ(this ->template reduction_test<double>( col, *cudf::make_quantile_aggregation<reduce_aggregation>({1.0}, interp)) .first, expected_value1); // test with nulls cudf::test::fixed_width_column_wrapper<T> col_nulls = construct_null_column(v, host_bools); double expected_null_value1 = v[7]; EXPECT_EQ(this ->template reduction_test<double>( col_nulls, *cudf::make_quantile_aggregation<reduce_aggregation>({0}, interp)) .first, expected_value0); EXPECT_EQ(this ->template reduction_test<double>( col_nulls, *cudf::make_quantile_aggregation<reduce_aggregation>({1}, interp)) .first, expected_null_value1); } TYPED_TEST(ReductionTest, UniqueCount) { using T = TypeParam; std::vector<int> int_values({1, -3, 1, 2, 0, 2, -4, 45}); // 6 unique values std::vector<bool> host_bools({1, 1, 1, 0, 1, 1, 1, 1}); std::vector<T> v = convert_values<T>(int_values); // test without nulls cudf::test::fixed_width_column_wrapper<T> col(v.begin(), v.end()); cudf::size_type expected_value = std::is_same_v<T, bool> ? 2 : 6; EXPECT_EQ( this ->template reduction_test<cudf::size_type>( col, *cudf::make_nunique_aggregation<reduce_aggregation>(cudf::null_policy::INCLUDE)) .first, expected_value); EXPECT_EQ( this ->template reduction_test<cudf::size_type>( col, *cudf::make_nunique_aggregation<reduce_aggregation>(cudf::null_policy::EXCLUDE)) .first, expected_value); // test with nulls cudf::test::fixed_width_column_wrapper<T> col_nulls = construct_null_column(v, host_bools); cudf::size_type expected_null_value0 = std::is_same_v<T, bool> ? 3 : 7; cudf::size_type expected_null_value1 = std::is_same_v<T, bool> ? 2 : 6; EXPECT_EQ( this ->template reduction_test<cudf::size_type>( col_nulls, *cudf::make_nunique_aggregation<reduce_aggregation>(cudf::null_policy::INCLUDE)) .first, expected_null_value0); EXPECT_EQ( this ->template reduction_test<cudf::size_type>( col_nulls, *cudf::make_nunique_aggregation<reduce_aggregation>(cudf::null_policy::EXCLUDE)) .first, expected_null_value1); } template <typename T> struct FixedPointTestAllReps : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(FixedPointTestAllReps, cudf::test::FixedPointTypes); TYPED_TEST(FixedPointTestAllReps, FixedPointReductionProductZeroScale) { using namespace numeric; using decimalXX = TypeParam; auto const ONE = decimalXX{1, scale_type{0}}; auto const TWO = decimalXX{2, scale_type{0}}; auto const THREE = decimalXX{3, scale_type{0}}; auto const FOUR = decimalXX{4, scale_type{0}}; auto const _24 = decimalXX{24, scale_type{0}}; auto const _48 = decimalXX{48, scale_type{0}}; auto const in = std::vector<decimalXX>{ONE, TWO, THREE, FOUR}; auto const column = cudf::test::fixed_width_column_wrapper<decimalXX>(in.cbegin(), in.cend()); auto const expected = std::accumulate(in.cbegin(), in.cend(), ONE, std::multiplies<decimalXX>()); auto const out_type = static_cast<cudf::column_view>(column).type(); auto const result = cudf::reduce(column, *cudf::make_product_aggregation<reduce_aggregation>(), out_type); auto const result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(result.get()); auto const result_fp = decimalXX{result_scalar->value()}; EXPECT_EQ(result_fp, expected); EXPECT_EQ(result_fp, _24); // Test with initial value auto const init_expected = std::accumulate(in.cbegin(), in.cend(), TWO, std::multiplies<decimalXX>()); auto const init_scalar = cudf::make_fixed_point_scalar<decimalXX>(2, scale_type{0}); auto const init_result = cudf::reduce( column, *cudf::make_product_aggregation<reduce_aggregation>(), out_type, *init_scalar); auto const init_result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(init_result.get()); auto const init_result_fp = decimalXX{init_result_scalar->value()}; EXPECT_EQ(init_result_fp, init_expected); EXPECT_EQ(init_result_fp, _48); } TYPED_TEST(FixedPointTestAllReps, FixedPointReductionProduct) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; for (auto const i : {0, -1}) { auto const scale = scale_type{i}; auto const column = fp_wrapper{{1, 2, 3, 1, 2, 3}, scale}; auto const out_type = static_cast<cudf::column_view>(column).type(); auto const expected = decimalXX{scaled_integer<RepType>{36, scale_type{i * 6}}}; auto const result = cudf::reduce(column, *cudf::make_product_aggregation<reduce_aggregation>(), out_type); auto const result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(result.get()); EXPECT_EQ(result_scalar->fixed_point_value(), expected); // Test with initial value auto const init_expected = decimalXX{scaled_integer<RepType>{72, scale_type{i * 7}}}; auto const init_scalar = cudf::make_fixed_point_scalar<decimalXX>(2, scale); auto const init_result = cudf::reduce( column, *cudf::make_product_aggregation<reduce_aggregation>(), out_type, *init_scalar); auto const init_result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(init_result.get()); EXPECT_EQ(init_result_scalar->fixed_point_value(), init_expected); } } TYPED_TEST(FixedPointTestAllReps, FixedPointReductionProductWithNulls) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; for (auto const i : {0, -1}) { auto const scale = scale_type{i}; auto const column = fp_wrapper{{1, 2, 3, 1, 2, 3}, {1, 1, 1, 0, 0, 0}, scale}; auto const out_type = static_cast<cudf::column_view>(column).type(); auto const expected = decimalXX{scaled_integer<RepType>{6, scale_type{i * 3}}}; auto const result = cudf::reduce(column, *cudf::make_product_aggregation<reduce_aggregation>(), out_type); auto const result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(result.get()); EXPECT_EQ(result_scalar->fixed_point_value(), expected); // Test with initial value auto const init_expected = decimalXX{scaled_integer<RepType>{12, scale_type{i * 4}}}; auto const init_scalar = cudf::make_fixed_point_scalar<decimalXX>(2, scale); auto const init_result = cudf::reduce( column, *cudf::make_product_aggregation<reduce_aggregation>(), out_type, *init_scalar); auto const init_result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(init_result.get()); EXPECT_EQ(init_result_scalar->fixed_point_value(), init_expected); } } TYPED_TEST(FixedPointTestAllReps, FixedPointReductionSum) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; for (auto const i : {0, -1, -2, -3}) { auto const scale = scale_type{i}; auto const column = fp_wrapper{{1, 2, 3, 4}, scale}; auto const expected = decimalXX{scaled_integer<RepType>{10, scale}}; auto const out_type = static_cast<cudf::column_view>(column).type(); auto const result = cudf::reduce(column, *cudf::make_sum_aggregation<reduce_aggregation>(), out_type); auto const result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(result.get()); EXPECT_EQ(result_scalar->fixed_point_value(), expected); // Test with initial value auto const init_expected = decimalXX{scaled_integer<RepType>{12, scale}}; auto const init_scalar = cudf::make_fixed_point_scalar<decimalXX>(2, scale); auto const init_result = cudf::reduce( column, *cudf::make_sum_aggregation<reduce_aggregation>(), out_type, *init_scalar); auto const init_result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(init_result.get()); EXPECT_EQ(init_result_scalar->fixed_point_value(), init_expected); } } TYPED_TEST(FixedPointTestAllReps, FixedPointReductionSumAlternate) { using namespace numeric; using decimalXX = TypeParam; auto const ZERO = decimalXX{0, scale_type{0}}; auto const ONE = decimalXX{1, scale_type{0}}; auto const TWO = decimalXX{2, scale_type{0}}; auto const THREE = decimalXX{3, scale_type{0}}; auto const FOUR = decimalXX{4, scale_type{0}}; auto const TEN = decimalXX{10, scale_type{0}}; auto const TWELVE = decimalXX{12, scale_type{0}}; auto const in = std::vector<decimalXX>{ONE, TWO, THREE, FOUR}; auto const column = cudf::test::fixed_width_column_wrapper<decimalXX>(in.cbegin(), in.cend()); auto const expected = std::accumulate(in.cbegin(), in.cend(), ZERO, std::plus<decimalXX>()); auto const out_type = static_cast<cudf::column_view>(column).type(); auto const result = cudf::reduce(column, *cudf::make_sum_aggregation<reduce_aggregation>(), out_type); auto const result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(result.get()); EXPECT_EQ(result_scalar->fixed_point_value(), expected); EXPECT_EQ(result_scalar->fixed_point_value(), TEN); // Test with initial value auto const init_expected = std::accumulate(in.cbegin(), in.cend(), TWO, std::plus<decimalXX>()); auto const init_scalar = cudf::make_fixed_point_scalar<decimalXX>(2, scale_type{0}); auto const init_result = cudf::reduce(column, *cudf::make_sum_aggregation<reduce_aggregation>(), out_type, *init_scalar); auto const init_result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(init_result.get()); EXPECT_EQ(init_result_scalar->fixed_point_value(), init_expected); EXPECT_EQ(init_result_scalar->fixed_point_value(), TWELVE); } TYPED_TEST(FixedPointTestAllReps, FixedPointReductionSumFractional) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; for (auto const i : {0, -1, -2, -3}) { auto const scale = scale_type{i}; auto const column = fp_wrapper{{111, 222, 333}, scale}; auto const out_type = static_cast<cudf::column_view>(column).type(); auto const expected = decimalXX{scaled_integer<RepType>{666, scale}}; auto const result = cudf::reduce(column, *cudf::make_sum_aggregation<reduce_aggregation>(), out_type); auto const result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(result.get()); EXPECT_EQ(result_scalar->fixed_point_value(), expected); // Test with initial value auto const init_expected = decimalXX{scaled_integer<RepType>{668, scale}}; auto const init_scalar = cudf::make_fixed_point_scalar<decimalXX>(2, scale); auto const init_result = cudf::reduce( column, *cudf::make_sum_aggregation<reduce_aggregation>(), out_type, *init_scalar); auto const init_result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(init_result.get()); EXPECT_EQ(init_result_scalar->fixed_point_value(), init_expected); } } TYPED_TEST(FixedPointTestAllReps, FixedPointReductionSumLarge) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; for (auto const i : {0, -1, -2}) { auto const scale = scale_type{i}; auto f = thrust::make_counting_iterator(0); auto const values = std::vector<RepType>(f, f + 1000); auto const column = fp_wrapper{values.cbegin(), values.cend(), scale}; auto const out_type = static_cast<cudf::column_view>(column).type(); auto const expected_value = std::accumulate(values.cbegin(), values.cend(), RepType{0}); auto const expected = decimalXX{scaled_integer<RepType>{expected_value, scale}}; auto const result = cudf::reduce(column, *cudf::make_sum_aggregation<reduce_aggregation>(), out_type); auto const result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(result.get()); EXPECT_EQ(result_scalar->fixed_point_value(), expected); // Test with initial value int const init_value = 2; auto const init_expected_value = std::accumulate(values.cbegin(), values.cend(), RepType{init_value}); auto const init_expected = decimalXX{scaled_integer<RepType>{init_expected_value, scale}}; auto const init_scalar = cudf::make_fixed_point_scalar<decimalXX>(init_value, scale); auto const init_result = cudf::reduce( column, *cudf::make_sum_aggregation<reduce_aggregation>(), out_type, *init_scalar); auto const init_result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(init_result.get()); EXPECT_EQ(init_result_scalar->fixed_point_value(), init_expected); } } TYPED_TEST(FixedPointTestAllReps, FixedPointReductionMin) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; for (auto const i : {0, -1, -2, -3}) { auto const scale = scale_type{i}; auto const ONE = decimalXX{scaled_integer<RepType>{1, scale}}; auto const column = fp_wrapper{{1, 2, 3, 4}, scale}; auto const out_type = static_cast<cudf::column_view>(column).type(); auto const result = cudf::reduce(column, *cudf::make_min_aggregation<reduce_aggregation>(), out_type); auto const result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(result.get()); EXPECT_EQ(result_scalar->fixed_point_value(), ONE); // Test with initial value auto const init_expected = decimalXX{scaled_integer<RepType>{0, scale}}; auto const init_scalar = cudf::make_fixed_point_scalar<decimalXX>(0, scale); auto const init_result = cudf::reduce( column, *cudf::make_min_aggregation<reduce_aggregation>(), out_type, *init_scalar); auto const init_result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(init_result.get()); EXPECT_EQ(init_result_scalar->fixed_point_value(), init_expected); } } TYPED_TEST(FixedPointTestAllReps, FixedPointReductionMinLarge) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; for (auto const i : {0, -1, -2, -3}) { auto const scale = scale_type{i}; auto f = cudf::detail::make_counting_transform_iterator(0, [](auto e) { return e % 43; }); auto const column = fp_wrapper{f, f + 5000, scale}; auto const out_type = static_cast<cudf::column_view>(column).type(); auto const expected = decimalXX{0, scale}; auto const result = cudf::reduce(column, *cudf::make_min_aggregation<reduce_aggregation>(), out_type); auto const result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(result.get()); EXPECT_EQ(result_scalar->fixed_point_value(), expected); // Test with initial value auto const init_expected = decimalXX{scaled_integer<RepType>{0, scale}}; auto const init_scalar = cudf::make_fixed_point_scalar<decimalXX>(0, scale); auto const init_result = cudf::reduce( column, *cudf::make_min_aggregation<reduce_aggregation>(), out_type, *init_scalar); auto const init_result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(init_result.get()); EXPECT_EQ(init_result_scalar->fixed_point_value(), init_expected); } } TYPED_TEST(FixedPointTestAllReps, FixedPointReductionMax) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; for (auto const i : {0, -1, -2, -3}) { auto const scale = scale_type{i}; auto const FOUR = decimalXX{scaled_integer<RepType>{4, scale}}; auto const column = fp_wrapper{{1, 2, 3, 4}, scale}; auto const out_type = static_cast<cudf::column_view>(column).type(); auto const result = cudf::reduce(column, *cudf::make_max_aggregation<reduce_aggregation>(), out_type); auto const result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(result.get()); EXPECT_EQ(result_scalar->fixed_point_value(), FOUR); // Test with initial value auto const init_expected = decimalXX{scaled_integer<RepType>{5, scale}}; auto const init_scalar = cudf::make_fixed_point_scalar<decimalXX>(5, scale); auto const init_result = cudf::reduce( column, *cudf::make_max_aggregation<reduce_aggregation>(), out_type, *init_scalar); auto const init_result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(init_result.get()); EXPECT_EQ(init_result_scalar->fixed_point_value(), init_expected); } } TYPED_TEST(FixedPointTestAllReps, FixedPointReductionMaxLarge) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; for (auto const i : {0, -1, -2, -3}) { auto const scale = scale_type{i}; auto f = cudf::detail::make_counting_transform_iterator(0, [](auto e) { return e % 43; }); auto const column = fp_wrapper{f, f + 5000, scale}; auto const out_type = static_cast<cudf::column_view>(column).type(); auto const expected = decimalXX{scaled_integer<RepType>{42, scale}}; auto const result = cudf::reduce(column, *cudf::make_max_aggregation<reduce_aggregation>(), out_type); auto const result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(result.get()); EXPECT_EQ(result_scalar->fixed_point_value(), expected); // Test with initial value auto const init_expected = decimalXX{scaled_integer<RepType>{43, scale}}; auto const init_scalar = cudf::make_fixed_point_scalar<decimalXX>(43, scale); auto const init_result = cudf::reduce( column, *cudf::make_max_aggregation<reduce_aggregation>(), out_type, *init_scalar); auto const init_result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(init_result.get()); EXPECT_EQ(init_result_scalar->fixed_point_value(), init_expected); } } TYPED_TEST(FixedPointTestAllReps, FixedPointReductionNUnique) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; for (auto const i : {0, -1, -2, -3}) { auto const scale = scale_type{i}; auto const column = fp_wrapper{{1, 1, 2, 2, 3, 3, 4, 4}, scale}; auto const out_type = static_cast<cudf::column_view>(column).type(); auto const result = cudf::reduce(column, *cudf::make_nunique_aggregation<reduce_aggregation>(), out_type); auto const result_scalar = static_cast<cudf::scalar_type_t<cudf::size_type>*>(result.get()); EXPECT_EQ(result_scalar->value(), 4); } } TYPED_TEST(FixedPointTestAllReps, FixedPointReductionSumOfSquares) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; for (auto const i : {0, -1, -2}) { auto const scale = scale_type{i}; auto const column = fp_wrapper{{1, 2, 3, 4}, scale}; auto const out_type = static_cast<cudf::column_view>(column).type(); auto const expected = decimalXX{scaled_integer<RepType>{30, scale_type{i * 2}}}; auto const result = cudf::reduce(column, *cudf::make_sum_of_squares_aggregation<reduce_aggregation>(), out_type); auto const result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(result.get()); EXPECT_EQ(result_scalar->fixed_point_value(), expected); } } TYPED_TEST(FixedPointTestAllReps, FixedPointReductionMedianOddNumberOfElements) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; for (auto const s : {0, -1, -2, -3, -4}) { auto const scale = scale_type{s}; auto const column = fp_wrapper{{1, 2, 2, 3, 4}, scale}; auto const out_type = static_cast<cudf::column_view>(column).type(); auto const expected = decimalXX{scaled_integer<RepType>{2, scale}}; auto const result = cudf::reduce(column, *cudf::make_median_aggregation<reduce_aggregation>(), out_type); auto const result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(result.get()); EXPECT_EQ(result_scalar->fixed_point_value(), expected); } } TYPED_TEST(FixedPointTestAllReps, FixedPointReductionMedianEvenNumberOfElements) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; for (auto const s : {0, -1, -2, -3, -4}) { auto const scale = scale_type{s}; auto const column = fp_wrapper{{10, 20, 20, 30, 30, 40}, scale}; auto const out_type = static_cast<cudf::column_view>(column).type(); auto const expected = decimalXX{scaled_integer<RepType>{25, scale}}; auto const result = cudf::reduce(column, *cudf::make_median_aggregation<reduce_aggregation>(), out_type); auto const result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(result.get()); EXPECT_EQ(result_scalar->fixed_point_value(), expected); } } TYPED_TEST(FixedPointTestAllReps, FixedPointReductionQuantile) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; for (auto const s : {0, -1, -2, -3, -4}) { auto const scale = scale_type{s}; auto const column = fp_wrapper{{1, 2, 3, 4, 5}, scale}; auto const out_type = static_cast<cudf::column_view>(column).type(); for (auto const i : {0, 1, 2, 3, 4}) { auto const expected = decimalXX{scaled_integer<RepType>{i + 1, scale}}; auto const result = cudf::reduce(column, *cudf::make_quantile_aggregation<reduce_aggregation>( {i / 4.0}, cudf::interpolation::LINEAR), out_type); auto const result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(result.get()); EXPECT_EQ(result_scalar->fixed_point_value(), expected); } } } TYPED_TEST(FixedPointTestAllReps, FixedPointReductionNthElement) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; for (auto const s : {0, -1, -2, -3, -4}) { auto const scale = scale_type{s}; auto const values = std::vector<RepType>{4104, 42, 1729, 55}; auto const column = fp_wrapper{values.cbegin(), values.cend(), scale}; auto const out_type = static_cast<cudf::column_view>(column).type(); for (auto const i : {0, 1, 2, 3}) { auto const expected = decimalXX{scaled_integer<RepType>{values[i], scale}}; auto const result = cudf::reduce( column, *cudf::make_nth_element_aggregation<reduce_aggregation>(i, cudf::null_policy::INCLUDE), out_type); auto const result_scalar = static_cast<cudf::scalar_type_t<decimalXX>*>(result.get()); EXPECT_EQ(result_scalar->fixed_point_value(), expected); } } } struct Decimal128Only : public cudf::test::BaseFixture {}; TEST_F(Decimal128Only, Decimal128ProductReduction) { using namespace numeric; using RepType = cudf::device_storage_type_t<decimal128>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; for (auto const i : {0, -1, -2, -3}) { auto const scale = scale_type{i}; auto const column = fp_wrapper{{2, 2, 2, 2, 2, 2, 2, 2, 2}, scale}; auto const expected = decimal128{scaled_integer<RepType>{512, scale_type{i * 9}}}; auto const out_type = cudf::data_type{cudf::type_id::DECIMAL128, scale}; auto const result = cudf::reduce(column, *cudf::make_product_aggregation<reduce_aggregation>(), out_type); auto const result_scalar = static_cast<cudf::scalar_type_t<decimal128>*>(result.get()); EXPECT_EQ(result_scalar->fixed_point_value(), expected); // Test with initial value auto const init_expected = decimal128{scaled_integer<RepType>{1024, scale_type{i * 10}}}; auto const init_scalar = cudf::make_fixed_point_scalar<decimal128>(2, scale); auto const init_result = cudf::reduce( column, *cudf::make_product_aggregation<reduce_aggregation>(), out_type, *init_scalar); auto const init_result_scalar = static_cast<cudf::scalar_type_t<decimal128>*>(init_result.get()); EXPECT_EQ(init_result_scalar->fixed_point_value(), init_expected); } } TEST_F(Decimal128Only, Decimal128ProductReduction2) { using namespace numeric; using RepType = cudf::device_storage_type_t<decimal128>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; for (auto const i : {0, -1, -2, -3, -4, -5, -6}) { auto const scale = scale_type{i}; auto const column = fp_wrapper{{1, 2, 3, 4, 5, 6}, scale}; auto const expected = decimal128{scaled_integer<RepType>{720, scale_type{i * 6}}}; auto const out_type = cudf::data_type{cudf::type_id::DECIMAL128, scale}; auto const result = cudf::reduce(column, *cudf::make_product_aggregation<reduce_aggregation>(), out_type); auto const result_scalar = static_cast<cudf::scalar_type_t<decimal128>*>(result.get()); EXPECT_EQ(result_scalar->fixed_point_value(), expected); // Test with initial value auto const init_expected = decimal128{scaled_integer<RepType>{2160, scale_type{i * 7}}}; auto const init_scalar = cudf::make_fixed_point_scalar<decimal128>(3, scale); auto const init_result = cudf::reduce( column, *cudf::make_product_aggregation<reduce_aggregation>(), out_type, *init_scalar); auto const init_result_scalar = static_cast<cudf::scalar_type_t<decimal128>*>(init_result.get()); EXPECT_EQ(init_result_scalar->fixed_point_value(), init_expected); } } TEST_F(Decimal128Only, Decimal128ProductReduction3) { using namespace numeric; using RepType = cudf::device_storage_type_t<decimal128>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const values = std::vector(127, -2); auto const scale = scale_type{0}; auto const column = fp_wrapper{values.cbegin(), values.cend(), scale}; auto const lowest = cuda::std::numeric_limits<RepType>::lowest(); auto const expected = decimal128{scaled_integer<RepType>{lowest, scale}}; auto const out_type = cudf::data_type{cudf::type_id::DECIMAL128, scale}; auto const result = cudf::reduce(column, *cudf::make_product_aggregation<reduce_aggregation>(), out_type); auto const result_scalar = static_cast<cudf::scalar_type_t<decimal128>*>(result.get()); EXPECT_EQ(result_scalar->fixed_point_value(), expected); // Test with initial value auto const init_scalar = cudf::make_fixed_point_scalar<decimal128>(5, scale); auto const init_result = cudf::reduce( column, *cudf::make_product_aggregation<reduce_aggregation>(), out_type, *init_scalar); auto const init_result_scalar = static_cast<cudf::scalar_type_t<decimal128>*>(init_result.get()); EXPECT_EQ(init_result_scalar->fixed_point_value(), expected); } TYPED_TEST(ReductionTest, NthElement) { using T = TypeParam; std::vector<int> int_values(4000); std::iota(int_values.begin(), int_values.end(), 0); std::vector<bool> host_bools(int_values.size()); auto valid_condition = [](auto i) { return (i % 3 and i % 7); }; std::transform(int_values.begin(), int_values.end(), host_bools.begin(), valid_condition); cudf::size_type valid_count = std::count(host_bools.begin(), host_bools.end(), true); std::vector<int> int_values_valid(valid_count); std::copy_if(int_values.begin(), int_values.end(), int_values_valid.begin(), valid_condition); std::vector<T> v = convert_values<T>(int_values); std::vector<T> v_valid = convert_values<T>(int_values_valid); cudf::size_type input_size = v.size(); auto mod = [](int a, int b) { return (a % b + b) % b; }; cudf::test::fixed_width_column_wrapper<T> col(v.begin(), v.end()); cudf::test::fixed_width_column_wrapper<T> col_nulls = construct_null_column(v, host_bools); // without nulls for (cudf::size_type n : {-input_size, -input_size / 2, -2, -1, 0, 1, 2, input_size / 2, input_size - 1}) { auto const index = mod(n, v.size()); T expected_value_nonull = v[index]; bool const expected_null = host_bools[index]; EXPECT_EQ( this ->template reduction_test<T>( col, *cudf::make_nth_element_aggregation<reduce_aggregation>(n, cudf::null_policy::INCLUDE)) .first, expected_value_nonull); EXPECT_EQ( this ->template reduction_test<T>( col, *cudf::make_nth_element_aggregation<reduce_aggregation>(n, cudf::null_policy::EXCLUDE)) .first, expected_value_nonull); auto res = this->template reduction_test<T>( col_nulls, *cudf::make_nth_element_aggregation<reduce_aggregation>(n, cudf::null_policy::INCLUDE)); EXPECT_EQ(res.first, expected_value_nonull); EXPECT_EQ(res.second, expected_null); } // valid only for (cudf::size_type n : {-valid_count, -valid_count / 2, -2, -1, 0, 1, 2, valid_count / 2, valid_count - 1}) { T expected_value_null = v_valid[mod(n, v_valid.size())]; EXPECT_EQ( this ->template reduction_test<T>( col_nulls, *cudf::make_nth_element_aggregation<reduce_aggregation>(n, cudf::null_policy::EXCLUDE)) .first, expected_value_null); } // error cases for (cudf::size_type n : {-input_size - 1, input_size}) { EXPECT_ANY_THROW(this->template reduction_test<T>( col, *cudf::make_nth_element_aggregation<reduce_aggregation>(n, cudf::null_policy::INCLUDE))); EXPECT_ANY_THROW(this->template reduction_test<T>( col_nulls, *cudf::make_nth_element_aggregation<reduce_aggregation>(n, cudf::null_policy::INCLUDE))); EXPECT_ANY_THROW(this->template reduction_test<T>( col, *cudf::make_nth_element_aggregation<reduce_aggregation>(n, cudf::null_policy::EXCLUDE))); EXPECT_ANY_THROW(this->template reduction_test<T>( col_nulls, *cudf::make_nth_element_aggregation<reduce_aggregation>(n, cudf::null_policy::EXCLUDE))); } } struct DictionaryStringReductionTest : public StringReductionTest {}; std::vector<std::string> data_list[] = { {"nine", "two", "five", "three", "five", "six", "two", "eight", "nine"}, }; INSTANTIATE_TEST_CASE_P(dictionary_cases, DictionaryStringReductionTest, testing::ValuesIn(data_list)); TEST_P(DictionaryStringReductionTest, MinMax) { std::vector<std::string> host_strings(GetParam()); cudf::data_type output_type{cudf::type_id::STRING}; cudf::test::dictionary_column_wrapper<std::string> col(host_strings.begin(), host_strings.end()); // MIN this->reduction_test(col, *(std::min_element(host_strings.begin(), host_strings.end())), true, *cudf::make_min_aggregation<reduce_aggregation>(), output_type); // sliced this->reduction_test(cudf::slice(col, {1, 7}).front(), *(std::min_element(host_strings.begin() + 1, host_strings.begin() + 7)), true, *cudf::make_min_aggregation<reduce_aggregation>(), output_type); // MAX this->reduction_test(col, *(std::max_element(host_strings.begin(), host_strings.end())), true, *cudf::make_max_aggregation<reduce_aggregation>(), output_type); // sliced this->reduction_test(cudf::slice(col, {1, 7}).front(), *(std::max_element(host_strings.begin() + 1, host_strings.begin() + 7)), true, *cudf::make_max_aggregation<reduce_aggregation>(), output_type); } template <typename T> struct DictionaryAnyAllTest : public ReductionTest<bool> {}; using DictionaryAnyAllTypes = cudf::test::Types<int16_t, int32_t, float, double, bool>; TYPED_TEST_SUITE(DictionaryAnyAllTest, cudf::test::NumericTypes); TYPED_TEST(DictionaryAnyAllTest, AnyAll) { using T = TypeParam; std::vector<int> all_values({true, true, true, true}); std::vector<T> v_all = convert_values<T>(all_values); std::vector<int> none_values({false, false, false, false}); std::vector<T> v_none = convert_values<T>(none_values); std::vector<int> some_values({false, true, false, true}); std::vector<T> v_some = convert_values<T>(some_values); cudf::data_type output_dtype(cudf::type_id::BOOL8); auto any_agg = cudf::make_any_aggregation<reduce_aggregation>(); auto all_agg = cudf::make_all_aggregation<reduce_aggregation>(); // without nulls { cudf::test::dictionary_column_wrapper<T> all_col(v_all.begin(), v_all.end()); EXPECT_TRUE(this->template reduction_test<bool>(all_col, *any_agg, output_dtype).first); EXPECT_TRUE(this->template reduction_test<bool>(all_col, *all_agg, output_dtype).first); cudf::test::dictionary_column_wrapper<T> none_col(v_none.begin(), v_none.end()); EXPECT_FALSE(this->template reduction_test<bool>(none_col, *any_agg, output_dtype).first); EXPECT_FALSE(this->template reduction_test<bool>(none_col, *all_agg, output_dtype).first); cudf::test::dictionary_column_wrapper<T> some_col(v_some.begin(), v_some.end()); EXPECT_TRUE(this->template reduction_test<bool>(some_col, *any_agg, output_dtype).first); EXPECT_FALSE(this->template reduction_test<bool>(some_col, *all_agg, output_dtype).first); // sliced test auto slice1 = cudf::slice(some_col, {1, 3}).front(); auto slice2 = cudf::slice(some_col, {1, 2}).front(); EXPECT_TRUE(this->template reduction_test<bool>(slice1, *any_agg, output_dtype).first); EXPECT_TRUE(this->template reduction_test<bool>(slice2, *all_agg, output_dtype).first); } // with nulls { std::vector<bool> valid({1, 1, 0, 1}); cudf::test::dictionary_column_wrapper<T> all_col(v_all.begin(), v_all.end(), valid.begin()); EXPECT_TRUE(this->template reduction_test<bool>(all_col, *any_agg, output_dtype).first); EXPECT_TRUE(this->template reduction_test<bool>(all_col, *all_agg, output_dtype).first); cudf::test::dictionary_column_wrapper<T> none_col(v_none.begin(), v_none.end(), valid.begin()); EXPECT_FALSE(this->template reduction_test<bool>(none_col, *any_agg, output_dtype).first); EXPECT_FALSE(this->template reduction_test<bool>(none_col, *all_agg, output_dtype).first); cudf::test::dictionary_column_wrapper<T> some_col(v_some.begin(), v_some.end(), valid.begin()); EXPECT_TRUE(this->template reduction_test<bool>(some_col, *any_agg, output_dtype).first); EXPECT_FALSE(this->template reduction_test<bool>(some_col, *all_agg, output_dtype).first); // sliced test auto slice1 = cudf::slice(some_col, {0, 3}).front(); auto slice2 = cudf::slice(some_col, {1, 4}).front(); EXPECT_TRUE(this->template reduction_test<bool>(slice1, *any_agg, output_dtype).first); EXPECT_TRUE(this->template reduction_test<bool>(slice2, *all_agg, output_dtype).first); } } template <typename T> struct DictionaryReductionTest : public ReductionTest<T> {}; using DictionaryTypes = cudf::test::Types<int16_t, int32_t, float, double>; TYPED_TEST_SUITE(DictionaryReductionTest, DictionaryTypes); TYPED_TEST(DictionaryReductionTest, Sum) { using T = TypeParam; std::vector<int> int_values({6, -14, 13, 64, 0, -13, -20, 45}); std::vector<T> v = convert_values<T>(int_values); cudf::data_type output_type{cudf::type_to_id<T>()}; cudf::test::dictionary_column_wrapper<T> col(v.begin(), v.end()); T expected_value = std::accumulate(v.begin(), v.end(), T{0}); EXPECT_EQ(this ->template reduction_test<T>( col, *cudf::make_sum_aggregation<reduce_aggregation>(), output_type) .first, expected_value); // test with nulls std::vector<bool> validity({1, 1, 0, 0, 1, 1, 1, 1}); cudf::test::dictionary_column_wrapper<T> col_nulls(v.begin(), v.end(), validity.begin()); expected_value = [v, validity] { auto const r = replace_nulls(v, validity, T{0}); return std::accumulate(r.begin(), r.end(), T{0}); }(); EXPECT_EQ(this ->template reduction_test<T>( col_nulls, *cudf::make_sum_aggregation<reduce_aggregation>(), output_type) .first, expected_value); } TYPED_TEST(DictionaryReductionTest, Product) { using T = TypeParam; std::vector<int> int_values({5, -1, 1, 0, 3, 2, 4}); std::vector<TypeParam> v = convert_values<TypeParam>(int_values); cudf::data_type output_type{cudf::type_to_id<T>()}; auto calc_prod = [](std::vector<T> const& v) { return std::accumulate(v.cbegin(), v.cend(), T{1}, std::multiplies<T>()); }; // test without nulls cudf::test::dictionary_column_wrapper<T> col(v.begin(), v.end()); EXPECT_EQ(this ->template reduction_test<T>( col, *cudf::make_product_aggregation<reduce_aggregation>(), output_type) .first, calc_prod(v)); // test with nulls std::vector<bool> validity({1, 1, 0, 0, 1, 1, 1}); cudf::test::dictionary_column_wrapper<T> col_nulls(v.begin(), v.end(), validity.begin()); EXPECT_EQ(this ->template reduction_test<T>( col_nulls, *cudf::make_product_aggregation<reduce_aggregation>(), output_type) .first, calc_prod(replace_nulls(v, validity, T{1}))); } TYPED_TEST(DictionaryReductionTest, SumOfSquare) { using T = TypeParam; std::vector<int> int_values({-3, 2, 1, 0, 5, -3, -2}); std::vector<T> v = convert_values<T>(int_values); cudf::data_type output_type{cudf::type_to_id<T>()}; auto calc_reduction = [](std::vector<T> const& v) { return std::accumulate(v.cbegin(), v.cend(), T{0}, [](T acc, T i) { return acc + i * i; }); }; // test without nulls cudf::test::dictionary_column_wrapper<T> col(v.begin(), v.end()); EXPECT_EQ(this ->template reduction_test<T>( col, *cudf::make_sum_of_squares_aggregation<reduce_aggregation>(), output_type) .first, calc_reduction(v)); // test with nulls std::vector<bool> validity({1, 1, 0, 0, 1, 1, 1, 1}); cudf::test::dictionary_column_wrapper<T> col_nulls(v.begin(), v.end(), validity.begin()); EXPECT_EQ( this ->template reduction_test<T>( col_nulls, *cudf::make_sum_of_squares_aggregation<reduce_aggregation>(), output_type) .first, calc_reduction(replace_nulls(v, validity, T{0}))); } TYPED_TEST(DictionaryReductionTest, Mean) { using T = TypeParam; std::vector<int> int_values({-3, 2, 1, 0, 5, -3, -2, 28}); std::vector<T> v = convert_values<T>(int_values); cudf::data_type output_type{cudf::type_to_id<double>()}; auto calc_mean = [](std::vector<T> const& v, cudf::size_type valid_count) { double sum = std::accumulate(v.cbegin(), v.cend(), double{0}); return sum / valid_count; }; // test without nulls cudf::test::dictionary_column_wrapper<T> col(v.begin(), v.end()); EXPECT_EQ(this ->template reduction_test<double>( col, *cudf::make_mean_aggregation<reduce_aggregation>(), output_type) .first, calc_mean(v, v.size())); // test with nulls std::vector<bool> validity({1, 1, 0, 1, 1, 1, 0, 1}); cudf::test::dictionary_column_wrapper<T> col_nulls(v.begin(), v.end(), validity.begin()); cudf::size_type valid_count = std::count(validity.begin(), validity.end(), true); EXPECT_EQ(this ->template reduction_test<double>( col_nulls, *cudf::make_mean_aggregation<reduce_aggregation>(), output_type) .first, calc_mean(replace_nulls(v, validity, T{0}), valid_count)); } #ifdef NDEBUG TYPED_TEST(DictionaryReductionTest, VarStd) #else TYPED_TEST(DictionaryReductionTest, DISABLED_VarStd) #endif { using T = TypeParam; std::vector<int> int_values({-3, 2, 1, 0, 5, -3, -2, 28}); std::vector<T> v = convert_values<T>(int_values); cudf::data_type output_type{cudf::type_to_id<double>()}; auto calc_var = [](std::vector<T> const& v, cudf::size_type valid_count, cudf::size_type ddof) { double mean = std::accumulate(v.cbegin(), v.cend(), double{0}); mean /= valid_count; double sum_of_sq = std::accumulate( v.cbegin(), v.cend(), double{0}, [](double acc, TypeParam i) { return acc + i * i; }); auto const div = valid_count - ddof; double var = sum_of_sq / div - ((mean * mean) * valid_count) / div; return var; }; // test without nulls cudf::test::dictionary_column_wrapper<T> col(v.begin(), v.end()); cudf::size_type const ddof = 1; double var = calc_var(v, v.size(), ddof); double std = std::sqrt(var); auto var_agg = cudf::make_variance_aggregation<reduce_aggregation>(ddof); auto std_agg = cudf::make_std_aggregation<reduce_aggregation>(ddof); EXPECT_EQ(this->template reduction_test<double>(col, *var_agg, output_type).first, var); EXPECT_EQ(this->template reduction_test<double>(col, *std_agg, output_type).first, std); // test with nulls std::vector<bool> validity({1, 1, 0, 1, 1, 1, 0, 1}); cudf::test::dictionary_column_wrapper<T> col_nulls(v.begin(), v.end(), validity.begin()); cudf::size_type const valid_count = std::count(validity.begin(), validity.end(), true); double var_nulls = calc_var(replace_nulls(v, validity, T{0}), valid_count, ddof); double std_nulls = std::sqrt(var_nulls); EXPECT_EQ(this->template reduction_test<double>(col_nulls, *var_agg, output_type).first, var_nulls); EXPECT_EQ(this->template reduction_test<double>(col_nulls, *std_agg, output_type).first, std_nulls); } TYPED_TEST(DictionaryReductionTest, NthElement) { using T = TypeParam; std::vector<int> int_values({-3, 2, 1, 0, 5, -3, -2, 28}); std::vector<T> v = convert_values<T>(int_values); cudf::data_type output_type{cudf::type_to_id<T>()}; // test without nulls cudf::test::dictionary_column_wrapper<T> col(v.begin(), v.end()); cudf::size_type n = 5; EXPECT_EQ(this ->template reduction_test<T>(col, *cudf::make_nth_element_aggregation<reduce_aggregation>( n, cudf::null_policy::INCLUDE), output_type) .first, v[n]); // test with nulls std::vector<bool> validity({1, 1, 0, 1, 1, 1, 0, 1}); cudf::test::dictionary_column_wrapper<T> col_nulls(v.begin(), v.end(), validity.begin()); EXPECT_EQ(this ->template reduction_test<T>(col_nulls, *cudf::make_nth_element_aggregation<reduce_aggregation>( n, cudf::null_policy::INCLUDE), output_type) .first, v[n]); EXPECT_FALSE( this ->template reduction_test<T>( col_nulls, *cudf::make_nth_element_aggregation<reduce_aggregation>(2, cudf::null_policy::INCLUDE), output_type) .second); } TYPED_TEST(DictionaryReductionTest, UniqueCount) { using T = TypeParam; std::vector<int> int_values({1, -3, 1, 2, 0, 2, -4, 45}); // 6 unique values std::vector<T> v = convert_values<T>(int_values); cudf::data_type output_type{cudf::type_to_id<cudf::size_type>()}; // test without nulls cudf::test::dictionary_column_wrapper<T> col(v.begin(), v.end()); EXPECT_EQ(this ->template reduction_test<int>( col, *cudf::make_nunique_aggregation<reduce_aggregation>(cudf::null_policy::INCLUDE), output_type) .first, 6); // test with nulls std::vector<bool> validity({1, 1, 1, 0, 1, 1, 1, 1}); cudf::test::dictionary_column_wrapper<T> col_nulls(v.begin(), v.end(), validity.begin()); EXPECT_EQ(this ->template reduction_test<int>( col_nulls, *cudf::make_nunique_aggregation<reduce_aggregation>(cudf::null_policy::INCLUDE), output_type) .first, 7); EXPECT_EQ(this ->template reduction_test<int>( col_nulls, *cudf::make_nunique_aggregation<reduce_aggregation>(cudf::null_policy::EXCLUDE), output_type) .first, 6); } TYPED_TEST(DictionaryReductionTest, Median) { using T = TypeParam; std::vector<int> int_values({6, -14, 13, 64, 0, -13, -20, 45}); std::vector<T> v = convert_values<T>(int_values); // test without nulls cudf::test::dictionary_column_wrapper<T> col(v.begin(), v.end()); EXPECT_EQ( this->template reduction_test<double>(col, *cudf::make_median_aggregation<reduce_aggregation>()) .first, (std::is_signed_v<T>) ? 3.0 : 13.5); // test with nulls std::vector<bool> validity({1, 1, 1, 0, 1, 1, 1, 1}); cudf::test::dictionary_column_wrapper<T> col_nulls(v.begin(), v.end(), validity.begin()); EXPECT_EQ(this ->template reduction_test<double>( col_nulls, *cudf::make_median_aggregation<reduce_aggregation>()) .first, (std::is_signed_v<T>) ? 0.0 : 13.0); } TYPED_TEST(DictionaryReductionTest, Quantile) { using T = TypeParam; std::vector<int> int_values({6, -14, 13, 64, 0, -13, -20, 45}); std::vector<T> v = convert_values<T>(int_values); cudf::interpolation interp{cudf::interpolation::LINEAR}; // test without nulls cudf::test::dictionary_column_wrapper<T> col(v.begin(), v.end()); double expected_value = std::is_same_v<T, bool> || std::is_unsigned_v<T> ? 0.0 : -20.0; EXPECT_EQ(this ->template reduction_test<double>( col, *cudf::make_quantile_aggregation<reduce_aggregation>({0.0}, interp)) .first, expected_value); EXPECT_EQ(this ->template reduction_test<double>( col, *cudf::make_quantile_aggregation<reduce_aggregation>({1.0}, interp)) .first, 64.0); // test with nulls std::vector<bool> validity({1, 1, 1, 0, 1, 1, 1, 1}); cudf::test::dictionary_column_wrapper<T> col_nulls(v.begin(), v.end(), validity.begin()); EXPECT_EQ(this ->template reduction_test<double>( col_nulls, *cudf::make_quantile_aggregation<reduce_aggregation>({0}, interp)) .first, expected_value); EXPECT_EQ(this ->template reduction_test<double>( col_nulls, *cudf::make_quantile_aggregation<reduce_aggregation>({1}, interp)) .first, 45.0); } struct ListReductionTest : public cudf::test::BaseFixture { void reduction_test(cudf::column_view const& input_data, cudf::column_view const& expected_value, bool succeeded_condition, bool is_valid, reduce_aggregation const& agg) { auto statement = [&]() { std::unique_ptr<cudf::scalar> result = cudf::reduce(input_data, agg, cudf::data_type(cudf::type_id::LIST)); auto list_result = dynamic_cast<cudf::list_scalar*>(result.get()); EXPECT_EQ(is_valid, list_result->is_valid()); if (is_valid) { CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_value, list_result->view()); } else { CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(expected_value, list_result->view()); } }; if (succeeded_condition) { CUDF_EXPECT_NO_THROW(statement()); } else { EXPECT_ANY_THROW(statement()); } } }; TEST_F(ListReductionTest, ListReductionNthElement) { using LCW = cudf::test::lists_column_wrapper<int>; using ElementCol = cudf::test::fixed_width_column_wrapper<int>; // test without nulls LCW col{{-3}, {2, 1}, {0, 5, -3}, {-2}, {}, {28}}; this->reduction_test( col, ElementCol{0, 5, -3}, // expected_value, true, true, *cudf::make_nth_element_aggregation<reduce_aggregation>(2, cudf::null_policy::INCLUDE)); // test with null-exclude std::vector<bool> validity{1, 0, 0, 1, 1, 0}; LCW col_nulls({{-3}, {2, 1}, {0, 5, -3}, {-2}, {}, {28}}, validity.begin()); this->reduction_test( col_nulls, ElementCol{-2}, // expected_value, true, true, *cudf::make_nth_element_aggregation<reduce_aggregation>(1, cudf::null_policy::EXCLUDE)); // test with null-include this->reduction_test( col_nulls, ElementCol{}, // expected_value, true, false, *cudf::make_nth_element_aggregation<reduce_aggregation>(1, cudf::null_policy::INCLUDE)); } TEST_F(ListReductionTest, NestedListReductionNthElement) { using LCW = cudf::test::lists_column_wrapper<int>; // test without nulls auto validity = std::vector<bool>{1, 0, 0, 1, 1}; auto nested_list = LCW( {{LCW{}, LCW{2, 3, 4}}, {}, {LCW{5}, LCW{6}, LCW{7, 8}}, {LCW{9, 10}}, {LCW{11}, LCW{12, 13}}}, validity.begin()); this->reduction_test( nested_list, LCW{{}, {2, 3, 4}}, // expected_value, true, true, *cudf::make_nth_element_aggregation<reduce_aggregation>(0, cudf::null_policy::INCLUDE)); // test with null-include this->reduction_test( nested_list, LCW{}, // expected_value, true, false, *cudf::make_nth_element_aggregation<reduce_aggregation>(2, cudf::null_policy::INCLUDE)); // test with null-exclude this->reduction_test( nested_list, LCW{{11}, {12, 13}}, // expected_value, true, true, *cudf::make_nth_element_aggregation<reduce_aggregation>(2, cudf::null_policy::EXCLUDE)); } TEST_F(ListReductionTest, NonValidListReductionNthElement) { using LCW = cudf::test::lists_column_wrapper<int>; using ElementCol = cudf::test::fixed_width_column_wrapper<int>; // test against col.size() <= col.null_count() std::vector<bool> validity{0}; this->reduction_test( LCW{{{1, 2}}, validity.begin()}, ElementCol{}, // expected_value, true, false, *cudf::make_nth_element_aggregation<reduce_aggregation>(0, cudf::null_policy::INCLUDE)); // test against empty input this->reduction_test( LCW{}, ElementCol{}, // expected_value, true, false, *cudf::make_nth_element_aggregation<reduce_aggregation>(0, cudf::null_policy::INCLUDE)); } TEST_F(ListReductionTest, ReductionMinMaxNoNull) { using INTS_CW = cudf::test::fixed_width_column_wrapper<int>; using LISTS_CW = cudf::test::lists_column_wrapper<int>; using STRINGS_CW = cudf::test::strings_column_wrapper; using LISTS_STRINGS_CW = cudf::test::lists_column_wrapper<cudf::string_view>; { auto const input = LISTS_CW{{3, 4}, {1, 2}, {5, 6, 7}, {0, 8}, {9, 10}, {1, 0}}; this->reduction_test( input, INTS_CW{0, 8}, true, true, *cudf::make_min_aggregation<reduce_aggregation>()); this->reduction_test( input, INTS_CW{9, 10}, true, true, *cudf::make_max_aggregation<reduce_aggregation>()); } { auto const input = LISTS_STRINGS_CW{ {"34", "43"}, {"12", "21"}, {"567", "6", "765"}, {"08", "8"}, {"109", "10"}, {"10", "00"}}; this->reduction_test( input, STRINGS_CW{"08", "8"}, true, true, *cudf::make_min_aggregation<reduce_aggregation>()); this->reduction_test(input, STRINGS_CW{"567", "6", "765"}, true, true, *cudf::make_max_aggregation<reduce_aggregation>()); } } TEST_F(ListReductionTest, ReductionMinMaxSlicedInput) { using INTS_CW = cudf::test::fixed_width_column_wrapper<int>; using LISTS_CW = cudf::test::lists_column_wrapper<int>; using STRINGS_CW = cudf::test::strings_column_wrapper; using LISTS_STRINGS_CW = cudf::test::lists_column_wrapper<cudf::string_view>; { auto const input_original = LISTS_CW{{9, 9} /*don't care*/, {0, 0} /*don't care*/, {3, 4}, {1, 2}, {5, 6, 7}, {0, 8}, {9, 10}, {1, 0}, {0, 7} /*don't care*/}; auto const input = cudf::slice(input_original, {2, 8})[0]; this->reduction_test( input, INTS_CW{0, 8}, true, true, *cudf::make_min_aggregation<reduce_aggregation>()); this->reduction_test( input, INTS_CW{9, 10}, true, true, *cudf::make_max_aggregation<reduce_aggregation>()); } { auto const input_original = LISTS_STRINGS_CW{{"08", "8"} /*don't care*/, {"999", "8"} /*don't care*/, {"34", "43"}, {"12", "21"}, {"567", "6", "765"}, {"08", "8"}, {"109", "10"}, {"10", "00"}}; auto const input = cudf::slice(input_original, {2, 8})[0]; this->reduction_test( input, STRINGS_CW{"08", "8"}, true, true, *cudf::make_min_aggregation<reduce_aggregation>()); this->reduction_test(input, STRINGS_CW{"567", "6", "765"}, true, true, *cudf::make_max_aggregation<reduce_aggregation>()); } } TEST_F(ListReductionTest, ReductionMinMaxWithNulls) { using INTS_CW = cudf::test::fixed_width_column_wrapper<int>; using LISTS_CW = cudf::test::lists_column_wrapper<int>; using cudf::test::iterators::null_at; using cudf::test::iterators::nulls_at; constexpr int null{0}; auto const input = LISTS_CW{{LISTS_CW{3, 4}, LISTS_CW{1, 2}, LISTS_CW{{1, null}, null_at(1)}, LISTS_CW{} /*null*/, LISTS_CW{5, 6, 7}, LISTS_CW{1, 8}, LISTS_CW{{9, null}, null_at(1)}, LISTS_CW{} /*null*/}, nulls_at({3, 7})}; this->reduction_test(input, INTS_CW{{1, null}, null_at(1)}, true, true, *cudf::make_min_aggregation<reduce_aggregation>()); this->reduction_test(input, INTS_CW{{9, null}, null_at(1)}, true, true, *cudf::make_max_aggregation<reduce_aggregation>()); } struct StructReductionTest : public cudf::test::BaseFixture { using SCW = cudf::test::structs_column_wrapper; void reduction_test(cudf::column_view const& struct_column, cudf::table_view const& expected_value, bool succeeded_condition, bool is_valid, reduce_aggregation const& agg) { auto statement = [&]() { std::unique_ptr<cudf::scalar> result = cudf::reduce(struct_column, agg, cudf::data_type(cudf::type_id::STRUCT)); auto struct_result = dynamic_cast<cudf::struct_scalar*>(result.get()); EXPECT_EQ(is_valid, struct_result->is_valid()); if (is_valid) { CUDF_TEST_EXPECT_TABLES_EQUIVALENT(expected_value, struct_result->view()); } }; if (succeeded_condition) { CUDF_EXPECT_NO_THROW(statement()); } else { EXPECT_ANY_THROW(statement()); } } }; TEST_F(StructReductionTest, StructReductionNthElement) { using ICW = cudf::test::fixed_width_column_wrapper<int>; // test without nulls auto child0 = *ICW{-3, 2, 1, 0, 5, -3, -2, 28}.release(); auto child1 = *ICW{0, 1, 2, 3, 4, 5, 6, 7}.release(); auto child2 = *ICW{{-10, 10, -100, 100, -1000, 1000, -10000, 10000}, {1, 0, 0, 1, 1, 1, 0, 1}}.release(); std::vector<std::unique_ptr<cudf::column>> input_vector; input_vector.push_back(std::make_unique<cudf::column>(child0)); input_vector.push_back(std::make_unique<cudf::column>(child1)); input_vector.push_back(std::make_unique<cudf::column>(child2)); auto struct_col = SCW(std::move(input_vector)); auto result_col0 = ICW{1}; auto result_col1 = ICW{2}; auto result_col2 = ICW{{0}, {0}}; this->reduction_test( struct_col, cudf::table_view{{result_col0, result_col1, result_col2}}, // expected_value, true, true, *cudf::make_nth_element_aggregation<reduce_aggregation>(2, cudf::null_policy::INCLUDE)); // test with null-include std::vector<bool> validity{1, 1, 1, 0, 1, 0, 0, 1}; input_vector.clear(); input_vector.push_back(std::make_unique<cudf::column>(child0)); input_vector.push_back(std::make_unique<cudf::column>(child1)); input_vector.push_back(std::make_unique<cudf::column>(child2)); struct_col = SCW(std::move(input_vector), validity); result_col0 = ICW{{0}, {0}}; result_col1 = ICW{{0}, {0}}; result_col2 = ICW{{0}, {0}}; this->reduction_test( struct_col, cudf::table_view{{result_col0, result_col1, result_col2}}, // expected_value, true, false, *cudf::make_nth_element_aggregation<reduce_aggregation>(6, cudf::null_policy::INCLUDE)); // test with null-exclude result_col0 = ICW{{28}, {1}}; result_col1 = ICW{{7}, {1}}; result_col2 = ICW{{10000}, {1}}; this->reduction_test( struct_col, cudf::table_view{{result_col0, result_col1, result_col2}}, // expected_value, true, true, *cudf::make_nth_element_aggregation<reduce_aggregation>(4, cudf::null_policy::EXCLUDE)); } TEST_F(StructReductionTest, NestedStructReductionNthElement) { using ICW = cudf::test::fixed_width_column_wrapper<int>; using LCW = cudf::test::lists_column_wrapper<int>; auto int_col0 = ICW{-4, -3, -2, -1, 0}; auto struct_col0 = SCW({int_col0}, std::vector<bool>{1, 0, 0, 1, 1}); auto int_col1 = ICW{0, 1, 2, 3, 4}; auto list_col = LCW{{0}, {}, {1, 2}, {3}, {4}}; auto struct_col1 = SCW({struct_col0, int_col1, list_col}, std::vector<bool>{1, 1, 1, 0, 1}); auto result_child0 = ICW{0}; auto result_col0 = SCW({result_child0}, std::vector<bool>{0}); auto result_col1 = ICW{{1}, {1}}; auto result_col2 = LCW({LCW{}}, std::vector<bool>{1}.begin()); // test without nulls this->reduction_test( struct_col1, cudf::table_view{{result_col0, result_col1, result_col2}}, // expected_value, true, true, *cudf::make_nth_element_aggregation<reduce_aggregation>(1, cudf::null_policy::INCLUDE)); // test with null-include result_child0 = ICW{0}; result_col0 = SCW({result_child0}, std::vector<bool>{0}); result_col1 = ICW{{0}, {0}}; result_col2 = LCW({LCW{3}}, std::vector<bool>{0}.begin()); this->reduction_test( struct_col1, cudf::table_view{{result_col0, result_col1, result_col2}}, // expected_value, true, false, *cudf::make_nth_element_aggregation<reduce_aggregation>(3, cudf::null_policy::INCLUDE)); // test with null-exclude result_child0 = ICW{0}; result_col0 = SCW({result_child0}, std::vector<bool>{1}); result_col1 = ICW{{4}, {1}}; result_col2 = LCW({LCW{4}}, std::vector<bool>{1}.begin()); this->reduction_test( struct_col1, cudf::table_view{{result_col0, result_col1, result_col2}}, // expected_value, true, true, *cudf::make_nth_element_aggregation<reduce_aggregation>(3, cudf::null_policy::EXCLUDE)); } TEST_F(StructReductionTest, NonValidStructReductionNthElement) { using ICW = cudf::test::fixed_width_column_wrapper<int>; // test against col.size() <= col.null_count() auto child0 = ICW{-3, 3}; auto child1 = ICW{0, 0}; auto child2 = ICW{{-10, 10}, {0, 1}}; auto struct_col = SCW{{child0, child1, child2}, {0, 0}}; auto ret_col0 = ICW{{0}, {0}}; auto ret_col1 = ICW{{0}, {0}}; auto ret_col2 = ICW{{0}, {0}}; this->reduction_test( struct_col, cudf::table_view{{ret_col0, ret_col1, ret_col2}}, // expected_value, true, false, *cudf::make_nth_element_aggregation<reduce_aggregation>(0, cudf::null_policy::INCLUDE)); // test against empty input (would fail because we can not create empty struct scalar) child0 = ICW{}; child1 = ICW{}; child2 = ICW{}; struct_col = SCW{{child0, child1, child2}}; ret_col0 = ICW{}; ret_col1 = ICW{}; ret_col2 = ICW{}; this->reduction_test( struct_col, cudf::table_view{{ret_col0, ret_col1, ret_col2}}, // expected_value, false, false, *cudf::make_nth_element_aggregation<reduce_aggregation>(0, cudf::null_policy::INCLUDE)); } TEST_F(StructReductionTest, StructReductionMinMaxNoNull) { using INTS_CW = cudf::test::fixed_width_column_wrapper<int>; using STRINGS_CW = cudf::test::strings_column_wrapper; using STRUCTS_CW = cudf::test::structs_column_wrapper; auto const input = [] { auto child1 = STRINGS_CW{"año", "bit", "₹1", "aaa", "zit", "bat", "aab", "$1", "€1", "wut"}; auto child2 = INTS_CW{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; return STRUCTS_CW{{child1, child2}}; }(); { auto const expected_child1 = STRINGS_CW{"$1"}; auto const expected_child2 = INTS_CW{8}; this->reduction_test(input, cudf::table_view{{expected_child1, expected_child2}}, true, true, *cudf::make_min_aggregation<reduce_aggregation>()); } { auto const expected_child1 = STRINGS_CW{"₹1"}; auto const expected_child2 = INTS_CW{3}; this->reduction_test(input, cudf::table_view{{expected_child1, expected_child2}}, true, true, *cudf::make_max_aggregation<reduce_aggregation>()); } } TEST_F(StructReductionTest, StructReductionMinMaxSlicedInput) { using INTS_CW = cudf::test::fixed_width_column_wrapper<int>; using STRINGS_CW = cudf::test::strings_column_wrapper; using STRUCTS_CW = cudf::test::structs_column_wrapper; constexpr int32_t dont_care{1}; auto const input_original = [] { auto child1 = STRINGS_CW{"$dont_care", "$dont_care", "año", "bit", "₹1", "aaa", "zit", "bat", "aab", "$1", "€1", "wut", "₹dont_care"}; auto child2 = INTS_CW{dont_care, dont_care, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, dont_care}; return STRUCTS_CW{{child1, child2}}; }(); auto const input = cudf::slice(input_original, {2, 12})[0]; { auto const expected_child1 = STRINGS_CW{"$1"}; auto const expected_child2 = INTS_CW{8}; this->reduction_test(input, cudf::table_view{{expected_child1, expected_child2}}, true, true, *cudf::make_min_aggregation<reduce_aggregation>()); } { auto const expected_child1 = STRINGS_CW{"₹1"}; auto const expected_child2 = INTS_CW{3}; this->reduction_test(input, cudf::table_view{{expected_child1, expected_child2}}, true, true, *cudf::make_max_aggregation<reduce_aggregation>()); } } TEST_F(StructReductionTest, StructReductionMinMaxWithNulls) { using INTS_CW = cudf::test::fixed_width_column_wrapper<int>; using STRINGS_CW = cudf::test::strings_column_wrapper; using STRUCTS_CW = cudf::test::structs_column_wrapper; using cudf::test::iterators::null_at; using cudf::test::iterators::nulls_at; // `null` means null at child column. // `NULL` means null at parent column. auto const input = [] { auto child1 = STRINGS_CW{{"año", "bit", "₹1" /*null*/, "aaa" /*NULL*/, "zit", "bat", "aab", "$1" /*null*/, "€1" /*NULL*/, "wut"}, nulls_at({2, 7})}; auto child2 = INTS_CW{{1, 2, 3 /*null*/, 4 /*NULL*/, 5, 6, 7, 8 /*null*/, 9 /*NULL*/, 10}, nulls_at({2, 7})}; return STRUCTS_CW{{child1, child2}, nulls_at({3, 8})}; }(); { // In the structs column, the min struct is {null, null}. auto const expected_child1 = STRINGS_CW{{""}, null_at(0)}; auto const expected_child2 = INTS_CW{{8}, null_at(0)}; this->reduction_test(input, cudf::table_view{{expected_child1, expected_child2}}, true, true, *cudf::make_min_aggregation<reduce_aggregation>()); } { auto const expected_child1 = STRINGS_CW{"zit"}; auto const expected_child2 = INTS_CW{5}; this->reduction_test(input, cudf::table_view{{expected_child1, expected_child2}}, true, true, *cudf::make_max_aggregation<reduce_aggregation>()); } } CUDF_TEST_PROGRAM_MAIN()
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/utilities/debug_utilities.cu
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/column_utilities.hpp> #include <cudf_test/debug_utilities.hpp> #include <cudf/detail/get_value.cuh> #include <cudf/dictionary/dictionary_column_view.hpp> #include <cudf/lists/lists_column_view.hpp> #include <cudf/strings/convert/convert_datetime.hpp> #include <cudf/structs/structs_column_view.hpp> #include <cudf/utilities/bit.hpp> #include <cudf/utilities/default_stream.hpp> #include <cudf/utilities/type_dispatcher.hpp> #include <rmm/exec_policy.hpp> #include <thrust/iterator/counting_iterator.h> #include <thrust/transform.h> #include <iomanip> #include <sstream> namespace cudf::test { // Forward declaration. namespace detail { /** * @brief Formats a column view as a string * * @param col The column view * @param delimiter The delimiter to put between strings * @param indent Indentation for all output */ std::string to_string(cudf::column_view const& col, std::string const& delimiter, std::string const& indent = ""); /** * @brief Formats a null mask as a string * * @param null_mask The null mask buffer * @param null_mask_size Size of the null mask (in rows) * @param indent Indentation for all output */ std::string to_string(std::vector<bitmask_type> const& null_mask, size_type null_mask_size, std::string const& indent = ""); /** * @brief Convert column values to a host vector of strings * * Supports indentation of all output. For example, if the displayed output of your column * would be * * @code{.pseudo} * "1,2,3,4,5" * @endcode * and the `indent` parameter was " ", that indentation would be prepended to * result in the output * @code{.pseudo} * " 1,2,3,4,5" * @endcode * * The can be useful for displaying complex types. An example use case would be for * displaying the nesting of a LIST type column (via recursion). * * List<List<int>>: * Length : 3 * Offsets : 0, 2, 5, 6 * Children : * List<int>: * Length : 6 * Offsets : 0, 2, 4, 7, 8, 9, 11 * Children : * 1, 2, 3, 4, 5, 6, 7, 0, 8, 9, 10 * * @param col The column view * @param indent Indentation for all output */ std::vector<std::string> to_strings(cudf::column_view const& col, std::string const& indent = ""); } // namespace detail namespace { template <typename T, std::enable_if_t<std::is_integral_v<T>>* = nullptr> static auto numeric_to_string_precise(T value) { return std::to_string(value); } template <typename T, std::enable_if_t<std::is_floating_point_v<T>>* = nullptr> static auto numeric_to_string_precise(T value) { std::ostringstream o; o << std::setprecision(std::numeric_limits<T>::max_digits10) << value; return o.str(); } static auto duration_suffix(cudf::duration_D) { return " days"; } static auto duration_suffix(cudf::duration_s) { return " seconds"; } static auto duration_suffix(cudf::duration_ms) { return " milliseconds"; } static auto duration_suffix(cudf::duration_us) { return " microseconds"; } static auto duration_suffix(cudf::duration_ns) { return " nanoseconds"; } std::string get_nested_type_str(cudf::column_view const& view) { if (view.type().id() == cudf::type_id::LIST) { lists_column_view lcv(view); return cudf::type_to_name(view.type()) + "<" + (get_nested_type_str(lcv.child())) + ">"; } if (view.type().id() == cudf::type_id::STRUCT) { std::ostringstream out; out << cudf::type_to_name(view.type()) + "<"; std::transform(view.child_begin(), view.child_end(), std::ostream_iterator<std::string>(out, ","), [&out](auto const col) { return get_nested_type_str(col); }); out << ">"; return out.str(); } return cudf::type_to_name(view.type()); } template <typename NestedColumnView> std::string nested_offsets_to_string(NestedColumnView const& c, std::string const& delimiter = ", ") { column_view offsets = (c.parent()).child(NestedColumnView::offsets_column_index); CUDF_EXPECTS(offsets.type().id() == type_id::INT32, "Column does not appear to be an offsets column"); CUDF_EXPECTS(offsets.offset() == 0, "Offsets column has an internal offset!"); size_type output_size = c.size() + 1; // the first offset value to normalize everything against size_type first = cudf::detail::get_value<size_type>(offsets, c.offset(), cudf::get_default_stream()); rmm::device_uvector<size_type> shifted_offsets(output_size, cudf::get_default_stream()); // normalize the offset values for the column offset size_type const* d_offsets = offsets.head<size_type>() + c.offset(); thrust::transform( rmm::exec_policy(cudf::get_default_stream()), d_offsets, d_offsets + output_size, shifted_offsets.begin(), [first] __device__(int32_t offset) { return static_cast<size_type>(offset - first); }); auto const h_shifted_offsets = cudf::detail::make_host_vector_sync(shifted_offsets, cudf::get_default_stream()); std::ostringstream buffer; for (size_t idx = 0; idx < h_shifted_offsets.size(); idx++) { buffer << h_shifted_offsets[idx]; if (idx < h_shifted_offsets.size() - 1) { buffer << delimiter; } } return buffer.str(); } struct column_view_printer { template <typename Element, std::enable_if_t<is_numeric<Element>()>* = nullptr> void operator()(cudf::column_view const& col, std::vector<std::string>& out, std::string const&) { auto h_data = cudf::test::to_host<Element>(col); out.resize(col.size()); if (col.nullable()) { std::transform(thrust::make_counting_iterator(size_type{0}), thrust::make_counting_iterator(col.size()), out.begin(), [&h_data](auto idx) { return bit_is_set(h_data.second.data(), idx) ? numeric_to_string_precise(h_data.first[idx]) : std::string("NULL"); }); } else { std::transform(h_data.first.begin(), h_data.first.end(), out.begin(), [](Element el) { return numeric_to_string_precise(el); }); } } template <typename Element, std::enable_if_t<is_timestamp<Element>()>* = nullptr> void operator()(cudf::column_view const& col, std::vector<std::string>& out, std::string const& indent) { // For timestamps, convert timestamp column to column of strings, then // call string version std::string format = [&]() { if constexpr (std::is_same_v<cudf::timestamp_s, Element>) { return std::string{"%Y-%m-%dT%H:%M:%SZ"}; } else if constexpr (std::is_same_v<cudf::timestamp_ms, Element>) { return std::string{"%Y-%m-%dT%H:%M:%S.%3fZ"}; } else if constexpr (std::is_same_v<cudf::timestamp_us, Element>) { return std::string{"%Y-%m-%dT%H:%M:%S.%6fZ"}; } else if constexpr (std::is_same_v<cudf::timestamp_ns, Element>) { return std::string{"%Y-%m-%dT%H:%M:%S.%9fZ"}; } return std::string{"%Y-%m-%d"}; }(); auto col_as_strings = cudf::strings::from_timestamps(col, format); if (col_as_strings->size() == 0) { return; } this->template operator()<cudf::string_view>(*col_as_strings, out, indent); } template <typename Element, std::enable_if_t<cudf::is_fixed_point<Element>()>* = nullptr> void operator()(cudf::column_view const& col, std::vector<std::string>& out, std::string const&) { auto const h_data = cudf::test::to_host<Element>(col); if (col.nullable()) { std::transform(thrust::make_counting_iterator(size_type{0}), thrust::make_counting_iterator(col.size()), std::back_inserter(out), [&h_data](auto idx) { return h_data.second.empty() || bit_is_set(h_data.second.data(), idx) ? static_cast<std::string>(h_data.first[idx]) : std::string("NULL"); }); } else { std::transform(std::cbegin(h_data.first), std::cend(h_data.first), std::back_inserter(out), [col](auto const& fp) { return static_cast<std::string>(fp); }); } } template <typename Element, std::enable_if_t<std::is_same_v<Element, cudf::string_view>>* = nullptr> void operator()(cudf::column_view const& col, std::vector<std::string>& out, std::string const&) { // // Implementation for strings, call special to_host variant // if (col.is_empty()) return; auto h_data = cudf::test::to_host<std::string>(col); // explicitly replace some special whitespace characters with their literal equivalents auto cleaned = [](std::string_view in) { std::string out(in); auto replace_char = [](std::string& out, char c, std::string_view repl) { for (std::string::size_type pos{}; out.npos != (pos = out.find(c, pos)); pos++) { out.replace(pos, 1, repl); } }; replace_char(out, '\a', "\\a"); replace_char(out, '\b', "\\b"); replace_char(out, '\f', "\\f"); replace_char(out, '\r', "\\r"); replace_char(out, '\t', "\\t"); replace_char(out, '\n', "\\n"); replace_char(out, '\v', "\\v"); return out; }; out.resize(col.size()); std::transform(thrust::make_counting_iterator(size_type{0}), thrust::make_counting_iterator(col.size()), out.begin(), [&](auto idx) { return h_data.second.empty() || bit_is_set(h_data.second.data(), idx) ? cleaned(h_data.first[idx]) : std::string("NULL"); }); } template <typename Element, std::enable_if_t<std::is_same_v<Element, cudf::dictionary32>>* = nullptr> void operator()(cudf::column_view const& col, std::vector<std::string>& out, std::string const&) { cudf::dictionary_column_view dictionary(col); if (col.is_empty()) return; std::vector<std::string> keys = to_strings(dictionary.keys()); std::vector<std::string> indices = to_strings({dictionary.indices().type(), dictionary.size(), dictionary.indices().head(), dictionary.null_mask(), dictionary.null_count(), dictionary.offset()}); out.insert(out.end(), keys.begin(), keys.end()); if (!indices.empty()) { std::string first = "\x08 : " + indices.front(); // use : as delimiter out.push_back(first); // between keys and indices out.insert(out.end(), indices.begin() + 1, indices.end()); } } // Print the tick counts with the units template <typename Element, std::enable_if_t<is_duration<Element>()>* = nullptr> void operator()(cudf::column_view const& col, std::vector<std::string>& out, std::string const&) { auto h_data = cudf::test::to_host<Element>(col); out.resize(col.size()); if (col.nullable()) { std::transform(thrust::make_counting_iterator(size_type{0}), thrust::make_counting_iterator(col.size()), out.begin(), [&h_data](auto idx) { return bit_is_set(h_data.second.data(), idx) ? numeric_to_string_precise(h_data.first[idx].count()) + duration_suffix(h_data.first[idx]) : std::string("NULL"); }); } else { std::transform(h_data.first.begin(), h_data.first.end(), out.begin(), [](Element el) { return numeric_to_string_precise(el.count()) + duration_suffix(el); }); } } template <typename Element, std::enable_if_t<std::is_same_v<Element, cudf::list_view>>* = nullptr> void operator()(cudf::column_view const& col, std::vector<std::string>& out, std::string const& indent) { lists_column_view lcv(col); // propagate slicing to the child if necessary column_view child = lcv.get_sliced_child(cudf::get_default_stream()); bool const is_sliced = lcv.offset() > 0 || child.offset() > 0; std::string tmp = get_nested_type_str(col) + (is_sliced ? "(sliced)" : "") + ":\n" + indent + "Length : " + std::to_string(lcv.size()) + "\n" + indent + "Offsets : " + (lcv.size() > 0 ? nested_offsets_to_string(lcv) : "") + "\n" + (lcv.parent().nullable() ? indent + "Null count: " + std::to_string(lcv.null_count()) + "\n" + detail::to_string(cudf::test::bitmask_to_host(col), col.size(), indent) + "\n" : "") + // non-nested types don't typically display their null masks, so do it here for convenience. (!is_nested(child.type()) && child.nullable() ? " " + detail::to_string(cudf::test::bitmask_to_host(child), child.size(), indent) + "\n" : "") + (detail::to_string(child, ", ", indent + " ")) + "\n"; out.push_back(tmp); } template <typename Element, std::enable_if_t<std::is_same_v<Element, cudf::struct_view>>* = nullptr> void operator()(cudf::column_view const& col, std::vector<std::string>& out, std::string const& indent) { structs_column_view view{col}; std::ostringstream out_stream; out_stream << get_nested_type_str(col) << ":\n" << indent << "Length : " << view.size() << ":\n"; if (view.nullable()) { out_stream << indent << "Null count: " << view.null_count() << "\n" << detail::to_string(cudf::test::bitmask_to_host(col), col.size(), indent) << "\n"; } auto iter = thrust::make_counting_iterator(0); std::transform( iter, iter + view.num_children(), std::ostream_iterator<std::string>(out_stream, "\n"), [&](size_type index) { auto child = view.get_sliced_child(index, cudf::get_default_stream()); // non-nested types don't typically display their null masks, so do it here for convenience. return (!is_nested(child.type()) && child.nullable() ? " " + detail::to_string(cudf::test::bitmask_to_host(child), child.size(), indent) + "\n" : "") + detail::to_string(child, ", ", indent + " "); }); out.push_back(out_stream.str()); } }; } // namespace namespace detail { /** * @copydoc cudf::test::detail::to_strings */ std::vector<std::string> to_strings(cudf::column_view const& col, std::string const& indent) { std::vector<std::string> reply; cudf::type_dispatcher(col.type(), column_view_printer{}, col, reply, indent); return reply; } /** * @copydoc cudf::test::detail::to_string(cudf::column_view, std::string, std::string) * * @param indent Indentation for all output */ std::string to_string(cudf::column_view const& col, std::string const& delimiter, std::string const& indent) { std::ostringstream buffer; std::vector<std::string> h_data = to_strings(col, indent); buffer << indent; std::copy(h_data.begin(), h_data.end() - (!h_data.empty()), std::ostream_iterator<std::string>(buffer, delimiter.c_str())); if (!h_data.empty()) buffer << h_data.back(); return buffer.str(); } /** * @copydoc cudf::test::detail::to_string(std::vector<bitmask_type>, size_type, std::string) * * @param indent Indentation for all output. See comment in `to_strings` for * a detailed description. */ std::string to_string(std::vector<bitmask_type> const& null_mask, size_type null_mask_size, std::string const& indent) { std::ostringstream buffer; buffer << indent; for (int idx = null_mask_size - 1; idx >= 0; idx--) { buffer << (cudf::bit_is_set(null_mask.data(), idx) ? "1" : "0"); } return buffer.str(); } } // namespace detail std::vector<std::string> to_strings(cudf::column_view const& col) { return detail::to_strings(col); } std::string to_string(cudf::column_view const& col, std::string const& delimiter) { return detail::to_string(col, delimiter); } std::string to_string(std::vector<bitmask_type> const& null_mask, size_type null_mask_size) { return detail::to_string(null_mask, null_mask_size); } void print(cudf::column_view const& col, std::ostream& os) { os << to_string(col, ",") << std::endl; } } // namespace cudf::test
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/utilities/table_utilities.cu
/* * Copyright (c) 2019-2022, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/column_utilities.hpp> #include <cudf_test/table_utilities.hpp> #include <gmock/gmock.h> namespace cudf::test::detail { void expect_table_properties_equal(cudf::table_view lhs, cudf::table_view rhs) { EXPECT_EQ(lhs.num_rows(), rhs.num_rows()); EXPECT_EQ(lhs.num_columns(), rhs.num_columns()); } void expect_tables_equal(cudf::table_view lhs, cudf::table_view rhs) { expect_table_properties_equal(lhs, rhs); for (auto i = 0; i < lhs.num_columns(); ++i) { cudf::test::detail::expect_columns_equal(lhs.column(i), rhs.column(i)); } } /** * @copydoc cudf::test::expect_tables_equivalent */ void expect_tables_equivalent(cudf::table_view lhs, cudf::table_view rhs) { auto num_columns = lhs.num_columns(); for (auto i = 0; i < num_columns; ++i) { cudf::test::detail::expect_columns_equivalent(lhs.column(i), rhs.column(i)); } } } // namespace cudf::test::detail
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/utilities/identify_stream_usage.cpp
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/detail/utilities/stacktrace.hpp> #include <rmm/cuda_stream.hpp> #include <rmm/cuda_stream_view.hpp> #include <cuda_runtime.h> #include <cstdlib> #include <cstring> #include <cxxabi.h> #include <dlfcn.h> #include <execinfo.h> #include <iostream> #include <stdexcept> #include <string> #include <unordered_map> // We control whether to override cudf::test::get_default_stream or // cudf::get_default_stream with a compile-time flag. Thesee are the two valid // options: // 1. STREAM_MODE_TESTING=OFF: In this mode, cudf::get_default_stream will // return a custom stream and stream_is_invalid will return true if any CUDA // API is called using any of CUDA's default stream constants // (cudaStreamLegacy, cudaStreamDefault, or cudaStreamPerThread). This check // is sufficient to ensure that cudf is using cudf::get_default_stream // everywhere internally rather than implicitly using stream 0, // cudaStreamDefault, cudaStreamLegacy, thrust execution policies, etc. It // is not sufficient to guarantee a stream-ordered API because it will not // identify places in the code that use cudf::get_default_stream instead of // properly forwarding along a user-provided stream. // 2. STREAM_MODE_TESTING=ON: In this mode, cudf::test::get_default_stream // returns a custom stream and stream_is_invalid returns true if any CUDA // API is called using any stream other than cudf::test::get_default_stream. // This is a necessary and sufficient condition to ensure that libcudf is // properly passing streams through all of its (tested) APIs. namespace cudf { #ifdef STREAM_MODE_TESTING namespace test { #endif rmm::cuda_stream_view const get_default_stream() { static rmm::cuda_stream stream{}; return {stream}; } #ifdef STREAM_MODE_TESTING } // namespace test #endif } // namespace cudf bool stream_is_invalid(cudaStream_t stream) { #ifdef STREAM_MODE_TESTING // In this mode the _only_ valid stream is the one returned by cudf::test::get_default_stream. return (stream != cudf::test::get_default_stream().value()); #else // We explicitly list the possibilities rather than using // `cudf::get_default_stream().value()` because there is no guarantee that // `thrust::device` and the default value of // `cudf::get_default_stream().value()` are actually the same. At present, the // former is `cudaStreamLegacy` while the latter is 0. return (stream == cudaStreamDefault) || (stream == cudaStreamLegacy) || (stream == cudaStreamPerThread); #endif } /** * @brief Print a backtrace and raise an error if stream is a default stream. */ void check_stream_and_error(cudaStream_t stream) { if (stream_is_invalid(stream)) { // Exclude the current function from stacktrace. std::cout << cudf::detail::get_stacktrace(cudf::detail::capture_last_stackframe::NO) << std::endl; char const* env_stream_error_mode{std::getenv("GTEST_CUDF_STREAM_ERROR_MODE")}; if (env_stream_error_mode && !strcmp(env_stream_error_mode, "print")) { std::cout << "cudf_identify_stream_usage found unexpected stream!" << std::endl; } else { throw std::runtime_error("cudf_identify_stream_usage found unexpected stream!"); } } } /** * @brief Container for CUDA APIs that have been overloaded using DEFINE_OVERLOAD. * * This variable must be initialized before everything else. * * @see find_originals for a description of the priorities */ __attribute__((init_priority(1001))) std::unordered_map<std::string, void*> originals; /** * @brief Macro for generating functions to override existing CUDA functions. * * Define a new function with the provided signature that checks the used * stream and raises an exception if it is one of CUDA's default streams. If * not, the new function forwards all arguments to the original function. * * Note that since this only defines the function, we do not need default * parameter values since those will be provided by the original declarations * in CUDA itself. * * @see find_originals for a description of the priorities * * @param function The function to overload. * @param signature The function signature (must include names, not just types). * @parameter arguments The function arguments (names only, no types). */ #define DEFINE_OVERLOAD(function, signature, arguments) \ using function##_t = cudaError_t (*)(signature); \ \ cudaError_t function(signature) \ { \ check_stream_and_error(stream); \ return ((function##_t)originals[#function])(arguments); \ } \ __attribute__((constructor(1002))) void queue_##function() { originals[#function] = nullptr; } /** * @brief Helper macro to define macro arguments that contain a comma. */ #define ARG(...) __VA_ARGS__ // clang-format off /* We need to overload all the functions from the runtime API (assuming that we don't use the driver API) that accept streams. The main webpage for APIs is https://docs.nvidia.com/cuda/cuda-runtime-api/modules.html#modules. Here are the modules containing any APIs using streams as of 9/20/2022: - https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__STREAM.html - https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__EVENT.html#group__CUDART__EVENT - Done - https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__EXTRES__INTEROP.html#group__CUDART__EXTRES__INTEROP - https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__EXECUTION.html#group__CUDART__EXECUTION - Done - https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__MEMORY.html#group__CUDART__MEMORY - Done - https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__MEMORY__POOLS.html#group__CUDART__MEMORY__POOLS - Done - https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__OPENGL__DEPRECATED.html#group__CUDART__OPENGL__DEPRECATED - https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__EGL.html#group__CUDART__EGL - https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__INTEROP.html#group__CUDART__INTEROP - https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__GRAPH.html#group__CUDART__GRAPH - https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__HIGHLEVEL.html#group__CUDART__HIGHLEVEL */ // clang-format on // Event APIS: // https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__EVENT.html#group__CUDART__EVENT DEFINE_OVERLOAD(cudaEventRecord, ARG(cudaEvent_t event, cudaStream_t stream), ARG(event, stream)); DEFINE_OVERLOAD(cudaEventRecordWithFlags, ARG(cudaEvent_t event, cudaStream_t stream, unsigned int flags), ARG(event, stream, flags)); // Execution APIS: // https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__EXECUTION.html#group__CUDART__EXECUTION DEFINE_OVERLOAD(cudaLaunchKernel, ARG(void const* func, dim3 gridDim, dim3 blockDim, void** args, size_t sharedMem, cudaStream_t stream), ARG(func, gridDim, blockDim, args, sharedMem, stream)); DEFINE_OVERLOAD(cudaLaunchCooperativeKernel, ARG(void const* func, dim3 gridDim, dim3 blockDim, void** args, size_t sharedMem, cudaStream_t stream), ARG(func, gridDim, blockDim, args, sharedMem, stream)); DEFINE_OVERLOAD(cudaLaunchHostFunc, ARG(cudaStream_t stream, cudaHostFn_t fn, void* userData), ARG(stream, fn, userData)); // Memory transfer APIS: // https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__MEMORY.html#group__CUDART__MEMORY DEFINE_OVERLOAD(cudaMemPrefetchAsync, ARG(void const* devPtr, size_t count, int dstDevice, cudaStream_t stream), ARG(devPtr, count, dstDevice, stream)); DEFINE_OVERLOAD(cudaMemcpy2DAsync, ARG(void* dst, size_t dpitch, void const* src, size_t spitch, size_t width, size_t height, cudaMemcpyKind kind, cudaStream_t stream), ARG(dst, dpitch, src, spitch, width, height, kind, stream)); DEFINE_OVERLOAD(cudaMemcpy2DFromArrayAsync, ARG(void* dst, size_t dpitch, cudaArray_const_t src, size_t wOffset, size_t hOffset, size_t width, size_t height, cudaMemcpyKind kind, cudaStream_t stream), ARG(dst, dpitch, src, wOffset, hOffset, width, height, kind, stream)); DEFINE_OVERLOAD(cudaMemcpy2DToArrayAsync, ARG(cudaArray_t dst, size_t wOffset, size_t hOffset, void const* src, size_t spitch, size_t width, size_t height, cudaMemcpyKind kind, cudaStream_t stream), ARG(dst, wOffset, hOffset, src, spitch, width, height, kind, stream)); DEFINE_OVERLOAD(cudaMemcpy3DAsync, ARG(cudaMemcpy3DParms const* p, cudaStream_t stream), ARG(p, stream)); DEFINE_OVERLOAD(cudaMemcpy3DPeerAsync, ARG(cudaMemcpy3DPeerParms const* p, cudaStream_t stream), ARG(p, stream)); DEFINE_OVERLOAD( cudaMemcpyAsync, ARG(void* dst, void const* src, size_t count, cudaMemcpyKind kind, cudaStream_t stream), ARG(dst, src, count, kind, stream)); DEFINE_OVERLOAD(cudaMemcpyFromSymbolAsync, ARG(void* dst, void const* symbol, size_t count, size_t offset, cudaMemcpyKind kind, cudaStream_t stream), ARG(dst, symbol, count, offset, kind, stream)); DEFINE_OVERLOAD(cudaMemcpyToSymbolAsync, ARG(void const* symbol, void const* src, size_t count, size_t offset, cudaMemcpyKind kind, cudaStream_t stream), ARG(symbol, src, count, offset, kind, stream)); DEFINE_OVERLOAD( cudaMemset2DAsync, ARG(void* devPtr, size_t pitch, int value, size_t width, size_t height, cudaStream_t stream), ARG(devPtr, pitch, value, width, height, stream)); DEFINE_OVERLOAD( cudaMemset3DAsync, ARG(cudaPitchedPtr pitchedDevPtr, int value, cudaExtent extent, cudaStream_t stream), ARG(pitchedDevPtr, value, extent, stream)); DEFINE_OVERLOAD(cudaMemsetAsync, ARG(void* devPtr, int value, size_t count, cudaStream_t stream), ARG(devPtr, value, count, stream)); // Memory allocation APIS: // https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__MEMORY__POOLS.html#group__CUDART__MEMORY__POOLS DEFINE_OVERLOAD(cudaFreeAsync, ARG(void* devPtr, cudaStream_t stream), ARG(devPtr, stream)); DEFINE_OVERLOAD(cudaMallocAsync, ARG(void** devPtr, size_t size, cudaStream_t stream), ARG(devPtr, size, stream)); DEFINE_OVERLOAD(cudaMallocFromPoolAsync, ARG(void** ptr, size_t size, cudaMemPool_t memPool, cudaStream_t stream), ARG(ptr, size, memPool, stream)); /** * @brief Function to collect all the original CUDA symbols corresponding to overloaded functions. * * Note on priorities: * - `originals` must be initialized first, so it is 1001. * - The function names must be added to originals next in the macro, so those are 1002. * - Finally, this function actually finds the original symbols so it is 1003. */ __attribute__((constructor(1003))) void find_originals() { for (auto it : originals) { originals[it.first] = dlsym(RTLD_NEXT, it.first.data()); } }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/utilities/base_fixture.cpp
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * Licensed 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 <cudf/types.hpp> namespace cudf { namespace test { namespace detail { /** * @copydoc cudf::test::detail::random_generator_incrementing_seed() */ uint64_t random_generator_incrementing_seed() { static uint64_t seed = 0; return ++seed; } } // namespace detail } // namespace test } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/utilities/default_stream.cpp
/* * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/utilities/default_stream.hpp> #include <cudf_test/default_stream.hpp> namespace cudf { namespace test { rmm::cuda_stream_view const get_default_stream() { return cudf::get_default_stream(); } } // namespace test } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/utilities/column_utilities.cu
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/debug_utilities.hpp> #include <cudf_test/default_stream.hpp> #include <cudf/column/column_view.hpp> #include <cudf/copying.hpp> #include <cudf/detail/get_value.cuh> #include <cudf/detail/iterator.cuh> #include <cudf/detail/utilities/vector_factories.hpp> #include <cudf/lists/list_view.hpp> #include <cudf/structs/struct_view.hpp> #include <cudf/table/experimental/row_operators.cuh> #include <cudf/table/table_device_view.cuh> #include <cudf/utilities/default_stream.hpp> #include <cudf/utilities/type_dispatcher.hpp> #include <rmm/exec_policy.hpp> #include <thrust/copy.h> #include <thrust/distance.h> #include <thrust/equal.h> #include <thrust/execution_policy.h> #include <thrust/generate.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/iterator/transform_iterator.h> #include <thrust/logical.h> #include <thrust/reduce.h> #include <thrust/remove.h> #include <thrust/scan.h> #include <thrust/scatter.h> #include <thrust/sequence.h> #include <thrust/transform.h> #include <numeric> #include <sstream> namespace cudf { namespace test { namespace { std::unique_ptr<column> generate_all_row_indices(size_type num_rows) { auto indices = cudf::make_fixed_width_column( data_type{type_id::INT32}, num_rows, mask_state::UNALLOCATED, cudf::test::get_default_stream()); thrust::sequence(rmm::exec_policy(cudf::test::get_default_stream()), indices->mutable_view().begin<size_type>(), indices->mutable_view().end<size_type>(), 0); return indices; } // generate the rows indices that should be checked for the child column of a list column. // // - if we are just checking for equivalence, we can skip any rows that are nulls. this allows // things like non-empty rows that have been nullified after creation. they may actually contain // values, but since the row is null they don't matter for equivalency. // // - if we are checking for exact equality, we need to check all rows. // // This allows us to differentiate between: // // List<int32_t>: // Length : 1 // Offsets : 0, 4 // Null count: 1 // 0 // 0, 1, 2, 3 // // List<int32_t>: // Length : 1 // Offsets : 0, 0 // Null count: 1 // 0 // std::unique_ptr<column> generate_child_row_indices(lists_column_view const& c, column_view const& row_indices, bool check_exact_equality) { // if we are checking for exact equality, we should be checking for "unsanitized" data that may // be hiding underneath nulls. so check all rows instead of just non-null rows if (check_exact_equality) { return generate_all_row_indices(c.get_sliced_child(cudf::test::get_default_stream()).size()); } // Example input // List<int32_t>: // Length : 7 // Offsets : 0, 3, 6, 8, 11, 14, 16, 19 // | | <-- non-null input rows // Null count: 5 // 0010100 // 1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 7, 7, 7 // | | | | | <-- child rows of non-null rows // // Desired output: [6, 7, 11, 12, 13] // compute total # of child row indices we will be emitting. auto row_size_iter = cudf::detail::make_counting_transform_iterator( 0, [row_indices = row_indices.begin<size_type>(), validity = c.null_mask(), offsets = c.offsets().begin<size_type>(), offset = c.offset()] __device__(int index) { // both null mask and offsets data are not pre-sliced. so we need to add the column offset to // every incoming index. auto const true_index = row_indices[index] + offset; return !validity || cudf::bit_is_set(validity, true_index) ? (offsets[true_index + 1] - offsets[true_index]) : 0; }); auto const output_size = thrust::reduce(rmm::exec_policy(cudf::test::get_default_stream()), row_size_iter, row_size_iter + row_indices.size()); // no output. done. auto result = cudf::make_fixed_width_column(data_type{type_id::INT32}, output_size, mask_state::UNALLOCATED); if (output_size == 0) { return result; } // for all input rows, what position in the output column they will start at. // // output_row_start = [0, 0, 0, 2, 2, 5, 5] // | | <-- non-null input rows // auto output_row_start = cudf::make_fixed_width_column( data_type{type_id::INT32}, row_indices.size(), mask_state::UNALLOCATED); thrust::exclusive_scan(rmm::exec_policy(cudf::test::get_default_stream()), row_size_iter, row_size_iter + row_indices.size(), output_row_start->mutable_view().begin<size_type>()); // fill result column with 1s // // result = [1, 1, 1, 1, 1] // thrust::generate(rmm::exec_policy(cudf::test::get_default_stream()), result->mutable_view().begin<size_type>(), result->mutable_view().end<size_type>(), [] __device__() { return 1; }); // scatter the output row positions into result buffer // // result = [6, 1, 11, 1, 1] // auto output_row_iter = cudf::detail::make_counting_transform_iterator( 0, [row_indices = row_indices.begin<size_type>(), offsets = c.offsets().begin<size_type>(), offset = c.offset(), first_offset = cudf::detail::get_value<size_type>( c.offsets(), c.offset(), cudf::test::get_default_stream())] __device__(int index) { auto const true_index = row_indices[index] + offset; return offsets[true_index] - first_offset; }); thrust::scatter_if(rmm::exec_policy(cudf::test::get_default_stream()), output_row_iter, output_row_iter + row_indices.size(), output_row_start->view().begin<size_type>(), row_size_iter, result->mutable_view().begin<size_type>(), [] __device__(auto row_size) { return row_size != 0; }); // generate keys for each output row // // result = [1, 1, 2, 2, 2] // auto keys = cudf::make_fixed_width_column(data_type{type_id::INT32}, output_size, mask_state::UNALLOCATED); thrust::generate(rmm::exec_policy(cudf::test::get_default_stream()), keys->mutable_view().begin<size_type>(), keys->mutable_view().end<size_type>(), [] __device__() { return 0; }); thrust::scatter_if(rmm::exec_policy(cudf::test::get_default_stream()), row_size_iter, row_size_iter + row_indices.size(), output_row_start->view().begin<size_type>(), row_size_iter, keys->mutable_view().begin<size_type>(), [] __device__(auto row_size) { return row_size != 0; }); thrust::inclusive_scan(rmm::exec_policy(cudf::test::get_default_stream()), keys->view().begin<size_type>(), keys->view().end<size_type>(), keys->mutable_view().begin<size_type>()); // scan by key to generate final child row indices. // input // result = [6, 1, 11, 1, 1] // keys = [1, 1, 2, 2, 2] // // output // result = [6, 7, 11, 12, 13] // thrust::inclusive_scan_by_key(rmm::exec_policy(cudf::test::get_default_stream()), keys->view().begin<size_type>(), keys->view().end<size_type>(), result->view().begin<size_type>(), result->mutable_view().begin<size_type>()); return result; } #define PROP_EXPECT_EQ(a, b) \ do { \ if (verbosity == debug_output_level::QUIET) { \ if (a != b) { return false; } \ } else { \ EXPECT_EQ(a, b); \ if (a != b) { \ if (verbosity == debug_output_level::FIRST_ERROR) { \ return false; \ } else { \ result = false; \ } \ } \ } \ } while (0) template <bool check_exact_equality> struct column_property_comparator { bool types_equivalent(cudf::data_type const& lhs, cudf::data_type const& rhs) { return is_fixed_point(lhs) ? lhs.id() == rhs.id() : lhs == rhs; } size_type count_nulls(cudf::column_view const& c, cudf::column_view const& row_indices) { auto validity_iter = cudf::detail::make_counting_transform_iterator( 0, [row_indices = row_indices.begin<size_type>(), validity = c.null_mask(), offset = c.offset()] __device__(int index) { // both null mask and offsets data are not pre-sliced. so we need to add the column offset // to every incoming index. auto const true_index = row_indices[index] + offset; return !validity || cudf::bit_is_set(validity, true_index) ? 0 : 1; }); return thrust::reduce(rmm::exec_policy(cudf::test::get_default_stream()), validity_iter, validity_iter + row_indices.size()); } bool compare_common(cudf::column_view const& lhs, cudf::column_view const& rhs, cudf::column_view const& lhs_row_indices, cudf::column_view const& rhs_row_indices, debug_output_level verbosity) { bool result = true; if (check_exact_equality) { PROP_EXPECT_EQ(lhs.type(), rhs.type()); } else { PROP_EXPECT_EQ(types_equivalent(lhs.type(), rhs.type()), true); } auto const lhs_size = check_exact_equality ? lhs.size() : lhs_row_indices.size(); auto const rhs_size = check_exact_equality ? rhs.size() : rhs_row_indices.size(); PROP_EXPECT_EQ(lhs_size, rhs_size); if (lhs_size > 0 && check_exact_equality) { PROP_EXPECT_EQ(lhs.nullable(), rhs.nullable()); } // DISCUSSION: does this make sense, semantically? auto const lhs_null_count = check_exact_equality ? lhs.null_count() : count_nulls(lhs, lhs_row_indices); auto const rhs_null_count = check_exact_equality ? rhs.null_count() : count_nulls(rhs, rhs_row_indices); PROP_EXPECT_EQ(lhs_null_count, rhs_null_count); // equivalent, but not exactly equal columns can have a different number of children if their // sizes are both 0. Specifically, empty string columns may or may not have children. if (check_exact_equality || (lhs.size() > 0 && lhs.null_count() < lhs.size())) { PROP_EXPECT_EQ(lhs.num_children(), rhs.num_children()); } return result; } template <typename T, std::enable_if_t<!std::is_same_v<T, cudf::list_view> && !std::is_same_v<T, cudf::struct_view>>* = nullptr> bool operator()(cudf::column_view const& lhs, cudf::column_view const& rhs, cudf::column_view const& lhs_row_indices, cudf::column_view const& rhs_row_indices, debug_output_level verbosity) { return compare_common(lhs, rhs, lhs_row_indices, rhs_row_indices, verbosity); } template <typename T, std::enable_if_t<std::is_same_v<T, cudf::list_view>>* = nullptr> bool operator()(cudf::column_view const& lhs, cudf::column_view const& rhs, cudf::column_view const& lhs_row_indices, cudf::column_view const& rhs_row_indices, debug_output_level verbosity) { if (!compare_common(lhs, rhs, lhs_row_indices, rhs_row_indices, verbosity)) { return false; } cudf::lists_column_view lhs_l(lhs); cudf::lists_column_view rhs_l(rhs); // recurse // note: if a column is all nulls (and we are checking for exact equality) or otherwise empty, // no indices are generated and no recursion happens auto lhs_child_indices = generate_child_row_indices(lhs_l, lhs_row_indices, check_exact_equality); if (lhs_child_indices->size() > 0) { auto lhs_child = lhs_l.get_sliced_child(cudf::test::get_default_stream()); auto rhs_child = rhs_l.get_sliced_child(cudf::test::get_default_stream()); auto rhs_child_indices = generate_child_row_indices(rhs_l, rhs_row_indices, check_exact_equality); return cudf::type_dispatcher(lhs_child.type(), column_property_comparator<check_exact_equality>{}, lhs_child, rhs_child, *lhs_child_indices, *rhs_child_indices, verbosity); } return true; } template <typename T, std::enable_if_t<std::is_same_v<T, cudf::struct_view>>* = nullptr> bool operator()(cudf::column_view const& lhs, cudf::column_view const& rhs, cudf::column_view const& lhs_row_indices, cudf::column_view const& rhs_row_indices, debug_output_level verbosity) { if (!compare_common(lhs, rhs, lhs_row_indices, rhs_row_indices, verbosity)) { return false; } structs_column_view l_scv(lhs); structs_column_view r_scv(rhs); for (size_type i = 0; i < lhs.num_children(); i++) { column_view lhs_child = l_scv.get_sliced_child(i, cudf::test::get_default_stream()); column_view rhs_child = r_scv.get_sliced_child(i, cudf::test::get_default_stream()); if (!cudf::type_dispatcher(lhs_child.type(), column_property_comparator<check_exact_equality>{}, lhs_child, rhs_child, lhs_row_indices, rhs_row_indices, verbosity)) { return false; } } return true; } }; template <typename DeviceComparator> class corresponding_rows_unequal { public: corresponding_rows_unequal(column_device_view lhs_row_indices_, column_device_view rhs_row_indices_, size_type /*fp_ulps*/, DeviceComparator comp_, column_device_view /*lhs*/, column_device_view /*rhs*/) : lhs_row_indices(lhs_row_indices_), rhs_row_indices(rhs_row_indices_), comp(comp_) { } __device__ bool operator()(size_type index) { using cudf::experimental::row::lhs_index_type; using cudf::experimental::row::rhs_index_type; return !comp(lhs_index_type{lhs_row_indices.element<size_type>(index)}, rhs_index_type{rhs_row_indices.element<size_type>(index)}); } column_device_view lhs_row_indices; column_device_view rhs_row_indices; DeviceComparator comp; }; template <typename DeviceComparator> class corresponding_rows_not_equivalent { column_device_view lhs_row_indices; column_device_view rhs_row_indices; size_type const fp_ulps; DeviceComparator comp; column_device_view lhs; column_device_view rhs; public: corresponding_rows_not_equivalent(column_device_view lhs_row_indices_, column_device_view rhs_row_indices_, size_type fp_ulps_, DeviceComparator comp_, column_device_view lhs_, column_device_view rhs_) : lhs_row_indices(lhs_row_indices_), rhs_row_indices(rhs_row_indices_), fp_ulps(fp_ulps_), comp(comp_), lhs(lhs_), rhs(rhs_) { } struct typed_element_not_equivalent { template <typename T> __device__ std::enable_if_t<std::is_floating_point_v<T>, bool> operator()( column_device_view const& lhs, column_device_view const& rhs, size_type lhs_index, size_type rhs_index, size_type fp_ulps) { if (lhs.is_valid(lhs_index) and rhs.is_valid(rhs_index)) { T const x = lhs.element<T>(lhs_index); T const y = rhs.element<T>(rhs_index); // Must handle inf and nan separately if (std::isinf(x) || std::isinf(y)) { return x != y; // comparison of (inf==inf) returns true } else if (std::isnan(x) || std::isnan(y)) { return std::isnan(x) != std::isnan(y); // comparison of (nan==nan) returns false } else { T const abs_x_minus_y = std::abs(x - y); return abs_x_minus_y >= std::numeric_limits<T>::min() && abs_x_minus_y > std::numeric_limits<T>::epsilon() * std::abs(x + y) * fp_ulps; } } else { // if either is null, then the inequality was checked already return true; } } template <typename T, typename... Args> __device__ std::enable_if_t<not std::is_floating_point_v<T>, bool> operator()(Args...) { // Non-floating point inequality is checked already return true; } }; __device__ bool operator()(size_type index) { using cudf::experimental::row::lhs_index_type; using cudf::experimental::row::rhs_index_type; auto const lhs_index = lhs_row_indices.element<size_type>(index); auto const rhs_index = rhs_row_indices.element<size_type>(index); if (not comp(lhs_index_type{lhs_index}, rhs_index_type{rhs_index})) { return type_dispatcher( lhs.type(), typed_element_not_equivalent{}, lhs, rhs, lhs_index, rhs_index, fp_ulps); } return false; } }; // Stringify the inconsistent values resulted from the comparison of two columns element-wise std::string stringify_column_differences(cudf::device_span<int const> differences, column_view const& lhs, column_view const& rhs, column_view const& lhs_row_indices, column_view const& rhs_row_indices, debug_output_level verbosity, int depth) { CUDF_EXPECTS(not differences.empty(), "Shouldn't enter this function if `differences` is empty"); std::string const depth_str = depth > 0 ? "depth " + std::to_string(depth) + '\n' : ""; // move the differences to the host. auto h_differences = cudf::detail::make_host_vector_sync(differences, cudf::test::get_default_stream()); if (verbosity == debug_output_level::ALL_ERRORS) { std::ostringstream buffer; buffer << depth_str << "differences:" << std::endl; auto source_table = cudf::table_view({lhs, rhs}); auto diff_column = fixed_width_column_wrapper<int32_t>(h_differences.begin(), h_differences.end()); auto diff_table = cudf::gather(source_table, diff_column); // Need to pull back the differences auto const h_left_strings = to_strings(diff_table->get_column(0)); auto const h_right_strings = to_strings(diff_table->get_column(1)); for (size_t i = 0; i < h_differences.size(); ++i) buffer << depth_str << "lhs[" << h_differences[i] << "] = " << h_left_strings[i] << ", rhs[" << h_differences[i] << "] = " << h_right_strings[i] << std::endl; return buffer.str(); } else { auto const index = h_differences[0]; // only stringify first difference auto const lhs_index = cudf::detail::get_value<size_type>(lhs_row_indices, index, cudf::test::get_default_stream()); auto const rhs_index = cudf::detail::get_value<size_type>(rhs_row_indices, index, cudf::test::get_default_stream()); auto diff_lhs = cudf::slice(lhs, {lhs_index, lhs_index + 1}).front(); auto diff_rhs = cudf::slice(rhs, {rhs_index, rhs_index + 1}).front(); return depth_str + "first difference: " + "lhs[" + std::to_string(index) + "] = " + to_string(diff_lhs, "") + ", rhs[" + std::to_string(index) + "] = " + to_string(diff_rhs, ""); } } // non-nested column types template <typename T, bool check_exact_equality> struct column_comparator_impl { bool operator()(column_view const& lhs, column_view const& rhs, column_view const& lhs_row_indices, column_view const& rhs_row_indices, debug_output_level verbosity, size_type fp_ulps, int depth) { auto d_lhs_row_indices = cudf::column_device_view::create(lhs_row_indices, cudf::test::get_default_stream()); auto d_rhs_row_indices = cudf::column_device_view::create(rhs_row_indices, cudf::test::get_default_stream()); auto d_lhs = cudf::column_device_view::create(lhs, cudf::test::get_default_stream()); auto d_rhs = cudf::column_device_view::create(rhs, cudf::test::get_default_stream()); auto lhs_tview = table_view{{lhs}}; auto rhs_tview = table_view{{rhs}}; auto const comparator = cudf::experimental::row::equality::two_table_comparator{ lhs_tview, rhs_tview, cudf::test::get_default_stream()}; auto const has_nulls = cudf::has_nulls(lhs_tview) or cudf::has_nulls(rhs_tview); auto const device_comparator = comparator.equal_to<false>(cudf::nullate::DYNAMIC{has_nulls}); using ComparatorType = std::conditional_t<check_exact_equality, corresponding_rows_unequal<decltype(device_comparator)>, corresponding_rows_not_equivalent<decltype(device_comparator)>>; auto differences = rmm::device_uvector<int>( lhs_row_indices.size(), cudf::test::get_default_stream()); // worst case: everything different auto input_iter = thrust::make_counting_iterator(0); auto diff_map = rmm::device_uvector<bool>(lhs_row_indices.size(), cudf::test::get_default_stream()); thrust::transform( rmm::exec_policy(cudf::test::get_default_stream()), input_iter, input_iter + lhs_row_indices.size(), diff_map.begin(), ComparatorType( *d_lhs_row_indices, *d_rhs_row_indices, fp_ulps, device_comparator, *d_lhs, *d_rhs)); auto diff_iter = thrust::copy_if(rmm::exec_policy(cudf::test::get_default_stream()), input_iter, input_iter + lhs_row_indices.size(), diff_map.begin(), differences.begin(), thrust::identity<bool>{}); differences.resize(thrust::distance(differences.begin(), diff_iter), cudf::test::get_default_stream()); // shrink back down if (not differences.is_empty()) { if (verbosity != debug_output_level::QUIET) { // GTEST_FAIL() does a return that conflicts with our return type. so hide it in a lambda. [&]() { GTEST_FAIL() << stringify_column_differences( differences, lhs, rhs, lhs_row_indices, rhs_row_indices, verbosity, depth); }(); } return false; } return true; } }; // forward declaration for nested-type recursion. template <bool check_exact_equality> struct column_comparator; // specialization for list columns template <bool check_exact_equality> struct column_comparator_impl<list_view, check_exact_equality> { bool operator()(column_view const& lhs, column_view const& rhs, column_view const& lhs_row_indices, column_view const& rhs_row_indices, debug_output_level verbosity, size_type fp_ulps, int depth) { lists_column_view lhs_l(lhs); lists_column_view rhs_l(rhs); CUDF_EXPECTS(lhs_row_indices.size() == rhs_row_indices.size(), "List column size mismatch"); if (lhs_row_indices.is_empty()) { return true; } // worst case - everything is different rmm::device_uvector<int> differences(lhs_row_indices.size(), cudf::test::get_default_stream()); // compare offsets, taking slicing into account // left side size_type lhs_shift = cudf::detail::get_value<size_type>( lhs_l.offsets(), lhs_l.offset(), cudf::test::get_default_stream()); auto lhs_offsets = thrust::make_transform_iterator( lhs_l.offsets().begin<size_type>() + lhs_l.offset(), [lhs_shift] __device__(size_type offset) { return offset - lhs_shift; }); auto lhs_valids = thrust::make_transform_iterator( thrust::make_counting_iterator(0), [mask = lhs_l.null_mask(), offset = lhs_l.offset()] __device__(size_type index) { return mask == nullptr ? true : cudf::bit_is_set(mask, index + offset); }); // right side size_type rhs_shift = cudf::detail::get_value<size_type>( rhs_l.offsets(), rhs_l.offset(), cudf::test::get_default_stream()); auto rhs_offsets = thrust::make_transform_iterator( rhs_l.offsets().begin<size_type>() + rhs_l.offset(), [rhs_shift] __device__(size_type offset) { return offset - rhs_shift; }); auto rhs_valids = thrust::make_transform_iterator( thrust::make_counting_iterator(0), [mask = rhs_l.null_mask(), offset = rhs_l.offset()] __device__(size_type index) { return mask == nullptr ? true : cudf::bit_is_set(mask, index + offset); }); // when checking for equivalency, we can't compare offset values directly, we can only // compare lengths of the rows, and only if valid. as a concrete example, you could have two // equivalent columns with the following data: // // column A // offsets = [0, 3, 5, 7] // validity = [0, 1, 1, 1] // // column B // offsets = [0, 0, 2, 4] // validity = [0, 1, 1, 1] // // Row 0 in column A happens to have a positive length, even though the row is null, but column // B does not. So the offsets for the remaining valid rows are fundamentally different even // though the row lengths are the same. // auto input_iter = thrust::make_counting_iterator(0); auto diff_iter = thrust::copy_if( rmm::exec_policy(cudf::test::get_default_stream()), input_iter, input_iter + lhs_row_indices.size(), differences.begin(), [lhs_offsets, rhs_offsets, lhs_valids, rhs_valids, lhs_indices = lhs_row_indices.begin<size_type>(), rhs_indices = rhs_row_indices.begin<size_type>()] __device__(size_type index) { auto const lhs_index = lhs_indices[index]; auto const rhs_index = rhs_indices[index]; // check for validity match if (lhs_valids[lhs_index] != rhs_valids[rhs_index]) { return true; } // if the row is valid, check that the length of the list is the same. do this // for both the equivalency and exact equality checks. if (lhs_valids[lhs_index] && ((lhs_offsets[lhs_index + 1] - lhs_offsets[lhs_index]) != (rhs_offsets[rhs_index + 1] - rhs_offsets[rhs_index]))) { return true; } // if validity matches -and- is false, we can ignore the actual offset values. this // is technically not checking "equal()", but it's how the non-list code path handles it if (!lhs_valids[lhs_index]) { return false; } // if checking exact equality, compare the actual offset values if (check_exact_equality && lhs_offsets[lhs_index] != rhs_offsets[rhs_index]) { return true; } return false; }); differences.resize(thrust::distance(differences.begin(), diff_iter), cudf::test::get_default_stream()); // shrink back down if (not differences.is_empty()) { if (verbosity != debug_output_level::QUIET) { // GTEST_FAIL() does a return that conflicts with our return type. so hide it in a lambda. [&]() { GTEST_FAIL() << stringify_column_differences( differences, lhs, rhs, lhs_row_indices, rhs_row_indices, verbosity, depth); }(); } return false; } // recurse // note: if a column is all nulls (and we are only checking for equivalence) or otherwise empty, // no indices are generated and no recursion happens auto lhs_child_indices = generate_child_row_indices(lhs_l, lhs_row_indices, check_exact_equality); if (lhs_child_indices->size() > 0) { auto lhs_child = lhs_l.get_sliced_child(cudf::test::get_default_stream()); auto rhs_child = rhs_l.get_sliced_child(cudf::test::get_default_stream()); auto rhs_child_indices = generate_child_row_indices(rhs_l, rhs_row_indices, check_exact_equality); return cudf::type_dispatcher(lhs_child.type(), column_comparator<check_exact_equality>{}, lhs_child, rhs_child, *lhs_child_indices, *rhs_child_indices, verbosity, fp_ulps, depth + 1); } return true; } }; template <bool check_exact_equality> struct column_comparator_impl<struct_view, check_exact_equality> { bool operator()(column_view const& lhs, column_view const& rhs, column_view const& lhs_row_indices, column_view const& rhs_row_indices, debug_output_level verbosity, size_type fp_ulps, int depth) { structs_column_view l_scv(lhs); structs_column_view r_scv(rhs); for (size_type i = 0; i < lhs.num_children(); i++) { column_view lhs_child = l_scv.get_sliced_child(i, cudf::test::get_default_stream()); column_view rhs_child = r_scv.get_sliced_child(i, cudf::test::get_default_stream()); if (!cudf::type_dispatcher(lhs_child.type(), column_comparator<check_exact_equality>{}, lhs_child, rhs_child, lhs_row_indices, rhs_row_indices, verbosity, fp_ulps, depth + 1)) { return false; } } return true; } }; template <bool check_exact_equality> struct column_comparator { template <typename T> bool operator()(column_view const& lhs, column_view const& rhs, column_view const& lhs_row_indices, column_view const& rhs_row_indices, debug_output_level verbosity, size_type fp_ulps, int depth = 0) { // compare properties if (!cudf::type_dispatcher(lhs.type(), column_property_comparator<check_exact_equality>{}, lhs, rhs, lhs_row_indices, rhs_row_indices, verbosity)) { return false; } // compare values column_comparator_impl<T, check_exact_equality> comparator{}; return comparator(lhs, rhs, lhs_row_indices, rhs_row_indices, verbosity, fp_ulps, depth); } }; } // namespace namespace detail { /** * @copydoc cudf::test::expect_column_properties_equal */ bool expect_column_properties_equal(column_view const& lhs, column_view const& rhs, debug_output_level verbosity) { auto lhs_indices = generate_all_row_indices(lhs.size()); auto rhs_indices = generate_all_row_indices(rhs.size()); return cudf::type_dispatcher(lhs.type(), column_property_comparator<true>{}, lhs, rhs, *lhs_indices, *rhs_indices, verbosity); } /** * @copydoc cudf::test::expect_column_properties_equivalent */ bool expect_column_properties_equivalent(column_view const& lhs, column_view const& rhs, debug_output_level verbosity) { auto lhs_indices = generate_all_row_indices(lhs.size()); auto rhs_indices = generate_all_row_indices(rhs.size()); return cudf::type_dispatcher(lhs.type(), column_property_comparator<false>{}, lhs, rhs, *lhs_indices, *rhs_indices, verbosity); } /** * @copydoc cudf::test::expect_columns_equal */ bool expect_columns_equal(cudf::column_view const& lhs, cudf::column_view const& rhs, debug_output_level verbosity) { auto lhs_indices = generate_all_row_indices(lhs.size()); auto rhs_indices = generate_all_row_indices(rhs.size()); return cudf::type_dispatcher(lhs.type(), column_comparator<true>{}, lhs, rhs, *lhs_indices, *rhs_indices, verbosity, cudf::test::default_ulp); } /** * @copydoc cudf::test::expect_columns_equivalent */ bool expect_columns_equivalent(cudf::column_view const& lhs, cudf::column_view const& rhs, debug_output_level verbosity, size_type fp_ulps) { auto lhs_indices = generate_all_row_indices(lhs.size()); auto rhs_indices = generate_all_row_indices(rhs.size()); return cudf::type_dispatcher(lhs.type(), column_comparator<false>{}, lhs, rhs, *lhs_indices, *rhs_indices, verbosity, fp_ulps); } /** * @copydoc cudf::test::expect_equal_buffers */ void expect_equal_buffers(void const* lhs, void const* rhs, std::size_t size_bytes) { if (size_bytes > 0) { EXPECT_NE(nullptr, lhs); EXPECT_NE(nullptr, rhs); } auto typed_lhs = static_cast<char const*>(lhs); auto typed_rhs = static_cast<char const*>(rhs); EXPECT_TRUE(thrust::equal(rmm::exec_policy(cudf::test::get_default_stream()), typed_lhs, typed_lhs + size_bytes, typed_rhs)); } } // namespace detail /** * @copydoc cudf::test::expect_column_empty */ void expect_column_empty(cudf::column_view const& col) { EXPECT_EQ(0, col.size()); EXPECT_EQ(0, col.null_count()); } /** * @copydoc cudf::test::bitmask_to_host */ std::vector<bitmask_type> bitmask_to_host(cudf::column_view const& c) { if (c.nullable()) { auto num_bitmasks = num_bitmask_words(c.size()); std::vector<bitmask_type> host_bitmask(num_bitmasks); if (c.offset() == 0) { CUDF_CUDA_TRY(cudaMemcpy(host_bitmask.data(), c.null_mask(), num_bitmasks * sizeof(bitmask_type), cudaMemcpyDefault)); } else { auto mask = copy_bitmask(c.null_mask(), c.offset(), c.offset() + c.size()); CUDF_CUDA_TRY(cudaMemcpy( host_bitmask.data(), mask.data(), num_bitmasks * sizeof(bitmask_type), cudaMemcpyDefault)); } return host_bitmask; } else { return std::vector<bitmask_type>{}; } } /** * @copydoc cudf::test::validate_host_masks */ bool validate_host_masks(std::vector<bitmask_type> const& expected_mask, std::vector<bitmask_type> const& got_mask, size_type number_of_elements) { return std::all_of(thrust::make_counting_iterator(0), thrust::make_counting_iterator(number_of_elements), [&expected_mask, &got_mask](auto index) { return cudf::bit_is_set(expected_mask.data(), index) == cudf::bit_is_set(got_mask.data(), index); }); } } // namespace test } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/utilities/tdigest_utilities.cu
/* * Copyright (c) 2022-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/column/column_factories.hpp> #include <cudf/concatenate.hpp> #include <cudf/detail/tdigest/tdigest.hpp> #include <cudf/tdigest/tdigest_column_view.hpp> #include <cudf/utilities/default_stream.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/tdigest_utilities.cuh> #include <rmm/exec_policy.hpp> #include <thrust/fill.h> #include <thrust/for_each.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/tuple.h> // for use with groupby and reduction aggregation tests. namespace cudf { namespace test { void tdigest_sample_compare(cudf::tdigest::tdigest_column_view const& tdv, std::vector<expected_value> const& h_expected) { column_view result_mean = tdv.means(); column_view result_weight = tdv.weights(); auto expected_mean = cudf::make_fixed_width_column( data_type{type_id::FLOAT64}, h_expected.size(), mask_state::UNALLOCATED); auto expected_weight = cudf::make_fixed_width_column( data_type{type_id::FLOAT64}, h_expected.size(), mask_state::UNALLOCATED); auto sampled_result_mean = cudf::make_fixed_width_column( data_type{type_id::FLOAT64}, h_expected.size(), mask_state::UNALLOCATED); auto sampled_result_weight = cudf::make_fixed_width_column( data_type{type_id::FLOAT64}, h_expected.size(), mask_state::UNALLOCATED); auto h_expected_src = std::vector<size_type>(h_expected.size()); auto h_expected_mean = std::vector<double>(h_expected.size()); auto h_expected_weight = std::vector<double>(h_expected.size()); { auto iter = thrust::make_counting_iterator(0); std::for_each_n(iter, h_expected.size(), [&](size_type const index) { h_expected_src[index] = thrust::get<0>(h_expected[index]); h_expected_mean[index] = thrust::get<1>(h_expected[index]); h_expected_weight[index] = thrust::get<2>(h_expected[index]); }); } auto d_expected_src = cudf::detail::make_device_uvector_async( h_expected_src, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto d_expected_mean = cudf::detail::make_device_uvector_async( h_expected_mean, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto d_expected_weight = cudf::detail::make_device_uvector_async( h_expected_weight, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); auto iter = thrust::make_counting_iterator(0); thrust::for_each( rmm::exec_policy(cudf::get_default_stream()), iter, iter + h_expected.size(), [expected_src_in = d_expected_src.data(), expected_mean_in = d_expected_mean.data(), expected_weight_in = d_expected_weight.data(), expected_mean = expected_mean->mutable_view().begin<double>(), expected_weight = expected_weight->mutable_view().begin<double>(), result_mean = result_mean.begin<double>(), result_weight = result_weight.begin<double>(), sampled_result_mean = sampled_result_mean->mutable_view().begin<double>(), sampled_result_weight = sampled_result_weight->mutable_view().begin<double>()] __device__(size_type index) { expected_mean[index] = expected_mean_in[index]; expected_weight[index] = expected_weight_in[index]; auto const src_index = expected_src_in[index]; sampled_result_mean[index] = result_mean[src_index]; sampled_result_weight[index] = result_weight[src_index]; }); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*expected_mean, *sampled_result_mean); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*expected_weight, *sampled_result_weight); } std::unique_ptr<column> make_expected_tdigest_column(std::vector<expected_tdigest> const& groups) { std::vector<std::unique_ptr<column>> tdigests; // make an individual digest auto make_digest = [&](expected_tdigest const& tdigest) { std::vector<std::unique_ptr<column>> inner_children; inner_children.push_back(std::make_unique<cudf::column>(tdigest.mean)); inner_children.push_back(std::make_unique<cudf::column>(tdigest.weight)); // tdigest struct auto tdigests = cudf::make_structs_column(tdigest.mean.size(), std::move(inner_children), 0, {}); std::vector<size_type> h_offsets{0, tdigest.mean.size()}; auto offsets = cudf::make_fixed_width_column(data_type{type_id::INT32}, 2, mask_state::UNALLOCATED); CUDF_CUDA_TRY(cudaMemcpy(offsets->mutable_view().begin<size_type>(), h_offsets.data(), sizeof(size_type) * 2, cudaMemcpyDefault)); auto list = cudf::make_lists_column(1, std::move(offsets), std::move(tdigests), 0, {}); auto min_col = cudf::make_fixed_width_column(data_type{type_id::FLOAT64}, 1, mask_state::UNALLOCATED); thrust::fill(rmm::exec_policy(cudf::get_default_stream()), min_col->mutable_view().begin<double>(), min_col->mutable_view().end<double>(), tdigest.min); auto max_col = cudf::make_fixed_width_column(data_type{type_id::FLOAT64}, 1, mask_state::UNALLOCATED); thrust::fill(rmm::exec_policy(cudf::get_default_stream()), max_col->mutable_view().begin<double>(), max_col->mutable_view().end<double>(), tdigest.max); std::vector<std::unique_ptr<column>> children; children.push_back(std::move(list)); children.push_back(std::move(min_col)); children.push_back(std::move(max_col)); return make_structs_column(1, std::move(children), 0, {}); }; // build the individual digests std::transform(groups.begin(), groups.end(), std::back_inserter(tdigests), make_digest); // concatenate them std::vector<column_view> views; std::transform(tdigests.begin(), tdigests.end(), std::back_inserter(views), [](std::unique_ptr<column> const& c) { return c->view(); }); return cudf::concatenate(views); } } // namespace test } // namespace cudf
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/jit/parse_ptx_function.cpp
/* * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed 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 <algorithm> #include <cctype> #include <cudf_test/base_fixture.hpp> #include <jit/parser.hpp> struct JitParseTest : public ::testing::Test {}; TEST_F(JitParseTest, PTXNoFunction) { std::string raw_ptx = R"( .visible .entry _ZN3cub17CUB_101702_750_NS11EmptyKernelIvEEvv() { ret; })"; EXPECT_THROW(cudf::jit::parse_single_function_ptx(raw_ptx, "GENERIC_OP", "float", {0}), cudf::logic_error); } inline bool ptx_equal(std::string input, std::string expected) { // Remove all whitespace and newline characters and compare // This allows us to handle things like excess newline characters // and trailing whitespace in the 'input' auto whitespace_or_newline = [](unsigned char c) { return std::isspace(c) || c == '\n'; }; input.erase(std::remove_if(input.begin(), input.end(), whitespace_or_newline), input.end()); expected.erase(std::remove_if(expected.begin(), expected.end(), whitespace_or_newline), expected.end()); return input == expected; } TEST_F(JitParseTest, SimplePTX) { std::string raw_ptx = R"( .visible .func (.param .b32 func_retval0) _ZN8__main__7add$241Eff( .param .b64 _ZN8__main__7add$241Eff_param_0, .param .b32 _ZN8__main__7add$241Eff_param_1, .param .b32 _ZN8__main__7add$241Eff_param_2 ) { ret; } )"; std::string expected = R"( __device__ __inline__ void GENERIC_OP( float* _ZN8__main__7add_241Eff_param_0, int _ZN8__main__7add_241Eff_param_1, int _ZN8__main__7add_241Eff_param_2 ){ asm volatile ("{"); asm volatile ("bra RETTGT;"); asm volatile ("RETTGT:}");} )"; std::string cuda_source = cudf::jit::parse_single_function_ptx(raw_ptx, "GENERIC_OP", "float", {0}); EXPECT_TRUE(ptx_equal(cuda_source, expected)); } TEST_F(JitParseTest, PTXWithPragma) { std::string raw_ptx = R"( .visible .func _ZN3cub17CUB_101702_750_NS11EmptyKernelIvEEvv() { $L__BB0_151: .pragma "nounroll"; mov.u32 % r1517, % r1516; mov.u32 % r1516, % r1515; mov.u32 % r1515, % r1505; mov.u32 % r1457, 0; $L__BB0_152: .pragma "nounroll"; })"; std::string expected = R"( __device__ __inline__ void EmptyKern(){ asm volatile ("{"); asm volatile (" $L__BB0_151: .pragma \"nounroll\";"); /** $L__BB0_151: .pragma "nounroll" */ asm volatile (" mov.u32 _ r1517, _ r1516;"); /** mov.u32 % r1517, % r1516 */ asm volatile (" mov.u32 _ r1516, _ r1515;"); /** mov.u32 % r1516, % r1515 */ asm volatile (" mov.u32 _ r1515, _ r1505;"); /** mov.u32 % r1515, % r1505 */ asm volatile (" mov.u32 _ r1457, 0;"); /** mov.u32 % r1457, 0 */ asm volatile (" $L__BB0_152: .pragma \"nounroll\";"); /** $L__BB0_152: .pragma "nounroll" */ asm volatile ("RETTGT:}");} )"; std::string cuda_source = cudf::jit::parse_single_function_ptx(raw_ptx, "EmptyKern", "void", {0}); EXPECT_TRUE(ptx_equal(cuda_source, expected)); } TEST_F(JitParseTest, PTXWithPragmaWithSpaces) { std::string raw_ptx = R"( .visible .func _ZN3cub17CUB_101702_750_NS11EmptyKernelIvEEvv() { $L__BB0_58: ld.param.u32 % r1419, [% rd419 + 80]; setp.ne.s32 % p394, % r1419, 22; mov.u32 % r2050, 0; mov.u32 % r2048, % r2050; @ % p394 bra $L__BB0_380; ld.param.u8 % rs1369, [% rd419 + 208]; setp.eq.s16 % p395, % rs1369, 0; selp.b32 % r1422, % r1925, 0, % p395; ld.param.u32 % r1423, [% rd419 + 112]; add.s32 % r427, % r1422, % r1423; ld.param.u64 % rd1249, [% rd419 + 120]; cvta.to.global.u64 % rd1250, % rd1249; .pragma "used_bytes_mask 4095"; ld.global.v4.u32{ % r1424, % r1425, % r1426, % r1427}, [% rd1250]; ld.global.v2.u64{ % rd1251, % rd1252}, [% rd1250 + 16]; ld.global.s32 % rd230, [% rd1250 + 32]; setp.gt.s32 % p396, % r1424, 6; @ % p396 bra $L__BB0_376; } } )"; std::string expected = R"( __device__ __inline__ void LongKernel(){ asm volatile ("{"); asm volatile (" $L__BB0_58: cvt.u32.u32 _ %0, [_ rd419 + 80];": : "r"(r1419)); /** $L__BB0_58: ld.param.u32 % r1419, [% rd419 + 80] */ asm volatile (" setp.ne.s32 _ p394, _ r1419, 22;"); /** setp.ne.s32 % p394, % r1419, 22 */ asm volatile (" mov.u32 _ r2050, 0;"); /** mov.u32 % r2050, 0 */ asm volatile (" mov.u32 _ r2048, _ r2050;"); /** mov.u32 % r2048, % r2050 */ asm volatile (" @ _ p394 bra $L__BB0_380;"); /** @ % p394 bra $L__BB0_380 */ asm volatile (" cvt.u8.u8 _ %0, [_ rd419 + 208];": : "h"( static_cast<short>(rs1369))); /** ld.param.u8 % rs1369, [% rd419 + 208] */ asm volatile (" setp.eq.s16 _ p395, _ rs1369, 0;"); /** setp.eq.s16 % p395, % rs1369, 0 */ asm volatile (" selp.b32 _ r1422, _ r1925, 0, _ p395;"); /** selp.b32 % r1422, % r1925, 0, % p395 */ asm volatile (" cvt.u32.u32 _ %0, [_ rd419 + 112];": : "r"(r1423)); /** ld.param.u32 % r1423, [% rd419 + 112] */ asm volatile (" add.s32 _ r427, _ r1422, _ r1423;"); /** add.s32 % r427, % r1422, % r1423 */ asm volatile (" mov.u64 _ %0, [_ rd419 + 120];": : "l"(rd1249)); /** ld.param.u64 % rd1249, [% rd419 + 120] */ asm volatile (" cvta.to.global.u64 _ rd1250, _ rd1249;"); /** cvta.to.global.u64 % rd1250, % rd1249 */ asm volatile (" .pragma \"used_bytes_mask 4095\";"); /** .pragma "used_bytes_mask 4095" */ asm volatile (" ld.global.v4.u32{ _ r1424, _ r1425, _ r1426, _ r1427}, [_ rd1250];"); /** ld.global.v4.u32{ % r1424, % r1425, % r1426, % r1427}, [% rd1250] */ asm volatile (" ld.global.v2.u64{ _ rd1251, _ rd1252}, [_ rd1250 + 16];"); /** ld.global.v2.u64{ % rd1251, % rd1252}, [% rd1250 + 16] */ asm volatile (" ld.global.s32 _ rd230, [_ rd1250 + 32];"); /** ld.global.s32 % rd230, [% rd1250 + 32] */ asm volatile (" setp.gt.s32 _ p396, _ r1424, 6;"); /** setp.gt.s32 % p396, % r1424, 6 */ asm volatile (" @ _ p396 bra $L__BB0_376;"); /** @ % p396 bra $L__BB0_376 */ asm volatile ("RETTGT:}");} )"; std::string cuda_source = cudf::jit::parse_single_function_ptx(raw_ptx, "LongKernel", "void", {0}); EXPECT_TRUE(ptx_equal(cuda_source, expected)); } CUDF_TEST_PROGRAM_MAIN()
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/partitioning/partition_test.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <cudf/copying.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/partitioning.hpp> #include <cudf/sorting.hpp> #include <cudf/table/table.hpp> template <typename T> class PartitionTest : public cudf::test::BaseFixture { using value_type = cudf::test::GetType<T, 0>; using map_type = cudf::test::GetType<T, 1>; }; using types = cudf::test::CrossProduct<cudf::test::FixedWidthTypes, cudf::test::IntegralTypesNotBool>; // using types = cudf::test::Types<cudf::test::Types<int32_t, int32_t> >; TYPED_TEST_SUITE(PartitionTest, types); using cudf::test::fixed_width_column_wrapper; using cudf::test::strings_column_wrapper; // Exceptional cases TYPED_TEST(PartitionTest, EmptyInputs) { using value_type = cudf::test::GetType<TypeParam, 0>; using map_type = cudf::test::GetType<TypeParam, 1>; fixed_width_column_wrapper<value_type> empty_column{}; fixed_width_column_wrapper<map_type> empty_map{}; auto result = cudf::partition(cudf::table_view{{empty_column}}, empty_map, 10); auto result_offsets = result.second; EXPECT_EQ(result_offsets.size(), std::size_t{11}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(empty_column, result.first->get_column(0)); } TYPED_TEST(PartitionTest, MapInputSizeMismatch) { using value_type = cudf::test::GetType<TypeParam, 0>; using map_type = cudf::test::GetType<TypeParam, 1>; fixed_width_column_wrapper<value_type, int32_t> input({1, 2, 3}); fixed_width_column_wrapper<map_type> map{1, 2}; EXPECT_THROW(cudf::partition(cudf::table_view{{input}}, map, 3), cudf::logic_error); } TYPED_TEST(PartitionTest, MapWithNullsThrows) { using value_type = cudf::test::GetType<TypeParam, 0>; using map_type = cudf::test::GetType<TypeParam, 1>; fixed_width_column_wrapper<value_type, int32_t> input({1, 2, 3}); fixed_width_column_wrapper<map_type> map{{1, 2}, {1, 0}}; EXPECT_THROW(cudf::partition(cudf::table_view{{input}}, map, 3), cudf::logic_error); } /** * @brief Verifies that partitions indicated by `offsets` are equal between * `expected` and `actual`. * * The order of rows within each partition may be different, so each partition * is first sorted before being compared for equality. */ void expect_equal_partitions(cudf::table_view expected, cudf::table_view actual, std::vector<cudf::size_type> const& offsets) { // Need to convert partition offsets into split points by dropping the first // and last element std::vector<cudf::size_type> split_points; std::copy(std::next(offsets.begin()), std::prev(offsets.end()), std::back_inserter(split_points)); // Split the partitions, sort each partition, then compare for equality auto actual_split = cudf::split(actual, split_points); auto expected_split = cudf::split(expected, split_points); std::equal(expected_split.begin(), expected_split.end(), actual_split.begin(), [](cudf::table_view expected, cudf::table_view actual) { auto sorted_expected = cudf::sort(expected); auto sorted_actual = cudf::sort(actual); CUDF_TEST_EXPECT_TABLES_EQUAL(*sorted_expected, *sorted_actual); return true; }); } void run_partition_test(cudf::table_view table_to_partition, cudf::column_view partition_map, cudf::size_type num_partitions, cudf::table_view expected_partitioned_table, std::vector<cudf::size_type> const& expected_offsets) { auto result = cudf::partition(table_to_partition, partition_map, num_partitions); auto const& actual_partitioned_table = result.first; auto const& actual_offsets = result.second; EXPECT_EQ(actual_offsets, expected_offsets); expect_equal_partitions(expected_partitioned_table, *actual_partitioned_table, expected_offsets); } // Normal cases TYPED_TEST(PartitionTest, Identity) { using value_type = cudf::test::GetType<TypeParam, 0>; using map_type = cudf::test::GetType<TypeParam, 1>; fixed_width_column_wrapper<value_type, int32_t> first({0, 1, 2, 3, 4, 5}); strings_column_wrapper strings{"this", "is", "a", "column", "of", "strings"}; auto table_to_partition = cudf::table_view{{first, strings}}; fixed_width_column_wrapper<map_type> map{0, 1, 2, 3, 4, 5}; std::vector<cudf::size_type> expected_offsets{0, 1, 2, 3, 4, 5, 6}; run_partition_test(table_to_partition, map, 6, table_to_partition, expected_offsets); } TYPED_TEST(PartitionTest, Struct) { using value_type = cudf::test::GetType<TypeParam, 0>; using map_type = cudf::test::GetType<TypeParam, 1>; fixed_width_column_wrapper<value_type, int32_t> A({1, 2}, {0, 1}); auto struct_col = cudf::test::structs_column_wrapper({A}, {0, 1}).release(); auto table_to_partition = cudf::table_view{{*struct_col}}; fixed_width_column_wrapper<map_type> map{9, 2}; fixed_width_column_wrapper<value_type, int32_t> A_expected({2, 1}, {1, 0}); auto struct_expected = cudf::test::structs_column_wrapper({A_expected}, {1, 0}).release(); auto expected = cudf::table_view{{*struct_expected}}; std::vector<cudf::size_type> expected_offsets{0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2}; // This does not work because we cannot sort a struct right now... // run_partition_test(table_to_partition, map, 12, expected, expected_offsets); // But there is no ambiguity in the ordering so I'll just copy it all here for now. auto num_partitions = 12; auto result = cudf::partition(table_to_partition, map, num_partitions); auto const& actual_partitioned_table = result.first; auto const& actual_offsets = result.second; EXPECT_EQ(actual_offsets, expected_offsets); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, *actual_partitioned_table); } TYPED_TEST(PartitionTest, Reverse) { using value_type = cudf::test::GetType<TypeParam, 0>; using map_type = cudf::test::GetType<TypeParam, 1>; fixed_width_column_wrapper<value_type, int32_t> first({0, 1, 3, 7, 5, 13}); strings_column_wrapper strings{"this", "is", "a", "column", "of", "strings"}; auto table_to_partition = cudf::table_view{{first, strings}}; fixed_width_column_wrapper<map_type> map{5, 4, 3, 2, 1, 0}; std::vector<cudf::size_type> expected_offsets{0, 1, 2, 3, 4, 5, 6}; fixed_width_column_wrapper<value_type, int32_t> expected_first({13, 5, 7, 3, 1, 0}); strings_column_wrapper expected_strings{"strings", "of", "column", "a", "is", "this"}; auto expected_partitioned_table = cudf::table_view{{expected_first, expected_strings}}; run_partition_test(table_to_partition, map, 6, expected_partitioned_table, expected_offsets); } TYPED_TEST(PartitionTest, SinglePartition) { using value_type = cudf::test::GetType<TypeParam, 0>; using map_type = cudf::test::GetType<TypeParam, 1>; fixed_width_column_wrapper<value_type, int32_t> first({0, 1, 3, 7, 5, 13}); strings_column_wrapper strings{"this", "is", "a", "column", "of", "strings"}; auto table_to_partition = cudf::table_view{{first, strings}}; fixed_width_column_wrapper<map_type> map{0, 0, 0, 0, 0, 0}; std::vector<cudf::size_type> expected_offsets{0, 6}; fixed_width_column_wrapper<value_type, int32_t> expected_first({13, 5, 7, 3, 1, 0}); strings_column_wrapper expected_strings{"strings", "of", "column", "a", "is", "this"}; auto expected_partitioned_table = cudf::table_view{{expected_first, expected_strings}}; run_partition_test(table_to_partition, map, 1, expected_partitioned_table, expected_offsets); } TYPED_TEST(PartitionTest, EmptyPartitions) { using value_type = cudf::test::GetType<TypeParam, 0>; using map_type = cudf::test::GetType<TypeParam, 1>; fixed_width_column_wrapper<value_type, int32_t> first({0, 1, 3, 7, 5, 13}); strings_column_wrapper strings{"this", "is", "a", "column", "of", "strings"}; auto table_to_partition = cudf::table_view{{first, strings}}; fixed_width_column_wrapper<map_type> map{2, 2, 0, 0, 4, 4}; std::vector<cudf::size_type> expected_offsets{0, 2, 2, 4, 4, 6}; fixed_width_column_wrapper<value_type, int32_t> expected_first({3, 7, 0, 1, 5, 13}); strings_column_wrapper expected_strings{"a", "column", "this", "is", "of", "strings"}; auto expected_partitioned_table = cudf::table_view{{expected_first, expected_strings}}; run_partition_test(table_to_partition, map, 5, expected_partitioned_table, expected_offsets); } template <typename T> class PartitionTestFixedPoint : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(PartitionTestFixedPoint, cudf::test::FixedPointTypes); TYPED_TEST(PartitionTestFixedPoint, Partition) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const input = fp_wrapper({11, 22, 33, 44, 55, 66}, scale_type{-1}); auto const map = fixed_width_column_wrapper<int32_t>{0, 1, 2, 3, 4, 5}; auto const expected = cudf::table_view{{input}}; auto const offsets = std::vector<cudf::size_type>{0, 1, 2, 3, 4, 5, 6}; run_partition_test(expected, map, 6, expected, offsets); } TYPED_TEST(PartitionTestFixedPoint, Partition1) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const input = fp_wrapper({11, 22, 33, 44, 55, 66}, scale_type{-1}); auto const map = fixed_width_column_wrapper<int32_t>{5, 4, 3, 2, 1, 0}; auto const expected = fp_wrapper({66, 55, 44, 33, 22, 11}, scale_type{-1}); auto const offsets = std::vector<cudf::size_type>{0, 1, 2, 3, 4, 5, 6}; run_partition_test(cudf::table_view{{input}}, map, 6, cudf::table_view{{expected}}, offsets); } TYPED_TEST(PartitionTestFixedPoint, Partition2) { using namespace numeric; using decimalXX = TypeParam; using RepType = cudf::device_storage_type_t<decimalXX>; using fp_wrapper = cudf::test::fixed_point_column_wrapper<RepType>; auto const input = fp_wrapper({11, 22, 33, 44, 55, 66}, scale_type{-1}); auto const map = fixed_width_column_wrapper<int32_t>{2, 1, 0, 2, 1, 0}; auto const expected = fp_wrapper({33, 66, 22, 55, 11, 44}, scale_type{-1}); auto const offsets = std::vector<cudf::size_type>{0, 2, 4, 6}; run_partition_test(cudf::table_view{{input}}, map, 3, cudf::table_view{{expected}}, offsets); } struct PartitionTestNotTyped : public cudf::test::BaseFixture {}; TEST_F(PartitionTestNotTyped, ListOfStringsEmpty) { cudf::test::lists_column_wrapper<cudf::string_view> list{{}, {}}; auto table_to_partition = cudf::table_view{{list}}; fixed_width_column_wrapper<int32_t> map{0, 0}; auto result = cudf::partition(table_to_partition, map, 2); CUDF_TEST_EXPECT_TABLES_EQUAL(table_to_partition, result.first->view()); EXPECT_EQ(3, result.second.size()); } TEST_F(PartitionTestNotTyped, ListOfListOfIntEmpty) { cudf::test::lists_column_wrapper<int32_t> level_2_list; fixed_width_column_wrapper<int32_t> level_1_offsets{0, 0, 0}; std::unique_ptr<cudf::column> level_1_list = cudf::make_lists_column(2, level_1_offsets.release(), level_2_list.release(), 0, {}); auto table_to_partition = cudf::table_view{{*level_1_list}}; fixed_width_column_wrapper<int32_t> map{0, 0}; auto result = cudf::partition(table_to_partition, map, 2); CUDF_TEST_EXPECT_TABLES_EQUAL(table_to_partition, result.first->view()); EXPECT_EQ(3, result.second.size()); } TEST_F(PartitionTestNotTyped, ListOfListOfListOfIntEmpty) { cudf::test::lists_column_wrapper<int32_t> level_3_list{}; fixed_width_column_wrapper<int32_t> level_2_offsets{}; std::unique_ptr<cudf::column> level_2_list = cudf::make_lists_column(0, level_2_offsets.release(), level_3_list.release(), 0, {}); fixed_width_column_wrapper<int32_t> level_1_offsets{0, 0}; std::unique_ptr<cudf::column> level_1_list = cudf::make_lists_column(1, level_1_offsets.release(), std::move(level_2_list), 0, {}); auto table_to_partition = cudf::table_view{{*level_1_list}}; fixed_width_column_wrapper<int32_t> map{0}; auto result = cudf::partition(table_to_partition, map, 2); CUDF_TEST_EXPECT_TABLES_EQUAL(table_to_partition, result.first->view()); EXPECT_EQ(3, result.second.size()); } TEST_F(PartitionTestNotTyped, NoIntegerOverflow) { auto elements = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i % 2; }); fixed_width_column_wrapper<int8_t> map(elements, elements + 129); auto table_to_partition = cudf::table_view{{map}}; std::vector<cudf::size_type> expected_offsets{0, 65, 129}; auto expected_elements = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i / 65; }); fixed_width_column_wrapper<int8_t> expected(expected_elements, expected_elements + 129); auto expected_table = cudf::table_view{{expected}}; run_partition_test(table_to_partition, map, 2, expected_table, expected_offsets); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/partitioning/hash_partition_test.cpp
/* * Copyright (c) 2019-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/detail/utilities/vector_factories.hpp> #include <cudf/hashing.hpp> #include <cudf/partitioning.hpp> #include <cudf/sorting.hpp> #include <cudf/table/table.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <cudf_test/table_utilities.hpp> #include <cudf_test/type_lists.hpp> #include <thrust/iterator/counting_iterator.h> #include <thrust/iterator/transform_iterator.h> using cudf::test::fixed_width_column_wrapper; using cudf::test::strings_column_wrapper; using structs_col = cudf::test::structs_column_wrapper; using cudf::test::iterators::null_at; using cudf::test::iterators::nulls_at; // Transform vector of column wrappers to vector of column views template <typename T> auto make_view_vector(std::vector<T> const& columns) { std::vector<cudf::column_view> views(columns.size()); std::transform(columns.begin(), columns.end(), views.begin(), [](auto const& col) { return static_cast<cudf::column_view>(col); }); return views; } class HashPartition : public cudf::test::BaseFixture {}; TEST_F(HashPartition, InvalidColumnsToHash) { fixed_width_column_wrapper<float> floats({1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f}); fixed_width_column_wrapper<int16_t> integers({1, 2, 3, 4, 5, 6, 7, 8}); strings_column_wrapper strings({"a", "bb", "ccc", "d", "ee", "fff", "gg", "h"}); auto input = cudf::table_view({floats, integers, strings}); auto columns_to_hash = std::vector<cudf::size_type>({-1}); cudf::size_type const num_partitions = 3; EXPECT_THROW(cudf::hash_partition(input, columns_to_hash, num_partitions), std::out_of_range); } TEST_F(HashPartition, ZeroPartitions) { fixed_width_column_wrapper<float> floats({1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f}); fixed_width_column_wrapper<int16_t> integers({1, 2, 3, 4, 5, 6, 7, 8}); strings_column_wrapper strings({"a", "bb", "ccc", "d", "ee", "fff", "gg", "h"}); auto input = cudf::table_view({floats, integers, strings}); auto columns_to_hash = std::vector<cudf::size_type>({2}); cudf::size_type const num_partitions = 0; auto [output, offsets] = cudf::hash_partition(input, columns_to_hash, num_partitions); // Expect empty table with same number of columns and zero partitions EXPECT_EQ(input.num_columns(), output->num_columns()); EXPECT_EQ(0, output->num_rows()); EXPECT_EQ(std::size_t{num_partitions}, offsets.size()); } TEST_F(HashPartition, ZeroRows) { fixed_width_column_wrapper<float> floats({}); fixed_width_column_wrapper<int16_t> integers({}); strings_column_wrapper strings; auto input = cudf::table_view({floats, integers, strings}); auto columns_to_hash = std::vector<cudf::size_type>({2}); cudf::size_type const num_partitions = 3; auto [output, offsets] = cudf::hash_partition(input, columns_to_hash, num_partitions); // Expect empty table with same number of columns and same number of partitions EXPECT_EQ(input.num_columns(), output->num_columns()); EXPECT_EQ(0, output->num_rows()); EXPECT_EQ(std::size_t{num_partitions}, offsets.size()); } TEST_F(HashPartition, ZeroColumns) { auto input = cudf::table_view(std::vector<cudf::column_view>{}); auto columns_to_hash = std::vector<cudf::size_type>({}); cudf::size_type const num_partitions = 3; auto [output, offsets] = cudf::hash_partition(input, columns_to_hash, num_partitions); // Expect empty table with same number of columns and same number of partitions EXPECT_EQ(input.num_columns(), output->num_columns()); EXPECT_EQ(0, output->num_rows()); EXPECT_EQ(std::size_t{num_partitions}, offsets.size()); } TEST_F(HashPartition, MixedColumnTypes) { fixed_width_column_wrapper<float> floats({1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f}); fixed_width_column_wrapper<int16_t> integers({1, 2, 3, 4, 5, 6, 7, 8}); strings_column_wrapper strings({"a", "bb", "ccc", "d", "ee", "fff", "gg", "h"}); auto input = cudf::table_view({floats, integers, strings}); auto columns_to_hash = std::vector<cudf::size_type>({0, 2}); cudf::size_type const num_partitions = 3; auto [output1, offsets1] = cudf::hash_partition(input, columns_to_hash, num_partitions); auto [output2, offsets2] = cudf::hash_partition(input, columns_to_hash, num_partitions); // Expect output to have size num_partitions EXPECT_EQ(static_cast<size_t>(num_partitions), offsets1.size()); EXPECT_EQ(offsets1.size(), offsets2.size()); // Expect output to have same shape as input CUDF_TEST_EXPECT_TABLE_PROPERTIES_EQUAL(input, output1->view()); // Expect deterministic result from hashing the same input CUDF_TEST_EXPECT_TABLES_EQUAL(output1->view(), output2->view()); } TEST_F(HashPartition, NullableStrings) { strings_column_wrapper strings({"a", "bb", "ccc", "d"}, {1, 1, 1, 1}); cudf::table_view input({strings}); std::vector<cudf::size_type> const columns_to_hash({0}); cudf::size_type const num_partitions = 3; auto [result, offsets] = cudf::hash_partition(input, columns_to_hash, num_partitions); auto const& col = result->get_column(0); EXPECT_EQ(0, col.null_count()); } TEST_F(HashPartition, ColumnsToHash) { fixed_width_column_wrapper<int32_t> to_hash({1, 2, 3, 4, 5, 6}); fixed_width_column_wrapper<int32_t> first_col({7, 8, 9, 10, 11, 12}); fixed_width_column_wrapper<int32_t> second_col({13, 14, 15, 16, 17, 18}); auto first_input = cudf::table_view({to_hash, first_col}); auto second_input = cudf::table_view({to_hash, second_col}); auto columns_to_hash = std::vector<cudf::size_type>({0}); cudf::size_type const num_partitions = 3; auto [first_result, first_offsets] = cudf::hash_partition(first_input, columns_to_hash, num_partitions); auto [second_result, second_offsets] = cudf::hash_partition(second_input, columns_to_hash, num_partitions); // Expect offsets to be equal and num_partitions in length EXPECT_EQ(static_cast<size_t>(num_partitions), first_offsets.size()); EXPECT_TRUE(std::equal( first_offsets.begin(), first_offsets.end(), second_offsets.begin(), second_offsets.end())); // Expect same result for the hashed columns CUDF_TEST_EXPECT_COLUMNS_EQUAL(first_result->get_column(0).view(), second_result->get_column(0).view()); } TEST_F(HashPartition, IdentityHashFailure) { fixed_width_column_wrapper<float> floats({1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f}); fixed_width_column_wrapper<int16_t> integers({1, 2, 3, 4, 5, 6, 7, 8}); strings_column_wrapper strings({"a", "bb", "ccc", "d", "ee", "fff", "gg", "h"}); auto input = cudf::table_view({floats, integers, strings}); auto columns_to_hash = std::vector<cudf::size_type>({2}); cudf::size_type const num_partitions = 3; EXPECT_THROW( cudf::hash_partition(input, columns_to_hash, num_partitions, cudf::hash_id::HASH_IDENTITY), cudf::logic_error); } TEST_F(HashPartition, UnsupportedHashFunction) { fixed_width_column_wrapper<float> floats({1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f}); fixed_width_column_wrapper<int16_t> integers({1, 2, 3, 4, 5, 6, 7, 8}); strings_column_wrapper strings({"a", "bb", "ccc", "d", "ee", "fff", "gg", "h"}); auto input = cudf::table_view({floats, integers, strings}); auto columns_to_hash = std::vector<cudf::size_type>({2}); cudf::size_type const num_partitions = 3; EXPECT_THROW( cudf::hash_partition(input, columns_to_hash, num_partitions, cudf::hash_id::HASH_MD5), cudf::logic_error); } TEST_F(HashPartition, CustomSeedValue) { fixed_width_column_wrapper<float> floats({1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f}); fixed_width_column_wrapper<int16_t> integers({1, 2, 3, 4, 5, 6, 7, 8}); strings_column_wrapper strings({"a", "bb", "ccc", "d", "ee", "fff", "gg", "h"}); auto input = cudf::table_view({floats, integers, strings}); auto columns_to_hash = std::vector<cudf::size_type>({0, 2}); cudf::size_type const num_partitions = 3; auto [output1, offsets1] = cudf::hash_partition( input, columns_to_hash, num_partitions, cudf::hash_id::HASH_MURMUR3, 12345); auto [output2, offsets2] = cudf::hash_partition( input, columns_to_hash, num_partitions, cudf::hash_id::HASH_MURMUR3, 12345); // Expect output to have size num_partitions EXPECT_EQ(static_cast<size_t>(num_partitions), offsets1.size()); EXPECT_EQ(offsets1.size(), offsets2.size()); // Expect output to have same shape as input CUDF_TEST_EXPECT_TABLE_PROPERTIES_EQUAL(input, output1->view()); // Expect deterministic result from hashing the same input CUDF_TEST_EXPECT_TABLES_EQUAL(output1->view(), output2->view()); } template <typename T> class HashPartitionFixedWidth : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(HashPartitionFixedWidth, cudf::test::FixedWidthTypesWithoutFixedPoint); TYPED_TEST(HashPartitionFixedWidth, NullableFixedWidth) { fixed_width_column_wrapper<TypeParam, int32_t> fixed({1, 2, 3, 4}, {1, 1, 1, 1}); cudf::table_view input({fixed}); std::vector<cudf::size_type> const columns_to_hash({0}); cudf::size_type const num_partitions = 3; auto [result, offsets] = cudf::hash_partition(input, columns_to_hash, num_partitions); auto const& col = result->get_column(0); EXPECT_EQ(0, col.null_count()); } template <typename T> void run_fixed_width_test(size_t cols, size_t rows, cudf::size_type num_partitions, cudf::hash_id hash_function, bool has_nulls = false) { std::vector<fixed_width_column_wrapper<T, int32_t>> columns; columns.reserve(cols); if (has_nulls) { std::generate_n(std::back_inserter(columns), cols, [rows]() { auto iter = thrust::make_counting_iterator(0); auto valids = thrust::make_transform_iterator(iter, [](auto i) { return i % 4 != 0; }); return fixed_width_column_wrapper<T, int32_t>(iter, iter + rows, valids); }); } else { std::generate_n(std::back_inserter(columns), cols, [rows]() { auto iter = thrust::make_counting_iterator(0); return fixed_width_column_wrapper<T, int32_t>(iter, iter + rows); }); } auto input = cudf::table_view(make_view_vector(columns)); auto columns_to_hash = std::vector<cudf::size_type>(cols); std::iota(columns_to_hash.begin(), columns_to_hash.end(), 0); auto [output1, offsets1] = cudf::hash_partition(input, columns_to_hash, num_partitions); auto [output2, offsets2] = cudf::hash_partition(input, columns_to_hash, num_partitions); // Expect output to have size num_partitions EXPECT_EQ(static_cast<size_t>(num_partitions), offsets1.size()); EXPECT_TRUE(std::equal(offsets1.begin(), offsets1.end(), offsets2.begin())); // Expect output to have same shape as input CUDF_TEST_EXPECT_TABLE_PROPERTIES_EQUAL(input, output1->view()); CUDF_TEST_EXPECT_TABLE_PROPERTIES_EQUAL(output1->view(), output2->view()); // Compute number of rows in each partition EXPECT_EQ(0, offsets1[0]); offsets1.push_back(rows); std::adjacent_difference(offsets1.begin() + 1, offsets1.end(), offsets1.begin() + 1); // Compute the partition number for each row cudf::size_type partition = 0; std::vector<cudf::size_type> partitions; std::for_each(offsets1.begin() + 1, offsets1.end(), [&](cudf::size_type const& count) { std::fill_n(std::back_inserter(partitions), count, partition++); }); // Make a table view of the partition numbers constexpr cudf::data_type dtype{cudf::type_id::INT32}; auto d_partitions = cudf::detail::make_device_uvector_sync( partitions, cudf::get_default_stream(), rmm::mr::get_current_device_resource()); cudf::column_view partitions_col(dtype, rows, d_partitions.data(), nullptr, 0); cudf::table_view partitions_table({partitions_col}); // Sort partition numbers by the corresponding row hashes of each output auto hash1 = cudf::hash(output1->view()); cudf::table_view hash1_table({hash1->view()}); auto sorted_partitions1 = cudf::sort_by_key(partitions_table, hash1_table); auto hash2 = cudf::hash(output2->view()); cudf::table_view hash2_table({hash2->view()}); auto sorted_partitions2 = cudf::sort_by_key(partitions_table, hash2_table); // After sorting by row hashes, the corresponding partition numbers should be // equal CUDF_TEST_EXPECT_TABLES_EQUAL(sorted_partitions1->view(), sorted_partitions2->view()); } TYPED_TEST(HashPartitionFixedWidth, MorePartitionsThanRows) { run_fixed_width_test<TypeParam>(5, 10, 50, cudf::hash_id::HASH_MURMUR3); run_fixed_width_test<TypeParam>(5, 10, 50, cudf::hash_id::HASH_IDENTITY); } TYPED_TEST(HashPartitionFixedWidth, LargeInput) { run_fixed_width_test<TypeParam>(10, 1000, 10, cudf::hash_id::HASH_MURMUR3); run_fixed_width_test<TypeParam>(10, 1000, 10, cudf::hash_id::HASH_IDENTITY); } TYPED_TEST(HashPartitionFixedWidth, HasNulls) { run_fixed_width_test<TypeParam>(10, 1000, 10, cudf::hash_id::HASH_MURMUR3, true); run_fixed_width_test<TypeParam>(10, 1000, 10, cudf::hash_id::HASH_IDENTITY, true); } TEST_F(HashPartition, FixedPointColumnsToHash) { fixed_width_column_wrapper<int32_t> to_hash({1}); cudf::test::fixed_point_column_wrapper<int64_t> first_col({7}, numeric::scale_type{-1}); cudf::test::fixed_point_column_wrapper<__int128_t> second_col({77}, numeric::scale_type{0}); auto input = cudf::table_view({to_hash, first_col, second_col}); auto columns_to_hash = std::vector<cudf::size_type>({0}); cudf::size_type const num_partitions = 1; auto [result, offsets] = cudf::hash_partition(input, columns_to_hash, num_partitions); // Expect offsets to be equal and num_partitions in length EXPECT_EQ(static_cast<size_t>(num_partitions), offsets.size()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->get_column(0).view(), input.column(0)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->get_column(1).view(), input.column(1)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result->get_column(2).view(), input.column(2)); } TEST_F(HashPartition, ListWithNulls) { using lcw = cudf::test::lists_column_wrapper<int32_t>; lcw to_hash{{{1}, {2, 2}, {0}, {1}, {2, 2}, {0}}, nulls_at({2, 5})}; fixed_width_column_wrapper<int32_t> first_col({7, 8, 9, 10, 11, 12}); fixed_width_column_wrapper<int32_t> second_col({13, 14, 15, 16, 17, 18}); auto const first_input = cudf::table_view({to_hash, first_col}); auto const second_input = cudf::table_view({to_hash, second_col}); auto const columns_to_hash = std::vector<cudf::size_type>({0}); cudf::size_type const num_partitions = 3; auto const [first_result, first_offsets] = cudf::hash_partition(first_input, columns_to_hash, num_partitions); auto const [second_result, second_offsets] = cudf::hash_partition(second_input, columns_to_hash, num_partitions); // Expect offsets to be equal and num_partitions in length EXPECT_EQ(static_cast<size_t>(num_partitions), first_offsets.size()); EXPECT_TRUE(std::equal( first_offsets.begin(), first_offsets.end(), second_offsets.begin(), second_offsets.end())); // Expect same result for the hashed columns CUDF_TEST_EXPECT_COLUMNS_EQUAL(first_result->get_column(0).view(), second_result->get_column(0).view()); } TEST_F(HashPartition, StructofStructWithNulls) { // +-----------------+ // | s1{s2{a,b}, c} | // +-----------------+ // 0 | { {1, 1}, 5} | // 1 | { {1, 1}, 5} | // 2 | { {1, 2}, 4} | // 3 | Null | // 4 | { Null, 4} | // 5 | { Null, 4} | auto const to_hash = [&] { auto a = fixed_width_column_wrapper<int32_t>{1, 1, 1, 0, 0, 0}; auto b = fixed_width_column_wrapper<int32_t>{1, 1, 2, 0, 0, 0}; auto s2 = structs_col{{a, b}, nulls_at({4, 5})}; auto c = fixed_width_column_wrapper<int32_t>{5, 5, 4, 0, 4, 4}; return structs_col({s2, c}, null_at(3)); }(); fixed_width_column_wrapper<int32_t> first_col({7, 8, 9, 10, 11, 12}); fixed_width_column_wrapper<int32_t> second_col({13, 14, 15, 16, 17, 18}); auto const first_input = cudf::table_view({to_hash, first_col}); auto const second_input = cudf::table_view({to_hash, second_col}); auto const columns_to_hash = std::vector<cudf::size_type>({0}); cudf::size_type const num_partitions = 3; auto const [first_result, first_offsets] = cudf::hash_partition(first_input, columns_to_hash, num_partitions); auto const [second_result, second_offsets] = cudf::hash_partition(second_input, columns_to_hash, num_partitions); // Expect offsets to be equal and num_partitions in length EXPECT_EQ(static_cast<size_t>(num_partitions), first_offsets.size()); EXPECT_TRUE(std::equal( first_offsets.begin(), first_offsets.end(), second_offsets.begin(), second_offsets.end())); // Expect same result for the hashed columns CUDF_TEST_EXPECT_COLUMNS_EQUAL(first_result->get_column(0).view(), second_result->get_column(0).view()); } CUDF_TEST_PROGRAM_MAIN()
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/partitioning/round_robin_test.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/column/column_factories.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/partitioning.hpp> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> #include <cudf/types.hpp> #include <cudf/utilities/type_dispatcher.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/cudf_gtest.hpp> #include <cudf_test/type_lists.hpp> #include <algorithm> #include <cassert> #include <initializer_list> #include <limits> #include <memory> #include <numeric> #include <vector> #include <gtest/gtest.h> using cudf::test::fixed_width_column_wrapper; using cudf::test::strings_column_wrapper; template <typename T> class RoundRobinTest : public cudf::test::BaseFixture {}; TYPED_TEST_SUITE(RoundRobinTest, cudf::test::FixedWidthTypes); TYPED_TEST(RoundRobinTest, EmptyInput) { auto const empty_column = fixed_width_column_wrapper<TypeParam>{}; auto const num_partitions = 5; auto const start_partition = 0; auto const [out_table, out_offsets] = cudf::round_robin_partition(cudf::table_view{{empty_column}}, num_partitions, start_partition); EXPECT_EQ(out_table->num_rows(), 0); EXPECT_EQ(out_offsets.size(), std::size_t{num_partitions}); } TYPED_TEST(RoundRobinTest, RoundRobinPartitions13_3) { strings_column_wrapper rrColWrap1( {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}); cudf::size_type inputRows = static_cast<cudf::column_view const&>(rrColWrap1).size(); auto sequence_l = cudf::detail::make_counting_transform_iterator( 0, [bool8 = (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8)](auto row) { return bool8 ? static_cast<decltype(row)>(row % 2 == 0) : row; }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence_l)::value_type> rrColWrap2(sequence_l, sequence_l + inputRows); cudf::table_view rr_view{{rrColWrap1, rrColWrap2}}; cudf::size_type num_partitions = 3; cudf::size_type start_partition = 0; { std::pair<std::unique_ptr<cudf::table>, std::vector<cudf::size_type>> result; EXPECT_NO_THROW(result = cudf::round_robin_partition(rr_view, num_partitions, start_partition)); auto p_outputTable = std::move(result.first); auto output_column_view1{p_outputTable->view().column(0)}; auto output_column_view2{p_outputTable->view().column(1)}; strings_column_wrapper expectedDataWrap1( {"a", "d", "g", "j", "m", "b", "e", "h", "k", "c", "f", "i", "l"}, {1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1}); auto expected_column_view1{static_cast<cudf::column_view const&>(expectedDataWrap1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view1, output_column_view1); if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { fixed_width_column_wrapper<bool> expectedDataWrap2({1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; EXPECT_EQ(inputRows, expected_column_view2.size()); EXPECT_EQ(inputRows, output_column_view2.size()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } else { fixed_width_column_wrapper<TypeParam, int32_t> expectedDataWrap2( {0, 3, 6, 9, 12, 1, 4, 7, 10, 2, 5, 8, 11}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } std::vector<cudf::size_type> expected_partition_offsets{0, 5, 9}; EXPECT_EQ(static_cast<std::size_t>(num_partitions), expected_partition_offsets.size()); EXPECT_EQ(expected_partition_offsets, result.second); } start_partition = 1; { std::pair<std::unique_ptr<cudf::table>, std::vector<cudf::size_type>> result; EXPECT_NO_THROW(result = cudf::round_robin_partition(rr_view, num_partitions, start_partition)); auto p_outputTable = std::move(result.first); auto output_column_view1{p_outputTable->view().column(0)}; auto output_column_view2{p_outputTable->view().column(1)}; strings_column_wrapper expectedDataWrap1( {"c", "f", "i", "l", "a", "d", "g", "j", "m", "b", "e", "h", "k"}, {1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1}); auto expected_column_view1{static_cast<cudf::column_view const&>(expectedDataWrap1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view1, output_column_view1); if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { fixed_width_column_wrapper<bool> expectedDataWrap2({1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; EXPECT_EQ(inputRows, expected_column_view2.size()); EXPECT_EQ(inputRows, output_column_view2.size()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } else { fixed_width_column_wrapper<TypeParam, int32_t> expectedDataWrap2( {2, 5, 8, 11, 0, 3, 6, 9, 12, 1, 4, 7, 10}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } std::vector<cudf::size_type> expected_partition_offsets{0, 4, 9}; EXPECT_EQ(static_cast<std::size_t>(num_partitions), expected_partition_offsets.size()); EXPECT_EQ(expected_partition_offsets, result.second); } start_partition = 2; { std::pair<std::unique_ptr<cudf::table>, std::vector<cudf::size_type>> result; EXPECT_NO_THROW(result = cudf::round_robin_partition(rr_view, num_partitions, start_partition)); auto p_outputTable = std::move(result.first); auto output_column_view1{p_outputTable->view().column(0)}; auto output_column_view2{p_outputTable->view().column(1)}; strings_column_wrapper expectedDataWrap1( {"b", "e", "h", "k", "c", "f", "i", "l", "a", "d", "g", "j", "m"}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}); auto expected_column_view1{static_cast<cudf::column_view const&>(expectedDataWrap1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view1, output_column_view1); if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { fixed_width_column_wrapper<bool> expectedDataWrap2({0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; EXPECT_EQ(inputRows, expected_column_view2.size()); EXPECT_EQ(inputRows, output_column_view2.size()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } else { fixed_width_column_wrapper<TypeParam, int32_t> expectedDataWrap2( {1, 4, 7, 10, 2, 5, 8, 11, 0, 3, 6, 9, 12}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } std::vector<cudf::size_type> expected_partition_offsets{0, 4, 8}; EXPECT_EQ(static_cast<std::size_t>(num_partitions), expected_partition_offsets.size()); EXPECT_EQ(expected_partition_offsets, result.second); } } TYPED_TEST(RoundRobinTest, RoundRobinPartitions11_3) { strings_column_wrapper rrColWrap1({"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}); cudf::size_type inputRows = static_cast<cudf::column_view const&>(rrColWrap1).size(); auto sequence_l = cudf::detail::make_counting_transform_iterator( 0, [bool8 = (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8)](auto row) { return bool8 ? static_cast<decltype(row)>(row % 2 == 0) : row; }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence_l)::value_type> rrColWrap2(sequence_l, sequence_l + inputRows); cudf::table_view rr_view{{rrColWrap1, rrColWrap2}}; cudf::size_type num_partitions = 3; cudf::size_type start_partition = 0; { std::pair<std::unique_ptr<cudf::table>, std::vector<cudf::size_type>> result; EXPECT_NO_THROW(result = cudf::round_robin_partition(rr_view, num_partitions, start_partition)); auto p_outputTable = std::move(result.first); auto output_column_view1{p_outputTable->view().column(0)}; auto output_column_view2{p_outputTable->view().column(1)}; strings_column_wrapper expectedDataWrap1( {"a", "d", "g", "j", "b", "e", "h", "k", "c", "f", "i"}, {1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1}); auto expected_column_view1{static_cast<cudf::column_view const&>(expectedDataWrap1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view1, output_column_view1); if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { fixed_width_column_wrapper<bool> expectedDataWrap2({1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; EXPECT_EQ(inputRows, expected_column_view2.size()); EXPECT_EQ(inputRows, output_column_view2.size()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } else { fixed_width_column_wrapper<TypeParam, int32_t> expectedDataWrap2( {0, 3, 6, 9, 1, 4, 7, 10, 2, 5, 8}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } std::vector<cudf::size_type> expected_partition_offsets{0, 4, 8}; EXPECT_EQ(static_cast<std::size_t>(num_partitions), expected_partition_offsets.size()); EXPECT_EQ(expected_partition_offsets, result.second); } start_partition = 1; { std::pair<std::unique_ptr<cudf::table>, std::vector<cudf::size_type>> result; EXPECT_NO_THROW(result = cudf::round_robin_partition(rr_view, num_partitions, start_partition)); auto p_outputTable = std::move(result.first); auto output_column_view1{p_outputTable->view().column(0)}; auto output_column_view2{p_outputTable->view().column(1)}; strings_column_wrapper expectedDataWrap1( {"c", "f", "i", "a", "d", "g", "j", "b", "e", "h", "k"}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}); auto expected_column_view1{static_cast<cudf::column_view const&>(expectedDataWrap1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view1, output_column_view1); if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { fixed_width_column_wrapper<bool> expectedDataWrap2({1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; EXPECT_EQ(inputRows, expected_column_view2.size()); EXPECT_EQ(inputRows, output_column_view2.size()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } else { fixed_width_column_wrapper<TypeParam, int32_t> expectedDataWrap2( {2, 5, 8, 0, 3, 6, 9, 1, 4, 7, 10}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } std::vector<cudf::size_type> expected_partition_offsets{0, 3, 7}; EXPECT_EQ(static_cast<std::size_t>(num_partitions), expected_partition_offsets.size()); EXPECT_EQ(expected_partition_offsets, result.second); } start_partition = 2; { std::pair<std::unique_ptr<cudf::table>, std::vector<cudf::size_type>> result; EXPECT_NO_THROW(result = cudf::round_robin_partition(rr_view, num_partitions, start_partition)); auto p_outputTable = std::move(result.first); auto output_column_view1{p_outputTable->view().column(0)}; auto output_column_view2{p_outputTable->view().column(1)}; strings_column_wrapper expectedDataWrap1( {"b", "e", "h", "k", "c", "f", "i", "a", "d", "g", "j"}, {1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1}); auto expected_column_view1{static_cast<cudf::column_view const&>(expectedDataWrap1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view1, output_column_view1); if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { fixed_width_column_wrapper<bool> expectedDataWrap2({0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; EXPECT_EQ(inputRows, expected_column_view2.size()); EXPECT_EQ(inputRows, output_column_view2.size()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } else { fixed_width_column_wrapper<TypeParam, int32_t> expectedDataWrap2( {1, 4, 7, 10, 2, 5, 8, 0, 3, 6, 9}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } std::vector<cudf::size_type> expected_partition_offsets{0, 4, 7}; EXPECT_EQ(static_cast<std::size_t>(num_partitions), expected_partition_offsets.size()); EXPECT_EQ(expected_partition_offsets, result.second); } } TYPED_TEST(RoundRobinTest, RoundRobinDegeneratePartitions11_15) { strings_column_wrapper rrColWrap1({"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}); cudf::size_type inputRows = static_cast<cudf::column_view const&>(rrColWrap1).size(); auto sequence_l = cudf::detail::make_counting_transform_iterator( 0, [bool8 = (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8)](auto row) { return bool8 ? static_cast<decltype(row)>(row % 2 == 0) : row; }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence_l)::value_type> rrColWrap2(sequence_l, sequence_l + inputRows); cudf::table_view rr_view{{rrColWrap1, rrColWrap2}}; cudf::size_type num_partitions = 15; cudf::size_type start_partition = 2; { std::pair<std::unique_ptr<cudf::table>, std::vector<cudf::size_type>> result; EXPECT_NO_THROW(result = cudf::round_robin_partition(rr_view, num_partitions, start_partition)); auto p_outputTable = std::move(result.first); auto output_column_view1{p_outputTable->view().column(0)}; auto output_column_view2{p_outputTable->view().column(1)}; strings_column_wrapper expectedDataWrap1( {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}); auto expected_column_view1{static_cast<cudf::column_view const&>(expectedDataWrap1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view1, output_column_view1); if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { fixed_width_column_wrapper<bool> expectedDataWrap2({1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; EXPECT_EQ(inputRows, expected_column_view2.size()); EXPECT_EQ(inputRows, output_column_view2.size()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } else { fixed_width_column_wrapper<TypeParam, int32_t> expectedDataWrap2( {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } std::vector<cudf::size_type> expected_partition_offsets{ 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11}; EXPECT_EQ(static_cast<std::size_t>(num_partitions), expected_partition_offsets.size()); EXPECT_EQ(expected_partition_offsets, result.second); } start_partition = 10; { std::pair<std::unique_ptr<cudf::table>, std::vector<cudf::size_type>> result; EXPECT_NO_THROW(result = cudf::round_robin_partition(rr_view, num_partitions, start_partition)); auto p_outputTable = std::move(result.first); auto output_column_view1{p_outputTable->view().column(0)}; auto output_column_view2{p_outputTable->view().column(1)}; strings_column_wrapper expectedDataWrap1( {"f", "g", "h", "i", "j", "k", "a", "b", "c", "d", "e"}, {1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1}); auto expected_column_view1{static_cast<cudf::column_view const&>(expectedDataWrap1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view1, output_column_view1); if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { fixed_width_column_wrapper<bool> expectedDataWrap2({0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; EXPECT_EQ(inputRows, expected_column_view2.size()); EXPECT_EQ(inputRows, output_column_view2.size()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } else { fixed_width_column_wrapper<TypeParam, int32_t> expectedDataWrap2( {5, 6, 7, 8, 9, 10, 0, 1, 2, 3, 4}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } std::vector<cudf::size_type> expected_partition_offsets{ 0, 1, 2, 3, 4, 5, 6, 6, 6, 6, 6, 7, 8, 9, 10}; EXPECT_EQ(static_cast<std::size_t>(num_partitions), expected_partition_offsets.size()); EXPECT_EQ(expected_partition_offsets, result.second); } start_partition = 14; { std::pair<std::unique_ptr<cudf::table>, std::vector<cudf::size_type>> result; EXPECT_NO_THROW(result = cudf::round_robin_partition(rr_view, num_partitions, start_partition)); auto p_outputTable = std::move(result.first); auto output_column_view1{p_outputTable->view().column(0)}; auto output_column_view2{p_outputTable->view().column(1)}; strings_column_wrapper expectedDataWrap1( {"b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "a"}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1}); auto expected_column_view1{static_cast<cudf::column_view const&>(expectedDataWrap1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view1, output_column_view1); if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { fixed_width_column_wrapper<bool> expectedDataWrap2({0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; EXPECT_EQ(inputRows, expected_column_view2.size()); EXPECT_EQ(inputRows, output_column_view2.size()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } else { fixed_width_column_wrapper<TypeParam, int32_t> expectedDataWrap2( {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } std::vector<cudf::size_type> expected_partition_offsets{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 10}; EXPECT_EQ(static_cast<std::size_t>(num_partitions), expected_partition_offsets.size()); EXPECT_EQ(expected_partition_offsets, result.second); } } TYPED_TEST(RoundRobinTest, RoundRobinDegeneratePartitions11_11) { strings_column_wrapper rrColWrap1({"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}); cudf::size_type inputRows = static_cast<cudf::column_view const&>(rrColWrap1).size(); auto sequence_l = cudf::detail::make_counting_transform_iterator( 0, [bool8 = (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8)](auto row) { return bool8 ? static_cast<decltype(row)>(row % 2 == 0) : row; }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence_l)::value_type> rrColWrap2(sequence_l, sequence_l + inputRows); cudf::table_view rr_view{{rrColWrap1, rrColWrap2}}; cudf::size_type num_partitions = 11; cudf::size_type start_partition = 2; { std::pair<std::unique_ptr<cudf::table>, std::vector<cudf::size_type>> result; EXPECT_NO_THROW(result = cudf::round_robin_partition(rr_view, num_partitions, start_partition)); auto p_outputTable = std::move(result.first); auto output_column_view1{p_outputTable->view().column(0)}; auto output_column_view2{p_outputTable->view().column(1)}; strings_column_wrapper expectedDataWrap1( {"j", "k", "a", "b", "c", "d", "e", "f", "g", "h", "i"}, {1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1}); auto expected_column_view1{static_cast<cudf::column_view const&>(expectedDataWrap1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view1, output_column_view1); if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { fixed_width_column_wrapper<bool> expectedDataWrap2({0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; EXPECT_EQ(inputRows, expected_column_view2.size()); EXPECT_EQ(inputRows, output_column_view2.size()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } else { fixed_width_column_wrapper<TypeParam, int32_t> expectedDataWrap2( {9, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } std::vector<cudf::size_type> expected_partition_offsets{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; EXPECT_EQ(static_cast<std::size_t>(num_partitions), expected_partition_offsets.size()); EXPECT_EQ(expected_partition_offsets, result.second); } } TYPED_TEST(RoundRobinTest, RoundRobinNPartitionsDivideNRows) { // test the case when nrows `mod` npartitions = 0 // // input: // strings: ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u"], // bools: [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1], // nulls: [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0]) // strings_column_wrapper rrColWrap1( {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u"}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}); cudf::size_type inputRows = static_cast<cudf::column_view const&>(rrColWrap1).size(); auto sequence_l = cudf::detail::make_counting_transform_iterator( 0, [bool8 = (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8)](auto row) { return bool8 ? static_cast<decltype(row)>(row % 2 == 0) : row; }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence_l)::value_type> rrColWrap2(sequence_l, sequence_l + inputRows); cudf::table_view rr_view{{rrColWrap1, rrColWrap2}}; cudf::size_type num_partitions = 3; // expected: // indxs: [0,3,6,9,12,15,18,1,4,7,10,13,16,19,2,5,8,11,14,17,20], // strings: ["a","d","g","j","m","p","s","b","e","h","k","n","q","t","c","f","i","l","o","r","u"], // bools: [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1], // nulls: [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0], // offsets: [0,7,14] // cudf::size_type start_partition = 0; { std::pair<std::unique_ptr<cudf::table>, std::vector<cudf::size_type>> result; EXPECT_NO_THROW(result = cudf::round_robin_partition(rr_view, num_partitions, start_partition)); auto p_outputTable = std::move(result.first); auto output_column_view1{p_outputTable->view().column(0)}; auto output_column_view2{p_outputTable->view().column(1)}; strings_column_wrapper expectedDataWrap1( {"a", "d", "g", "j", "m", "p", "s", "b", "e", "h", "k", "n", "q", "t", "c", "f", "i", "l", "o", "r", "u"}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}); auto expected_column_view1{static_cast<cudf::column_view const&>(expectedDataWrap1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view1, output_column_view1); if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { fixed_width_column_wrapper<bool> expectedDataWrap2( {1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; EXPECT_EQ(inputRows, expected_column_view2.size()); EXPECT_EQ(inputRows, output_column_view2.size()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } else { fixed_width_column_wrapper<TypeParam, int32_t> expectedDataWrap2( {0, 3, 6, 9, 12, 15, 18, 1, 4, 7, 10, 13, 16, 19, 2, 5, 8, 11, 14, 17, 20}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } std::vector<cudf::size_type> expected_partition_offsets{0, 7, 14}; EXPECT_EQ(static_cast<std::size_t>(num_partitions), expected_partition_offsets.size()); EXPECT_EQ(expected_partition_offsets, result.second); } // expected: // indxs: [2,5,8,11,14,17,20,0,3,6,9,12,15,18,1,4,7,10,13,16,19], // strings: ["c","f","i","l","o","r","u","a","d","g","j","m","p","s","b","e","h","k","n","q","t"], // bools: [1,0,1,0,1,0,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0], // nulls: [1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1], // offsets: [0,7,14] // start_partition = 1; { std::pair<std::unique_ptr<cudf::table>, std::vector<cudf::size_type>> result; EXPECT_NO_THROW(result = cudf::round_robin_partition(rr_view, num_partitions, start_partition)); auto p_outputTable = std::move(result.first); auto output_column_view1{p_outputTable->view().column(0)}; auto output_column_view2{p_outputTable->view().column(1)}; strings_column_wrapper expectedDataWrap1( {"c", "f", "i", "l", "o", "r", "u", "a", "d", "g", "j", "m", "p", "s", "b", "e", "h", "k", "n", "q", "t"}, {1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}); auto expected_column_view1{static_cast<cudf::column_view const&>(expectedDataWrap1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view1, output_column_view1); if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { fixed_width_column_wrapper<bool> expectedDataWrap2( {1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; EXPECT_EQ(inputRows, expected_column_view2.size()); EXPECT_EQ(inputRows, output_column_view2.size()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } else { fixed_width_column_wrapper<TypeParam, int32_t> expectedDataWrap2( {2, 5, 8, 11, 14, 17, 20, 0, 3, 6, 9, 12, 15, 18, 1, 4, 7, 10, 13, 16, 19}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } std::vector<cudf::size_type> expected_partition_offsets{0, 7, 14}; EXPECT_EQ(static_cast<std::size_t>(num_partitions), expected_partition_offsets.size()); EXPECT_EQ(expected_partition_offsets, result.second); } } TYPED_TEST(RoundRobinTest, RoundRobinSinglePartition) { strings_column_wrapper rrColWrap1({"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}); cudf::size_type inputRows = static_cast<cudf::column_view const&>(rrColWrap1).size(); auto sequence_l = cudf::detail::make_counting_transform_iterator( 0, [bool8 = (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8)](auto row) { return bool8 ? static_cast<decltype(row)>(row % 2 == 0) : row; }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence_l)::value_type> rrColWrap2(sequence_l, sequence_l + inputRows); cudf::table_view rr_view{{rrColWrap1, rrColWrap2}}; cudf::size_type num_partitions = 1; cudf::size_type start_partition = 0; std::pair<std::unique_ptr<cudf::table>, std::vector<cudf::size_type>> result; EXPECT_NO_THROW(result = cudf::round_robin_partition(rr_view, num_partitions, start_partition)); auto p_outputTable = std::move(result.first); auto output_column_view1{p_outputTable->view().column(0)}; auto output_column_view2{p_outputTable->view().column(1)}; strings_column_wrapper expectedDataWrap1({"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}); auto expected_column_view1{static_cast<cudf::column_view const&>(expectedDataWrap1)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view1, output_column_view1); if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { fixed_width_column_wrapper<bool> expectedDataWrap2({1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; EXPECT_EQ(inputRows, expected_column_view2.size()); EXPECT_EQ(inputRows, output_column_view2.size()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } else { fixed_width_column_wrapper<TypeParam, int32_t> expectedDataWrap2( {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); auto expected_column_view2{static_cast<cudf::column_view const&>(expectedDataWrap2)}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_column_view2, output_column_view2); } std::vector<cudf::size_type> expected_partition_offsets{0}; EXPECT_EQ(static_cast<std::size_t>(num_partitions), expected_partition_offsets.size()); EXPECT_EQ(expected_partition_offsets, result.second); } TYPED_TEST(RoundRobinTest, RoundRobinIncorrectNumPartitions) { strings_column_wrapper rrColWrap1({"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}); cudf::size_type inputRows = static_cast<cudf::column_view const&>(rrColWrap1).size(); auto sequence_l = cudf::detail::make_counting_transform_iterator(0, [](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { return (row % 2 == 0) ? 1 : 0; } else return row; }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence_l)::value_type> rrColWrap2(sequence_l, sequence_l + inputRows); cudf::table_view rr_view{{rrColWrap1, rrColWrap2}}; cudf::size_type num_partitions = 0; cudf::size_type start_partition = 0; EXPECT_THROW(cudf::round_robin_partition(rr_view, num_partitions, start_partition), cudf::logic_error); } TYPED_TEST(RoundRobinTest, RoundRobinIncorrectStartPartition) { strings_column_wrapper rrColWrap1({"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}); cudf::size_type inputRows = static_cast<cudf::column_view const&>(rrColWrap1).size(); auto sequence_l = cudf::detail::make_counting_transform_iterator(0, [](auto row) { if (cudf::type_to_id<TypeParam>() == cudf::type_id::BOOL8) { return (row % 2 == 0) ? 1 : 0; } else return row; }); cudf::test::fixed_width_column_wrapper<TypeParam, typename decltype(sequence_l)::value_type> rrColWrap2(sequence_l, sequence_l + inputRows); cudf::table_view rr_view{{rrColWrap1, rrColWrap2}}; cudf::size_type num_partitions = 4; cudf::size_type start_partition = 5; EXPECT_THROW(cudf::round_robin_partition(rr_view, num_partitions, start_partition), cudf::logic_error); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/text/subword_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/column/column.hpp> #include <cudf/column/column_view.hpp> #include <cudf/strings/strings_column_view.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <nvtext/subword_tokenize.hpp> #include <fstream> #include <iostream> #include <vector> // Global environment for temporary files auto const temp_env = static_cast<cudf::test::TempDirTestEnvironment*>( ::testing::AddGlobalTestEnvironment(new cudf::test::TempDirTestEnvironment)); struct TextSubwordTest : public cudf::test::BaseFixture {}; // Create a fake hashed vocab text file for the tests in this source file. // The vocab only includes the following words: // 'this', 'is', 'a', 'test', 'tést' // The period '.' character also has a token id. void create_hashed_vocab(std::string const& hash_file) { std::vector<std::pair<int, int>> coefficients(23, {65559, 0}); std::ofstream outfile(hash_file, std::ofstream::out); outfile << "1\n0\n" << coefficients.size() << "\n"; for (auto c : coefficients) outfile << c.first << " " << c.second << "\n"; std::vector<uint64_t> hash_table(23, 0); outfile << hash_table.size() << "\n"; hash_table[0] = 3015668L; // based on values hash_table[1] = 6205475701751155871L; // from the hash_table[5] = 6358029; // bert_hash_table.txt hash_table[16] = 451412625363L; // file for the test hash_table[20] = 6206321707968235495L; // words above for (auto h : hash_table) outfile << h << "\n"; outfile << "100\n101\n102\n\n"; } TEST(TextSubwordTest, Tokenize) { uint32_t nrows = 100; std::vector<char const*> h_strings(nrows, "This is a test. A test this is."); cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end()); std::string hash_file = temp_env->get_temp_filepath("hashed_vocab.txt"); create_hashed_vocab(hash_file); auto vocab = nvtext::load_vocabulary_file(hash_file); uint32_t max_sequence_length = 16; uint32_t stride = 16; auto result = nvtext::subword_tokenize(cudf::strings_column_view{strings}, *vocab, max_sequence_length, stride, true, // do_lower_case false); // do_truncate EXPECT_EQ(nrows, result.nrows_tensor); { std::vector<uint32_t> base_data( {2023, 2003, 1037, 3231, 1012, 1037, 3231, 2023, 2003, 1012, 0, 0, 0, 0, 0, 0}); std::vector<uint32_t> h_expected; for (uint32_t idx = 0; idx < nrows; ++idx) h_expected.insert(h_expected.end(), base_data.begin(), base_data.end()); cudf::test::fixed_width_column_wrapper<uint32_t> expected(h_expected.begin(), h_expected.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_token_ids->view(), expected); } { std::vector<uint32_t> base_data({1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0}); std::vector<uint32_t> h_expected; for (uint32_t idx = 0; idx < nrows; ++idx) h_expected.insert(h_expected.end(), base_data.begin(), base_data.end()); cudf::test::fixed_width_column_wrapper<uint32_t> expected(h_expected.begin(), h_expected.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_attention_mask->view(), expected); } { std::vector<uint32_t> h_expected; for (uint32_t idx = 0; idx < nrows; ++idx) { // 0,0,9,1,0,9,2,0,9,3,0,9,4,0,9,5,0,9,6,0,9,7,0,9,8,0,9,9,0,9,... h_expected.push_back(idx); h_expected.push_back(0); h_expected.push_back(9); } cudf::test::fixed_width_column_wrapper<uint32_t> expected(h_expected.begin(), h_expected.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_metadata->view(), expected); } } TEST(TextSubwordTest, TokenizeMultiRow) { std::vector<char const*> h_strings{"This is a test.", "This is a test. This is a tést."}; cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end()); std::string hash_file = temp_env->get_temp_filepath("hashed_vocab.txt"); create_hashed_vocab(hash_file); auto vocab = nvtext::load_vocabulary_file(hash_file); uint32_t max_sequence_length = 8; uint32_t stride = 6; auto result = nvtext::subword_tokenize(cudf::strings_column_view{strings}, *vocab, max_sequence_length, stride, true, // do_lower_case false); // do_truncate EXPECT_EQ(uint32_t{3}, result.nrows_tensor); cudf::test::fixed_width_column_wrapper<uint32_t> expected_tokens( {2023, 2003, 1037, 3231, 1012, 0, 0, 0, 2023, 2003, 1037, 3231, 1012, 2023, 2003, 1037, 2003, 1037, 3231, 1012, 0, 0, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_token_ids->view(), expected_tokens); cudf::test::fixed_width_column_wrapper<uint32_t> expected_attn( {1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_attention_mask->view(), expected_attn); cudf::test::fixed_width_column_wrapper<uint32_t> expected_metadata({0, 0, 4, 1, 0, 6, 1, 1, 3}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_metadata->view(), expected_metadata); } TEST(TextSubwordTest, TokenizeWithEmptyRow) { std::string hash_file = temp_env->get_temp_filepath("hashed_vocab.txt"); create_hashed_vocab(hash_file); auto vocab = nvtext::load_vocabulary_file(hash_file); cudf::test::strings_column_wrapper strings{ "This is a test.", "", "This is a test. This is a tést."}; auto input = cudf::strings_column_view{strings}; uint32_t const max_seq = 8; uint32_t const stride = 6; bool const lower = true; bool const truncate = false; auto result = nvtext::subword_tokenize(input, *vocab, max_seq, stride, lower, truncate); EXPECT_EQ(uint32_t{4}, result.nrows_tensor); // clang-format off auto expected_tokens = cudf::test::fixed_width_column_wrapper<uint32_t>( {2023, 2003, 1037, 3231, 1012, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2023, 2003, 1037, 3231, 1012, 2023, 2003, 1037, // this one 2003, 1037, 3231, 1012, 0, 0, 0, 0}); // continues here // clang-format on CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_token_ids->view(), expected_tokens); // clang-format off auto expected_attn = cudf::test::fixed_width_column_wrapper<uint32_t>( {1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0}); // clang-format on CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_attention_mask->view(), expected_attn); // clang-format off auto expected_metadata = cudf::test::fixed_width_column_wrapper<uint32_t>( {0,0,4, 1,0,0, 2,0,6, 2,1,3}); // note that the 3rd element has 2 tensors // clang-format on CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_metadata->view(), expected_metadata); } TEST(TextSubwordTest, TokenizeMaxEqualsTokens) { cudf::test::strings_column_wrapper strings({"This is a test."}); std::string hash_file = temp_env->get_temp_filepath("hashed_vocab.txt"); create_hashed_vocab(hash_file); auto vocab = nvtext::load_vocabulary_file(hash_file); uint32_t max_sequence_length = 5; // five tokens in strings; uint32_t stride = 5; // this should not effect the result auto result = nvtext::subword_tokenize(cudf::strings_column_view{strings}, *vocab, max_sequence_length, stride, true, // do_lower_case false); // do_truncate EXPECT_EQ(uint32_t{1}, result.nrows_tensor); cudf::test::fixed_width_column_wrapper<uint32_t> expected_tokens({2023, 2003, 1037, 3231, 1012}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_token_ids->view(), expected_tokens); cudf::test::fixed_width_column_wrapper<uint32_t> expected_attn({1, 1, 1, 1, 1}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_attention_mask->view(), expected_attn); cudf::test::fixed_width_column_wrapper<uint32_t> expected_metadata({0, 0, 4}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_metadata->view(), expected_metadata); } TEST(TextSubwordTest, ParameterErrors) { std::vector<char const*> h_strings{"This is a test.", "This is a test. This is a tést.", "", ""}; cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end()); std::string hash_file = temp_env->get_temp_filepath("hashed_vocab.txt"); create_hashed_vocab(hash_file); auto vocab = nvtext::load_vocabulary_file(hash_file); EXPECT_THROW(nvtext::subword_tokenize(cudf::strings_column_view{strings}, *vocab, 12, // max_sequence_length 13, // stride <= max_sequence_length true, // do_lower_case true), // do_truncate cudf::logic_error); EXPECT_THROW(nvtext::subword_tokenize(cudf::strings_column_view{strings}, *vocab, 858993459, 5, true, // do_lower_case true), // do_truncate std::overflow_error); } TEST(TextSubwordTest, EmptyStrings) { cudf::test::strings_column_wrapper strings; std::string hash_file = temp_env->get_temp_filepath("hashed_vocab.txt"); create_hashed_vocab(hash_file); auto vocab = nvtext::load_vocabulary_file(hash_file); auto result = nvtext::subword_tokenize(cudf::strings_column_view{strings}, *vocab, 16, 16, true, // do_lower_case false); // do_truncate EXPECT_EQ(uint32_t{0}, result.nrows_tensor); EXPECT_EQ(0, result.tensor_token_ids->size()); EXPECT_EQ(0, result.tensor_attention_mask->size()); EXPECT_EQ(0, result.tensor_metadata->size()); } TEST(TextSubwordTest, AllNullStrings) { cudf::test::strings_column_wrapper strings({"", "", ""}, {0, 0, 0}); std::string hash_file = temp_env->get_temp_filepath("hashed_vocab.txt"); create_hashed_vocab(hash_file); auto vocab = nvtext::load_vocabulary_file(hash_file); auto result = nvtext::subword_tokenize(cudf::strings_column_view{strings}, *vocab, 16, 16, true, // do_lower_case false); // do_truncate EXPECT_EQ(uint32_t{0}, result.nrows_tensor); EXPECT_EQ(0, result.tensor_token_ids->size()); EXPECT_EQ(0, result.tensor_attention_mask->size()); EXPECT_EQ(0, result.tensor_metadata->size()); } TEST(TextSubwordTest, NoTokens) { std::string hash_file = temp_env->get_temp_filepath("hashed_vocab.txt"); create_hashed_vocab(hash_file); auto vocab = nvtext::load_vocabulary_file(hash_file); cudf::test::strings_column_wrapper strings({" ", "\n\r", "\t"}); auto input = cudf::strings_column_view{strings}; uint32_t const max_seq = 16; uint32_t const stride = 16; bool const lower = true; bool const truncate = true; auto result = nvtext::subword_tokenize(input, *vocab, max_seq, stride, lower, truncate); std::vector<uint32_t> zeros(max_seq * input.size(), 0); EXPECT_EQ(static_cast<uint32_t>(input.size()), result.nrows_tensor); auto expected = cudf::test::fixed_width_column_wrapper<uint32_t>(zeros.begin(), zeros.end()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_token_ids->view(), expected); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_attention_mask->view(), expected); auto expected_metadata = cudf::test::fixed_width_column_wrapper<uint32_t>({0, 0, 0, 1, 0, 0, 2, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_metadata->view(), expected_metadata); } TEST(TextSubwordTest, TokenizeFromVocabStruct) { std::string hash_file = temp_env->get_temp_filepath("hashed_vocab.txt"); create_hashed_vocab(hash_file); std::vector<char const*> h_strings{"This is a test.", "This is a test. This is a tést."}; cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end()); auto vocab = nvtext::load_vocabulary_file(hash_file); auto result = nvtext::subword_tokenize(cudf::strings_column_view{strings}, *vocab, 8, 6, true, // do_lower_case true); // do_truncate EXPECT_EQ(uint32_t{2}, result.nrows_tensor); cudf::test::fixed_width_column_wrapper<uint32_t> expected_tokens( {2023, 2003, 1037, 3231, 1012, 0, 0, 0, 2023, 2003, 1037, 3231, 1012, 2023, 2003, 1037}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_token_ids->view(), expected_tokens); cudf::test::fixed_width_column_wrapper<uint32_t> expected_attn( {1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_attention_mask->view(), expected_attn); cudf::test::fixed_width_column_wrapper<uint32_t> expected_metadata({0, 0, 4, 1, 0, 7}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_metadata->view(), expected_metadata); } TEST(TextSubwordTest, LoadVocabFileErrors) { std::vector<char const*> h_strings{"This is a test.", "This is a test. This is a tést."}; cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end()); std::string hash_file = temp_env->get_temp_filepath("nothing.txt"); EXPECT_THROW(nvtext::load_vocabulary_file(hash_file), cudf::logic_error); } // This includes the words above and 7 special tokens: // [BOS] [EOS] [UNK] [SEP] [PAD] [CLS] [MASK] // The data here was generated by the utility: // cudf.utils.hash_vocab_utils.hash_vocab() void create_special_tokens_hashed_vocab(std::string const& hash_file) { std::ofstream outfile(hash_file, std::ofstream::out); outfile << "26899\n27424\n3\n"; outfile << "1416131940466419714 0\n"; outfile << "313740585393291779 2\n"; outfile << "17006415773850330120 5\n"; outfile << "13\n"; outfile << "5903884228619468800\n"; outfile << "6205475701751152650\n"; outfile << "16285378285009240068\n"; outfile << "5162333542489915397\n"; outfile << "6064762127302393859\n"; outfile << "6173800107753209857\n"; outfile << "5322083323972878342\n"; outfile << "6242701866907861003\n"; outfile << "451412623368\n"; outfile << "3014668\n"; outfile << "5214737420442796034\n"; outfile << "6206321707968233479\n"; outfile << "6357001\n"; outfile << "1\n2\n3\n\n"; } TEST(TextSubwordTest, TokenizeWithSpecialTokens) { std::string hash_file = temp_env->get_temp_filepath("hashed_vocab.txt"); create_special_tokens_hashed_vocab(hash_file); // clang-format off std::vector<const char*> h_strings{ "[BOS]This is a tést.[eos]", "[CLS]A test[SEP]this is.", "[PAD] [A][MASK]", "test this [CL", "S] is a ."}; // clang-format on cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end()); auto vocab = nvtext::load_vocabulary_file(hash_file); auto result = nvtext::subword_tokenize(cudf::strings_column_view{strings}, *vocab, 8, 6, true, // do_lower_case true); // do_truncate EXPECT_EQ(static_cast<uint32_t>(h_strings.size()), result.nrows_tensor); // clang-format off cudf::test::fixed_width_column_wrapper<uint32_t> expected_tokens( { 5, 7, 8, 9, 10, 12, 6, 0, 2, 9, 10, 3, 7, 8, 12, 0, 0, 1, 9, 1, 4, 0, 0, 0, 10, 7, 1, 1, 0, 0, 0, 0, 1, 1, 8, 9, 12, 0, 0, 0}); cudf::test::fixed_width_column_wrapper<uint32_t> expected_attn( {1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0}); cudf::test::fixed_width_column_wrapper<uint32_t> expected_metadata( {0, 0, 6, 1, 0, 6, 2, 0, 4, 3, 0, 3, 4, 0, 4}); // clang-format on CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_token_ids->view(), expected_tokens); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_attention_mask->view(), expected_attn); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_metadata->view(), expected_metadata); } TEST(TextSubwordTest, ZeroHashBinCoefficient) { std::string hash_file = temp_env->get_temp_filepath("hashed_vocab.txt"); { std::ofstream outfile(hash_file, std::ofstream::out); outfile << "26899\n27424\n2\n"; outfile << "6321733446031528966 0\n0 0\n9\n"; // zeroes are here outfile << "6206321707968233475\n3014663\n6205475701751152646\n"; outfile << "451412623364\n5214737420442796033\n6173800107753209856\n"; outfile << "0\n6356997\n6064762127302393858\n"; outfile << "0\n1\n2\n"; } std::vector<char const*> h_strings{".zzzz"}; cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end()); auto vocab = nvtext::load_vocabulary_file(hash_file); auto result = nvtext::subword_tokenize(cudf::strings_column_view{strings}, *vocab, 8, 8, true, // do_lower_case true); // do_truncate // clang-format off cudf::test::fixed_width_column_wrapper<uint32_t> expected_tokens({7, 0, 0, 0, 0, 0, 0, 0}); cudf::test::fixed_width_column_wrapper<uint32_t> expected_attn( {1, 1, 0, 0, 0, 0, 0, 0}); cudf::test::fixed_width_column_wrapper<uint32_t> expected_metadata({0, 0, 1}); // clang-format on CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_token_ids->view(), expected_tokens); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_attention_mask->view(), expected_attn); CUDF_TEST_EXPECT_COLUMNS_EQUAL(result.tensor_metadata->view(), expected_metadata); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/text/stemmer_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/column/column.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/strings/strings_column_view.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <nvtext/stemmer.hpp> #include <thrust/iterator/transform_iterator.h> #include <vector> struct TextStemmerTest : public cudf::test::BaseFixture {}; TEST_F(TextStemmerTest, PorterStemmer) { std::vector<char const*> h_strings{"abandon", nullptr, "abbey", "cleans", "trouble", "", "yearly", "tree", "y", "by", "oats", "ivy", "private", "orrery"}; auto validity = thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }); cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end(), validity); cudf::test::fixed_width_column_wrapper<int32_t> expected( {3, 0, 2, 1, 1, 0, 1, 0, 0, 0, 1, 1, 2, 2}, validity); auto const results = nvtext::porter_stemmer_measure(cudf::strings_column_view(strings)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } TEST_F(TextStemmerTest, IsLetterIndex) { std::vector<char const*> h_strings{"abandon", nullptr, "abbey", "cleans", "trouble", "", "yearly", "tree", "y", "by", "oats", "ivy", "private", "orrery"}; auto validity = thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }); cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end(), validity); cudf::strings_column_view sv(strings); { auto const results = nvtext::is_letter(sv, nvtext::letter_type::VOWEL, 0); cudf::test::fixed_width_column_wrapper<bool> expected( {1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1}, validity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } { auto const results = nvtext::is_letter(sv, nvtext::letter_type::CONSONANT, 0); cudf::test::fixed_width_column_wrapper<bool> expected( {0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0}, validity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } { auto const results = nvtext::is_letter(sv, nvtext::letter_type::VOWEL, 5); cudf::test::fixed_width_column_wrapper<bool> expected( {1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1}, validity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } { auto const results = nvtext::is_letter(sv, nvtext::letter_type::CONSONANT, 5); cudf::test::fixed_width_column_wrapper<bool> expected( {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0}, validity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } { auto const results = nvtext::is_letter(sv, nvtext::letter_type::VOWEL, -2); cudf::test::fixed_width_column_wrapper<bool> expected( {1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0}, validity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } { auto const results = nvtext::is_letter(sv, nvtext::letter_type::CONSONANT, -2); cudf::test::fixed_width_column_wrapper<bool> expected( {0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1}, validity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } } TEST_F(TextStemmerTest, IsLetterIndices) { std::vector<char const*> h_strings{"abandon", nullptr, "abbey", "cleans", "trouble", "", "yearly", "tree", "y", "by", "oats", "ivy", "private", "orrery"}; auto validity = thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; }); cudf::test::strings_column_wrapper strings(h_strings.begin(), h_strings.end(), validity); cudf::test::fixed_width_column_wrapper<int32_t> indices( {0, 1, 2, 3, 4, 5, 4, 3, 2, 1, -1, -2, -3, -4}); cudf::strings_column_view sv(strings); { auto const results = nvtext::is_letter(sv, nvtext::letter_type::VOWEL, indices); cudf::test::fixed_width_column_wrapper<bool> expected( {1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0}, validity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } { auto const results = nvtext::is_letter(sv, nvtext::letter_type::CONSONANT, indices); cudf::test::fixed_width_column_wrapper<bool> expected( {0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1}, validity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } } TEST_F(TextStemmerTest, EmptyTest) { auto strings = cudf::make_empty_column(cudf::data_type{cudf::type_id::STRING}); cudf::strings_column_view sv(strings->view()); auto results = nvtext::porter_stemmer_measure(sv); EXPECT_EQ(results->size(), 0); results = nvtext::is_letter(sv, nvtext::letter_type::CONSONANT, 0); EXPECT_EQ(results->size(), 0); auto indices = cudf::make_empty_column(cudf::data_type{cudf::type_id::INT32}); results = nvtext::is_letter(sv, nvtext::letter_type::VOWEL, indices->view()); EXPECT_EQ(results->size(), 0); } TEST_F(TextStemmerTest, ErrorTest) { auto empty = cudf::make_empty_column(cudf::data_type{cudf::type_id::STRING}); cudf::test::fixed_width_column_wrapper<int32_t> indices({0}, {0}); EXPECT_THROW(nvtext::is_letter( cudf::strings_column_view(empty->view()), nvtext::letter_type::VOWEL, indices), cudf::logic_error); cudf::test::strings_column_wrapper strings({"abc"}); EXPECT_THROW( nvtext::is_letter(cudf::strings_column_view(strings), nvtext::letter_type::VOWEL, indices), cudf::logic_error); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/text/edit_distance_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/column/column.hpp> #include <cudf/strings/strings_column_view.hpp> #include <nvtext/edit_distance.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <thrust/iterator/transform_iterator.h> #include <vector> struct TextEditDistanceTest : public cudf::test::BaseFixture {}; TEST_F(TextEditDistanceTest, EditDistance) { std::vector<char const*> h_strings{"dog", nullptr, "cat", "mouse", "pup", "", "puppy", "thé"}; cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(), thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; })); std::vector<char const*> h_targets{"hog", "not", "cake", "house", "fox", nullptr, "puppy", "the"}; cudf::test::strings_column_wrapper targets( h_targets.begin(), h_targets.end(), thrust::make_transform_iterator(h_targets.begin(), [](auto str) { return str != nullptr; })); { auto results = nvtext::edit_distance(cudf::strings_column_view(strings), cudf::strings_column_view(targets)); cudf::test::fixed_width_column_wrapper<int32_t> expected({1, 3, 2, 1, 3, 0, 0, 1}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } { cudf::test::strings_column_wrapper single({"pup"}); auto results = nvtext::edit_distance(cudf::strings_column_view(strings), cudf::strings_column_view(single)); cudf::test::fixed_width_column_wrapper<int32_t> expected({3, 3, 3, 4, 0, 3, 2, 3}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } } TEST_F(TextEditDistanceTest, EditDistanceMatrix) { std::vector<char const*> h_strings{"dog", nullptr, "hog", "frog", "cat", "", "hat", "clog"}; cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(), thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; })); { auto results = nvtext::edit_distance_matrix(cudf::strings_column_view(strings)); using LCW = cudf::test::lists_column_wrapper<int32_t>; LCW expected({LCW{0, 3, 1, 2, 3, 3, 3, 2}, LCW{3, 0, 3, 4, 3, 0, 3, 4}, LCW{1, 3, 0, 2, 3, 3, 2, 2}, LCW{2, 4, 2, 0, 4, 4, 4, 2}, LCW{3, 3, 3, 4, 0, 3, 1, 3}, LCW{3, 0, 3, 4, 3, 0, 3, 4}, LCW{3, 3, 2, 4, 1, 3, 0, 4}, LCW{2, 4, 2, 2, 3, 4, 4, 0}}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } } TEST_F(TextEditDistanceTest, EmptyTest) { auto strings = cudf::make_empty_column(cudf::data_type{cudf::type_id::STRING}); cudf::strings_column_view strings_view(strings->view()); auto results = nvtext::edit_distance(strings_view, strings_view); EXPECT_EQ(results->size(), 0); results = nvtext::edit_distance_matrix(strings_view); EXPECT_EQ(results->size(), 0); } TEST_F(TextEditDistanceTest, ErrorsTest) { cudf::test::strings_column_wrapper strings({"pup"}); cudf::test::strings_column_wrapper targets({"pup", ""}); EXPECT_THROW( nvtext::edit_distance(cudf::strings_column_view(strings), cudf::strings_column_view(targets)), cudf::logic_error); EXPECT_THROW(nvtext::edit_distance_matrix(cudf::strings_column_view(strings)), cudf::logic_error); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/text/ngrams_tokenize_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf/column/column.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/strings/strings_column_view.hpp> #include <nvtext/ngrams_tokenize.hpp> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <thrust/iterator/transform_iterator.h> #include <vector> struct TextNgramsTokenizeTest : public cudf::test::BaseFixture {}; TEST_F(TextNgramsTokenizeTest, Tokenize) { std::vector<char const*> h_strings{"the fox jumped over the dog", "the dog chased the cat", " the cat chased the mouse ", nullptr, "", "the mousé ate the cheese"}; cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(), thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; })); cudf::strings_column_view strings_view(strings); { cudf::test::strings_column_wrapper expected{"the_fox", "fox_jumped", "jumped_over", "over_the", "the_dog", "the_dog", "dog_chased", "chased_the", "the_cat", "the_cat", "cat_chased", "chased_the", "the_mouse", "the_mousé", "mousé_ate", "ate_the", "the_cheese"}; auto results = nvtext::ngrams_tokenize(strings_view, 2, std::string(), std::string("_")); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } { cudf::test::strings_column_wrapper expected{"the:fox:jumped", "fox:jumped:over", "jumped:over:the", "over:the:dog", "the:dog:chased", "dog:chased:the", "chased:the:cat", "the:cat:chased", "cat:chased:the", "chased:the:mouse", "the:mousé:ate", "mousé:ate:the", "ate:the:cheese"}; auto results = nvtext::ngrams_tokenize(strings_view, 3, std::string{" "}, std::string{":"}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } { cudf::test::strings_column_wrapper expected{"the--fox--jumped--over", "fox--jumped--over--the", "jumped--over--the--dog", "the--dog--chased--the", "dog--chased--the--cat", "the--cat--chased--the", "cat--chased--the--mouse", "the--mousé--ate--the", "mousé--ate--the--cheese"}; auto results = nvtext::ngrams_tokenize(strings_view, 4, std::string{" "}, std::string{"--"}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } } TEST_F(TextNgramsTokenizeTest, TokenizeOneGram) { cudf::test::strings_column_wrapper strings{"aaa bbb", " ccc ddd ", "eee"}; cudf::strings_column_view strings_view(strings); auto const empty = cudf::string_scalar(""); cudf::test::strings_column_wrapper expected{"aaa", "bbb", "ccc", "ddd", "eee"}; auto results = nvtext::ngrams_tokenize(strings_view, 1, empty, empty); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } TEST_F(TextNgramsTokenizeTest, TokenizeEmptyTest) { auto strings = cudf::make_empty_column(cudf::data_type{cudf::type_id::STRING}); cudf::strings_column_view strings_view(strings->view()); auto const empty = cudf::string_scalar(""); auto results = nvtext::ngrams_tokenize(strings_view, 2, empty, empty); EXPECT_EQ(results->size(), 0); EXPECT_EQ(results->has_nulls(), false); } TEST_F(TextNgramsTokenizeTest, TokenizeErrorTest) { cudf::test::strings_column_wrapper strings{"this column intentionally left blank"}; cudf::strings_column_view strings_view(strings); auto const empty = cudf::string_scalar(""); EXPECT_THROW(nvtext::ngrams_tokenize(strings_view, 0, empty, empty), cudf::logic_error); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/text/ngrams_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf/column/column.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/strings/strings_column_view.hpp> #include <nvtext/generate_ngrams.hpp> #include <thrust/iterator/transform_iterator.h> #include <vector> struct TextGenerateNgramsTest : public cudf::test::BaseFixture {}; TEST_F(TextGenerateNgramsTest, Ngrams) { cudf::test::strings_column_wrapper strings{"the", "fox", "jumped", "over", "thé", "dog"}; cudf::strings_column_view strings_view(strings); auto const separator = cudf::string_scalar("_"); { cudf::test::strings_column_wrapper expected{ "the_fox", "fox_jumped", "jumped_over", "over_thé", "thé_dog"}; auto const results = nvtext::generate_ngrams(strings_view, 2, separator); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } { cudf::test::strings_column_wrapper expected{ "the_fox_jumped", "fox_jumped_over", "jumped_over_thé", "over_thé_dog"}; auto const results = nvtext::generate_ngrams(strings_view, 3, separator); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } { cudf::test::strings_column_wrapper expected{"th", "he", "fo", "ox", "ju", "um", "mp", "pe", "ed", "ov", "ve", "er", "th", "hé", "do", "og"}; auto const results = nvtext::generate_character_ngrams(strings_view, 2); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } { cudf::test::strings_column_wrapper expected{ "the", "fox", "jum", "ump", "mpe", "ped", "ove", "ver", "thé", "dog"}; auto const results = nvtext::generate_character_ngrams(strings_view, 3); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } } TEST_F(TextGenerateNgramsTest, NgramsWithNulls) { std::vector<char const*> h_strings{"the", "fox", "", "jumped", "over", nullptr, "the", "dog"}; cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(), thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; })); auto const separator = cudf::string_scalar("_"); cudf::strings_column_view strings_view(strings); { auto const results = nvtext::generate_ngrams(strings_view, 3, separator); cudf::test::strings_column_wrapper expected{ "the_fox_jumped", "fox_jumped_over", "jumped_over_the", "over_the_dog"}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } { cudf::test::strings_column_wrapper expected{ "the", "fox", "jum", "ump", "mpe", "ped", "ove", "ver", "the", "dog"}; auto const results = nvtext::generate_character_ngrams(strings_view, 3); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } } TEST_F(TextGenerateNgramsTest, Empty) { auto const zero_size_strings_column = cudf::make_empty_column(cudf::type_id::STRING)->view(); auto const separator = cudf::string_scalar("_"); auto results = nvtext::generate_ngrams(cudf::strings_column_view(zero_size_strings_column), 2, separator); cudf::test::expect_column_empty(results->view()); results = nvtext::generate_character_ngrams(cudf::strings_column_view(zero_size_strings_column)); cudf::test::expect_column_empty(results->view()); } TEST_F(TextGenerateNgramsTest, Errors) { cudf::test::strings_column_wrapper strings{""}; auto const separator = cudf::string_scalar("_"); // invalid parameter value EXPECT_THROW(nvtext::generate_ngrams(cudf::strings_column_view(strings), 1, separator), cudf::logic_error); EXPECT_THROW(nvtext::generate_character_ngrams(cudf::strings_column_view(strings), 1), cudf::logic_error); // not enough strings to generate ngrams EXPECT_THROW(nvtext::generate_ngrams(cudf::strings_column_view(strings), 3, separator), cudf::logic_error); EXPECT_THROW(nvtext::generate_character_ngrams(cudf::strings_column_view(strings), 3), cudf::logic_error); cudf::test::strings_column_wrapper strings_no_tokens({"", "", "", ""}, {1, 0, 1, 0}); EXPECT_THROW(nvtext::generate_ngrams(cudf::strings_column_view(strings_no_tokens), 2, separator), cudf::logic_error); EXPECT_THROW(nvtext::generate_character_ngrams(cudf::strings_column_view(strings_no_tokens)), cudf::logic_error); } TEST_F(TextGenerateNgramsTest, NgramsHash) { auto input = cudf::test::strings_column_wrapper({"the quick brown fox", "jumped over the lazy dog."}); auto view = cudf::strings_column_view(input); auto results = nvtext::hash_character_ngrams(view); using LCW = cudf::test::lists_column_wrapper<uint32_t>; // clang-format off LCW expected({LCW{2169381797u, 3924065905u, 1634753325u, 3766025829u, 771291085u, 2286480985u, 2815102125u, 2383213292u, 1587939873u, 3417728802u, 741580288u, 1721912990u, 3322339040u, 2530504717u, 1448945146u}, LCW{3542029734u, 2351937583u, 2373822151u, 2610417165u, 1303810911u, 2541942822u, 1736466351u, 3466558519u, 408633648u, 1698719372u, 620653030u, 16851044u, 608863326u, 948572753u, 3672211877u, 4097451013u, 1444462157u, 3762829398u, 743082018u, 2953783152u, 2319357747u}}); // clang-format on CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } TEST_F(TextGenerateNgramsTest, NgramsHashErrors) { auto input = cudf::test::strings_column_wrapper({"1", "2", "3"}); auto view = cudf::strings_column_view(input); // invalid parameter value EXPECT_THROW(nvtext::hash_character_ngrams(view, 1), cudf::logic_error); // strings not long enough to generate ngrams EXPECT_THROW(nvtext::hash_character_ngrams(view), cudf::logic_error); } CUDF_TEST_PROGRAM_MAIN()
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/text/minhash_tests.cpp
/* * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <nvtext/minhash.hpp> #include <cudf/column/column.hpp> #include <cudf/strings/strings_column_view.hpp> #include <cudf/utilities/span.hpp> #include <rmm/cuda_stream_view.hpp> #include <rmm/device_uvector.hpp> #include <vector> struct MinHashTest : public cudf::test::BaseFixture {}; TEST_F(MinHashTest, Basic) { auto validity = cudf::test::iterators::null_at(1); auto input = cudf::test::strings_column_wrapper({"doc 1", "", "this is doc 2", "", "doc 3", "d", "The quick brown fox jumpéd over the lazy brown dog."}, validity); auto view = cudf::strings_column_view(input); auto results = nvtext::minhash(view); auto expected = cudf::test::fixed_width_column_wrapper<uint32_t>( {1207251914u, 0u, 21141582u, 0u, 1207251914u, 655955059u, 86520422u}, validity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); auto results64 = nvtext::minhash64(view); auto expected64 = cudf::test::fixed_width_column_wrapper<uint64_t>({774489391575805754ul, 0ul, 3232308021562742685ul, 0ul, 13145552576991307582ul, 14660046701545912182ul, 398062025280761388ul}, validity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results64, expected64); } TEST_F(MinHashTest, LengthEqualsWidth) { auto input = cudf::test::strings_column_wrapper({"abcdé", "fghjk", "lmnop", "qrstu", "vwxyz"}); auto view = cudf::strings_column_view(input); auto results = nvtext::minhash(view, 0, 5); auto expected = cudf::test::fixed_width_column_wrapper<uint32_t>( {3825281041u, 2728681928u, 1984332911u, 3965004915u, 192452857u}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } TEST_F(MinHashTest, MultiSeed) { auto input = cudf::test::strings_column_wrapper({"doc 1", "this is doc 2", "doc 3", "d", "The quick brown fox jumpéd over the lazy brown dog."}); auto view = cudf::strings_column_view(input); auto seeds = cudf::test::fixed_width_column_wrapper<uint32_t>({0, 1, 2}); auto results = nvtext::minhash(view, cudf::column_view(seeds)); using LCW = cudf::test::lists_column_wrapper<uint32_t>; // clang-format off LCW expected({LCW{1207251914u, 1677652962u, 1061355987u}, LCW{ 21141582u, 580916568u, 1258052021u}, LCW{1207251914u, 943567174u, 1109272887u}, LCW{ 655955059u, 488346356u, 2394664816u}, LCW{ 86520422u, 236622901u, 102546228u}}); // clang-format on CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); auto seeds64 = cudf::test::fixed_width_column_wrapper<uint64_t>({0, 1, 2}); auto results64 = nvtext::minhash64(view, cudf::column_view(seeds64)); using LCW64 = cudf::test::lists_column_wrapper<uint64_t>; // clang-format off LCW64 expected64({LCW64{ 774489391575805754ul, 10435654231793485448ul, 1188598072697676120ul}, LCW64{ 3232308021562742685ul, 4445611509348165860ul, 1188598072697676120ul}, LCW64{13145552576991307582ul, 6846192680998069919ul, 1188598072697676120ul}, LCW64{14660046701545912182ul, 17106501326045553694ul, 17713478494106035784ul}, LCW64{ 398062025280761388ul, 377720198157450084ul, 984941365662009329ul}}); // clang-format on CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results64, expected64); } TEST_F(MinHashTest, MultiSeedWithNullInputRow) { auto validity = cudf::test::iterators::null_at(1); auto input = cudf::test::strings_column_wrapper({"abcdéfgh", "", "", "stuvwxyz"}, validity); auto view = cudf::strings_column_view(input); auto seeds = cudf::test::fixed_width_column_wrapper<uint32_t>({1, 2}); auto results = nvtext::minhash(view, cudf::column_view(seeds)); using LCW = cudf::test::lists_column_wrapper<uint32_t>; LCW expected({LCW{484984072u, 1074168784u}, LCW{}, LCW{0u, 0u}, LCW{571652169u, 173528385u}}, validity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); auto seeds64 = cudf::test::fixed_width_column_wrapper<uint64_t>({11, 22}); auto results64 = nvtext::minhash64(view, cudf::column_view(seeds64)); using LCW64 = cudf::test::lists_column_wrapper<uint64_t>; LCW64 expected64({LCW64{2597399324547032480ul, 4461410998582111052ul}, LCW64{}, LCW64{0ul, 0ul}, LCW64{2717781266371273264ul, 6977325820868387259ul}}, validity); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results64, expected64); } TEST_F(MinHashTest, EmptyTest) { auto input = cudf::make_empty_column(cudf::data_type{cudf::type_id::STRING}); auto view = cudf::strings_column_view(input->view()); auto results = nvtext::minhash(view); EXPECT_EQ(results->size(), 0); results = nvtext::minhash64(view); EXPECT_EQ(results->size(), 0); } TEST_F(MinHashTest, ErrorsTest) { auto input = cudf::test::strings_column_wrapper({"this string intentionally left blank"}); auto view = cudf::strings_column_view(input); EXPECT_THROW(nvtext::minhash(view, 0, 0), std::invalid_argument); EXPECT_THROW(nvtext::minhash64(view, 0, 0), std::invalid_argument); auto seeds = cudf::test::fixed_width_column_wrapper<uint32_t>(); EXPECT_THROW(nvtext::minhash(view, cudf::column_view(seeds)), std::invalid_argument); auto seeds64 = cudf::test::fixed_width_column_wrapper<uint64_t>(); EXPECT_THROW(nvtext::minhash64(view, cudf::column_view(seeds64)), std::invalid_argument); std::vector<std::string> h_input(50000, ""); input = cudf::test::strings_column_wrapper(h_input.begin(), h_input.end()); view = cudf::strings_column_view(input); auto const zeroes = thrust::constant_iterator<uint32_t>(0); seeds = cudf::test::fixed_width_column_wrapper<uint32_t>(zeroes, zeroes + 50000); EXPECT_THROW(nvtext::minhash(view, cudf::column_view(seeds)), std::overflow_error); seeds64 = cudf::test::fixed_width_column_wrapper<uint64_t>(zeroes, zeroes + 50000); EXPECT_THROW(nvtext::minhash64(view, cudf::column_view(seeds64)), std::overflow_error); }
0
rapidsai_public_repos/cudf/cpp/tests
rapidsai_public_repos/cudf/cpp/tests/text/tokenize_tests.cpp
/* * Copyright (c) 2020-2023, NVIDIA CORPORATION. * * Licensed 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 <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/iterator_utilities.hpp> #include <nvtext/tokenize.hpp> #include <cudf/column/column.hpp> #include <cudf/scalar/scalar.hpp> #include <cudf/strings/strings_column_view.hpp> #include <thrust/iterator/transform_iterator.h> #include <vector> struct TextTokenizeTest : public cudf::test::BaseFixture {}; TEST_F(TextTokenizeTest, Tokenize) { std::vector<char const*> h_strings{"the fox jumped over the dog", "the dog chased the cat", " the cat chased the mouse ", nullptr, "", "the mousé ate the cheese"}; cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(), thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; })); cudf::strings_column_view strings_view(strings); cudf::test::strings_column_wrapper expected{ "the", "fox", "jumped", "over", "the", "dog", "the", "dog", "chased", "the", "cat", "the", "cat", "chased", "the", "mouse", "the", "mousé", "ate", "the", "cheese"}; auto results = nvtext::tokenize(strings_view, cudf::string_scalar(" ")); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); results = nvtext::tokenize(strings_view); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); cudf::test::fixed_width_column_wrapper<int32_t> expected_counts{6, 5, 5, 0, 0, 5}; results = nvtext::count_tokens(strings_view, cudf::string_scalar(": #")); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_counts); results = nvtext::count_tokens(strings_view); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_counts); } TEST_F(TextTokenizeTest, TokenizeMulti) { std::vector<char const*> h_strings{"the fox jumped over the dog", "the dog chased the cat", "the cat chased the mouse ", nullptr, "", "the over ", "the mousé ate the cheese"}; cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(), thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; })); cudf::strings_column_view strings_view(strings); cudf::test::strings_column_wrapper delimiters{"the ", "over "}; cudf::strings_column_view delimiters_view(delimiters); auto results = nvtext::tokenize(strings_view, delimiters_view); cudf::test::strings_column_wrapper expected{ "fox jumped ", "dog", "dog chased ", "cat", "cat chased ", "mouse ", "mousé ate ", "cheese"}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); cudf::test::fixed_width_column_wrapper<int32_t> expected_counts{2, 2, 2, 0, 0, 0, 2}; results = nvtext::count_tokens(strings_view, delimiters_view); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected_counts); } TEST_F(TextTokenizeTest, TokenizeErrorTest) { cudf::test::strings_column_wrapper strings{"this column intentionally left blank"}; cudf::strings_column_view strings_view(strings); { cudf::test::strings_column_wrapper delimiters; // empty delimiters cudf::strings_column_view delimiters_view(delimiters); EXPECT_THROW(nvtext::tokenize(strings_view, delimiters_view), cudf::logic_error); EXPECT_THROW(nvtext::count_tokens(strings_view, delimiters_view), cudf::logic_error); } { cudf::test::strings_column_wrapper delimiters({"", ""}, {0, 0}); // null delimiters cudf::strings_column_view delimiters_view(delimiters); EXPECT_THROW(nvtext::tokenize(strings_view, delimiters_view), cudf::logic_error); EXPECT_THROW(nvtext::count_tokens(strings_view, delimiters_view), cudf::logic_error); } } TEST_F(TextTokenizeTest, CharacterTokenize) { std::vector<char const*> h_strings{"the mousé ate the cheese", nullptr, ""}; cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(), thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; })); cudf::test::strings_column_wrapper expected{"t", "h", "e", " ", "m", "o", "u", "s", "é", " ", "a", "t", "e", " ", "t", "h", "e", " ", "c", "h", "e", "e", "s", "e"}; auto results = nvtext::character_tokenize(cudf::strings_column_view(strings)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } TEST_F(TextTokenizeTest, TokenizeEmptyTest) { auto input = cudf::make_empty_column(cudf::data_type{cudf::type_id::STRING}); auto view = cudf::strings_column_view(input->view()); cudf::test::strings_column_wrapper all_empty_wrapper({"", "", ""}); auto all_empty = cudf::strings_column_view(all_empty_wrapper); cudf::test::strings_column_wrapper all_null_wrapper({"", "", ""}, {0, 0, 0}); auto all_null = cudf::strings_column_view(all_null_wrapper); cudf::test::fixed_width_column_wrapper<cudf::size_type> expected({0, 0, 0}); auto results = nvtext::tokenize(view); EXPECT_EQ(results->size(), 0); results = nvtext::tokenize(all_empty); EXPECT_EQ(results->size(), 0); results = nvtext::tokenize(all_null); EXPECT_EQ(results->size(), 0); results = nvtext::count_tokens(view); EXPECT_EQ(results->size(), 0); results = nvtext::count_tokens(all_empty); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); results = nvtext::count_tokens(cudf::strings_column_view(all_null)); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); results = nvtext::character_tokenize(view); EXPECT_EQ(results->size(), 0); results = nvtext::character_tokenize(all_empty); EXPECT_EQ(results->size(), 0); results = nvtext::character_tokenize(all_null); EXPECT_EQ(results->size(), 0); auto const delimiter = cudf::string_scalar{""}; results = nvtext::tokenize_with_vocabulary(view, all_empty, delimiter); EXPECT_EQ(results->size(), 0); results = nvtext::tokenize_with_vocabulary(all_null, all_empty, delimiter); EXPECT_EQ(results->size(), results->null_count()); } TEST_F(TextTokenizeTest, Detokenize) { cudf::test::strings_column_wrapper strings{ "the", "fox", "jumped", "over", "the", "dog", "the", "dog", "chased", "the", "cat", "the", "cat", "chased", "the", "mouse", "the", "mousé", "ate", "cheese"}; { cudf::test::fixed_width_column_wrapper<int32_t> rows{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3}; auto results = nvtext::detokenize(cudf::strings_column_view(strings), rows); cudf::test::strings_column_wrapper expected{"the fox jumped over the dog", "the dog chased the cat", "the cat chased the mouse", "the mousé ate cheese"}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } { cudf::test::fixed_width_column_wrapper<int16_t> rows{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 0}; auto results = nvtext::detokenize(cudf::strings_column_view(strings), rows, cudf::string_scalar("_")); cudf::test::strings_column_wrapper expected{"the_fox_jumped_over_the_dog_cheese", "the_dog_chased_the_cat", "the_cat_chased_the_mouse", "the_mousé_ate"}; CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); } } TEST_F(TextTokenizeTest, DetokenizeErrors) { cudf::test::strings_column_wrapper strings{"this column intentionally left blank"}; cudf::strings_column_view strings_view(strings); cudf::test::fixed_width_column_wrapper<int32_t> one({0}); cudf::test::fixed_width_column_wrapper<int32_t> none; EXPECT_THROW(nvtext::detokenize(strings_view, none), cudf::logic_error); EXPECT_THROW(nvtext::detokenize(strings_view, one, cudf::string_scalar("", false)), cudf::logic_error); } TEST_F(TextTokenizeTest, Vocabulary) { cudf::test::strings_column_wrapper vocabulary( // leaving out 'cat' on purpose {"ate", "chased", "cheese", "dog", "fox", "jumped", "mouse", "mousé", "over", "the"}); auto vocab = nvtext::load_vocabulary(cudf::strings_column_view(vocabulary)); auto validity = cudf::test::iterators::null_at(5); auto input = cudf::test::strings_column_wrapper({" the fox jumped over the dog ", " the dog chased the cat", "", "the cat chased the mouse ", "the mousé ate cheese", "", "dog"}, validity); auto input_view = cudf::strings_column_view(input); auto delimiter = cudf::string_scalar(" "); auto default_id = -7; // should be the token for the missing 'cat' auto results = nvtext::tokenize_with_vocabulary(input_view, *vocab, delimiter, default_id); using LCW = cudf::test::lists_column_wrapper<cudf::size_type>; // clang-format off LCW expected({LCW{ 9, 4, 5, 8, 9, 3}, LCW{ 9, 3, 1, 9,-7}, LCW{}, LCW{ 9,-7, 1, 9, 6}, LCW{ 9, 7, 0, 2}, LCW{}, LCW{3}}, validity); // clang-format on CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); auto sliced = cudf::slice(input, {1, 4}).front(); auto sliced_expected = cudf::slice(expected, {1, 4}).front(); input_view = cudf::strings_column_view(sliced); results = nvtext::tokenize_with_vocabulary(input_view, *vocab, delimiter, default_id); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), sliced_expected); } TEST_F(TextTokenizeTest, VocabularyLongStrings) { cudf::test::strings_column_wrapper vocabulary( {"ate", "chased", "cheese", "dog", "fox", "jumped", "mouse", "mousé", "over", "the"}); auto vocab = nvtext::load_vocabulary(cudf::strings_column_view(vocabulary)); std::vector<std::string> h_strings( 4, "the fox jumped chased the dog cheese mouse at the over there dog mouse cat plus the horse " "jumped over the mousé house with the dog "); cudf::test::strings_column_wrapper input(h_strings.begin(), h_strings.end()); auto input_view = cudf::strings_column_view(input); auto delimiter = cudf::string_scalar(" "); auto default_id = -1; auto results = nvtext::tokenize_with_vocabulary(input_view, *vocab, delimiter, default_id); using LCW = cudf::test::lists_column_wrapper<cudf::size_type>; // clang-format off LCW expected({LCW{ 9, 4, 5, 1, 9, 3, 2, 6, -1, 9, 8, -1, 3, 6, -1, -1, 9, -1, 5, 8, 9, 7, -1, -1, 9, 3}, LCW{ 9, 4, 5, 1, 9, 3, 2, 6, -1, 9, 8, -1, 3, 6, -1, -1, 9, -1, 5, 8, 9, 7, -1, -1, 9, 3}, LCW{ 9, 4, 5, 1, 9, 3, 2, 6, -1, 9, 8, -1, 3, 6, -1, -1, 9, -1, 5, 8, 9, 7, -1, -1, 9, 3}, LCW{ 9, 4, 5, 1, 9, 3, 2, 6, -1, 9, 8, -1, 3, 6, -1, -1, 9, -1, 5, 8, 9, 7, -1, -1, 9, 3}}); // clang-format on CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected); auto sliced = cudf::slice(input, {1, 3}).front(); auto sliced_expected = cudf::slice(expected, {1, 3}).front(); input_view = cudf::strings_column_view(sliced); results = nvtext::tokenize_with_vocabulary(input_view, *vocab, delimiter, default_id); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(results->view(), sliced_expected); } TEST_F(TextTokenizeTest, TokenizeErrors) { cudf::test::strings_column_wrapper empty{}; cudf::strings_column_view view(empty); EXPECT_THROW(nvtext::load_vocabulary(view), cudf::logic_error); cudf::test::strings_column_wrapper vocab_nulls({""}, {0}); cudf::strings_column_view nulls(vocab_nulls); EXPECT_THROW(nvtext::load_vocabulary(nulls), cudf::logic_error); cudf::test::strings_column_wrapper some{"hello"}; auto vocab = nvtext::load_vocabulary(cudf::strings_column_view(some)); EXPECT_THROW(nvtext::tokenize_with_vocabulary(view, *vocab, cudf::string_scalar("", false)), cudf::logic_error); }
0